feat(domain): equine legacy importer (packages/anatomy) + generated official equine sheet seed as draft
This commit is contained in:
1 parent
f4682cdba5
commit
52bfc11553
43 files changed
+18466
-33
No files matched your search
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Generates supabase/seed/anatomical-sheets/equine/v1/ from the legacy
|
||||
* equine sources: canonical draft document, legacy id map, import report,
|
||||
* byte-identical SVG assets with their manifest, and the SQL seed.
|
||||
*
|
||||
* pnpm import:equine (from the repository root)
|
||||
*
|
||||
* Output is byte-identical across runs; commit it and review the report.
|
||||
*/
|
||||
import { copyFile, mkdir, writeFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import {
|
||||
EQUINE_SEED_DIR,
|
||||
EQUINE_SOURCE_PATHS,
|
||||
importEquineLegacy,
|
||||
readEquineSources,
|
||||
renderArtifacts,
|
||||
} from '../legacy'
|
||||
|
||||
const REPO_ROOT = fileURLToPath(new URL('../../../../', import.meta.url))
|
||||
|
||||
async function writeTextArtifacts(dir: string, files: Record<string, string>) {
|
||||
for (const [name, text] of Object.entries(files)) {
|
||||
await writeFile(join(dir, name), text, 'utf8')
|
||||
}
|
||||
}
|
||||
|
||||
async function copyAssets(dir: string): Promise<void> {
|
||||
const assetsDir = join(dir, 'assets')
|
||||
await mkdir(assetsDir, { recursive: true })
|
||||
for (const source of [
|
||||
EQUINE_SOURCE_PATHS.mainSvg,
|
||||
EQUINE_SOURCE_PATHS.headSvg,
|
||||
]) {
|
||||
const name = source.slice(source.lastIndexOf('/') + 1)
|
||||
await copyFile(join(REPO_ROOT, source), join(assetsDir, name))
|
||||
}
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const result = importEquineLegacy(await readEquineSources(REPO_ROOT))
|
||||
const dir = join(REPO_ROOT, EQUINE_SEED_DIR)
|
||||
await mkdir(dir, { recursive: true })
|
||||
await writeTextArtifacts(dir, await renderArtifacts(result))
|
||||
await copyAssets(dir)
|
||||
const errors = result.issues.filter((i) => i.severity === 'error').length
|
||||
console.log(
|
||||
`${EQUINE_SEED_DIR}: ${result.stats.annotations} annotations, ` +
|
||||
`${result.stats.nodes} nodes, ${result.anomalies.length} anomalies, ` +
|
||||
`${errors} integrity errors, ${result.issues.length - errors} warnings`,
|
||||
)
|
||||
}
|
||||
|
||||
main().catch((error: unknown) => {
|
||||
console.error(error instanceof Error ? error.message : error)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -0,0 +1 @@
|
||||
export * from './legacy'
|
||||
@@ -0,0 +1,180 @@
|
||||
import type { Annotation, Geometry, Laterality } from '@faunosteo/domain'
|
||||
import { normaliseCategoryId } from './categories'
|
||||
import { slugify } from './ids'
|
||||
import { inferRegionCode } from './regions'
|
||||
import type { LegacyAnnotation } from './svg'
|
||||
import type { Anomaly, AnnotationRow, RegionInference } from './types'
|
||||
|
||||
/**
|
||||
* Legacy SVG annotation → canonical annotation. The finding zone link is
|
||||
* resolved here, once, by exact FR + EN equality with the catalog (audit 06
|
||||
* §4); the document then carries finding_zone_id explicitly and nothing
|
||||
* matches labels at runtime.
|
||||
*/
|
||||
|
||||
export interface AnnotationContext {
|
||||
viewId: string
|
||||
fileName: string
|
||||
/** `${name_fr}\n${name_en}` → catalog zone key. */
|
||||
zoneByNames: ReadonlyMap<string, string>
|
||||
}
|
||||
|
||||
export interface MappedAnnotation {
|
||||
annotation: Annotation
|
||||
row: AnnotationRow
|
||||
region: RegionInference | null
|
||||
anomalies: Anomaly[]
|
||||
}
|
||||
|
||||
export function zoneNameKey(fr: string, en: string): string {
|
||||
return `${fr}\n${en}`
|
||||
}
|
||||
|
||||
function anomaly(code: string, subject: string, message: string): Anomaly {
|
||||
return { code, level: 'a_valider', subject, message }
|
||||
}
|
||||
|
||||
function laterality(a: LegacyAnnotation, out: Anomaly[]): Laterality {
|
||||
if (a.lateral === 'bilateral') return 'bilateral'
|
||||
if (a.lateral === null || a.lateral === 'unpaired') return 'unpaired'
|
||||
out.push(
|
||||
anomaly(
|
||||
'annotation.laterality.unknown',
|
||||
a.id,
|
||||
`Latéralité « ${a.lateral} » inconnue, importée en « unpaired ».`,
|
||||
),
|
||||
)
|
||||
return 'unpaired'
|
||||
}
|
||||
|
||||
function describeGeometry(geometry: Geometry | null): string {
|
||||
if (geometry === null) return 'aucune'
|
||||
if (geometry.type === 'circle') {
|
||||
return `cercle (${geometry.cx}, ${geometry.cy}) r ${geometry.r}`
|
||||
}
|
||||
if (geometry.type === 'polygon') {
|
||||
return `polygone ${geometry.points.length} points`
|
||||
}
|
||||
return 'chemin'
|
||||
}
|
||||
|
||||
function regionOf(a: LegacyAnnotation, out: Anomaly[]): RegionInference | null {
|
||||
if (a.special === null) return null
|
||||
if (a.special !== 'vertebral-precision') {
|
||||
out.push(
|
||||
anomaly(
|
||||
'annotation.special.unknown',
|
||||
a.id,
|
||||
`special « ${a.special} » ignoré.`,
|
||||
),
|
||||
)
|
||||
return null
|
||||
}
|
||||
const match = inferRegionCode(a.nameFr, a.nameEn)
|
||||
if (!match) {
|
||||
out.push(
|
||||
anomaly(
|
||||
'annotation.region.unknown',
|
||||
a.id,
|
||||
'Région vertébrale non déduite.',
|
||||
),
|
||||
)
|
||||
}
|
||||
return {
|
||||
annotationId: a.id,
|
||||
label: match?.label ?? a.nameFr ?? a.nameEn ?? a.id,
|
||||
root: match?.root ?? null,
|
||||
code: match?.code ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
function triggerName(a: LegacyAnnotation, out: Anomaly[]) {
|
||||
if (a.nameFr && a.nameEn) return { fr: a.nameFr, en: a.nameEn }
|
||||
out.push({
|
||||
code: 'annotation.trigger.unnamed',
|
||||
level: 'informatif',
|
||||
subject: a.id,
|
||||
message:
|
||||
'Déclencheur de vue détail sans nom (name null), comme dans le SVG.',
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
function mapTrigger(
|
||||
a: LegacyAnnotation,
|
||||
ctx: AnnotationContext,
|
||||
out: Anomaly[],
|
||||
) {
|
||||
const annotation: Annotation = {
|
||||
id: `${a.opensDetail}-trigger`,
|
||||
kind: 'detail_trigger',
|
||||
view_id: ctx.viewId,
|
||||
category_id: normaliseCategoryId(a.category ?? ''),
|
||||
laterality: laterality(a, out),
|
||||
geometry: a.geometry,
|
||||
name: triggerName(a, out),
|
||||
opens_view_id: a.opensDetail ?? '',
|
||||
}
|
||||
return { annotation, region: null }
|
||||
}
|
||||
|
||||
function observableName(a: LegacyAnnotation) {
|
||||
const fr = a.nameFr ?? a.nameEn ?? a.id
|
||||
return { fr, en: a.nameEn ?? fr }
|
||||
}
|
||||
|
||||
function mapObservable(
|
||||
a: LegacyAnnotation,
|
||||
ctx: AnnotationContext,
|
||||
out: Anomaly[],
|
||||
) {
|
||||
const name = observableName(a)
|
||||
const zoneId = ctx.zoneByNames.get(zoneNameKey(name.fr, name.en)) ?? null
|
||||
if (zoneId === null) {
|
||||
out.push(
|
||||
anomaly(
|
||||
'annotation.unmapped',
|
||||
a.id,
|
||||
'Annotation non reliée à une zone de constats.',
|
||||
),
|
||||
)
|
||||
}
|
||||
const region = regionOf(a, out)
|
||||
const annotation: Annotation = {
|
||||
id: zoneId ?? slugify(name.en),
|
||||
kind: a.tagName === 'circle' ? 'point' : 'zone',
|
||||
view_id: ctx.viewId,
|
||||
category_id: normaliseCategoryId(a.category ?? ''),
|
||||
laterality: laterality(a, out),
|
||||
geometry: a.geometry,
|
||||
name,
|
||||
finding_zone_id: zoneId,
|
||||
vertebral_region_code: region?.code ?? null,
|
||||
}
|
||||
return { annotation, region }
|
||||
}
|
||||
|
||||
export function mapAnnotation(
|
||||
a: LegacyAnnotation,
|
||||
ctx: AnnotationContext,
|
||||
): MappedAnnotation {
|
||||
const anomalies: Anomaly[] = []
|
||||
const { annotation, region } = a.opensDetail
|
||||
? mapTrigger(a, ctx, anomalies)
|
||||
: mapObservable(a, ctx, anomalies)
|
||||
const row: AnnotationRow = {
|
||||
legacyId: a.id,
|
||||
newId: annotation.id,
|
||||
viewId: ctx.viewId,
|
||||
kind: annotation.kind,
|
||||
laterality: annotation.laterality,
|
||||
regionCode:
|
||||
annotation.kind === 'detail_trigger'
|
||||
? null
|
||||
: annotation.vertebral_region_code,
|
||||
findingZoneId:
|
||||
annotation.kind === 'detail_trigger' ? null : annotation.finding_zone_id,
|
||||
geometry: describeGeometry(annotation.geometry),
|
||||
}
|
||||
return { annotation, row, region, anomalies }
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { format } from 'prettier'
|
||||
import { renderImportReport } from './report'
|
||||
import { renderSeedSql } from './seed'
|
||||
import type { ImportResult } from './types'
|
||||
|
||||
/**
|
||||
* Text artifacts of the generated seed folder, keyed by path relative to
|
||||
* supabase/seed/anatomical-sheets/equine/v1/. JSON and Markdown go
|
||||
* through Prettier with the repository options so `prettier --check`
|
||||
* accepts the committed files as generated (no exclusion needed).
|
||||
*/
|
||||
|
||||
export const SEED_SQL_FILE = 'equine_v1.sql'
|
||||
|
||||
const PRETTIER_OPTIONS = {
|
||||
semi: false,
|
||||
singleQuote: true,
|
||||
tabWidth: 2,
|
||||
useTabs: false,
|
||||
trailingComma: 'all',
|
||||
printWidth: 80,
|
||||
bracketSpacing: true,
|
||||
arrowParens: 'always',
|
||||
endOfLine: 'lf',
|
||||
} as const
|
||||
|
||||
function formatJson(value: unknown): Promise<string> {
|
||||
return format(JSON.stringify(value, null, 2), {
|
||||
...PRETTIER_OPTIONS,
|
||||
parser: 'json',
|
||||
})
|
||||
}
|
||||
|
||||
/** Deterministic: same result in, same bytes out. */
|
||||
export async function renderArtifacts(
|
||||
result: ImportResult,
|
||||
): Promise<Record<string, string>> {
|
||||
const documentJson = await formatJson(result.document)
|
||||
return {
|
||||
'document.json': documentJson,
|
||||
'legacy-id-map.json': await formatJson(result.legacyIdMap),
|
||||
'assets.json': await formatJson(result.assets),
|
||||
'IMPORT-REPORT.md': await format(renderImportReport(result), {
|
||||
...PRETTIER_OPTIONS,
|
||||
parser: 'markdown',
|
||||
}),
|
||||
[SEED_SQL_FILE]: renderSeedSql({ result, documentJson }),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { LegacyCatalog, LegacyNode } from './catalog'
|
||||
import type { Anomaly } from './types'
|
||||
|
||||
/**
|
||||
* Catalog-wide findings that need a business decision or an explanation.
|
||||
* Nothing here alters the data: the importer copies the catalog verbatim
|
||||
* and these checks only describe what a reviewer must know.
|
||||
*/
|
||||
|
||||
const PREFIXED = /^(.+)-(dysfunctions|observations)$/
|
||||
|
||||
/** A prefixed category id that names another zone (sphenoid → ssb-…). */
|
||||
function foreignPrefixAnomalies(catalog: LegacyCatalog): Anomaly[] {
|
||||
const zoneIds = Object.keys(catalog.zones)
|
||||
const out: Anomaly[] = []
|
||||
for (const [zoneId, zone] of Object.entries(catalog.zones)) {
|
||||
for (const category of zone.categories) {
|
||||
const match = PREFIXED.exec(category.id)
|
||||
if (!match || match[1] === zoneId || !zoneIds.includes(match[1]!))
|
||||
continue
|
||||
out.push({
|
||||
code: 'finding.category.foreign_prefix',
|
||||
level: 'a_valider',
|
||||
subject: `${zoneId}/${category.id}`,
|
||||
message:
|
||||
`Identifiant de catégorie dupliqué entre ${zoneId} et ${match[1]} ; ` +
|
||||
`${zoneId}-${match[2]} attendu ; décision ostéopathe requise. ` +
|
||||
'Importé tel quel (non renommé).',
|
||||
})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function childIds(category: LegacyNode): string {
|
||||
return (category.children ?? []).map((c) => c.id).join(', ')
|
||||
}
|
||||
|
||||
/** Same 'anamnesis' id everywhere, different content per zone family. */
|
||||
function anamnesisVariants(catalog: LegacyCatalog): Anomaly[] {
|
||||
const variants = new Map<string, string[]>()
|
||||
for (const [zoneId, zone] of Object.entries(catalog.zones)) {
|
||||
const category = zone.categories.find((c) => c.id === 'anamnesis')
|
||||
if (!category) continue
|
||||
const key = childIds(category)
|
||||
variants.set(key, [...(variants.get(key) ?? []), zoneId])
|
||||
}
|
||||
return [...variants.entries()].map(([children, zones], index) => ({
|
||||
code: 'finding.anamnesis.variant',
|
||||
level: 'informatif',
|
||||
subject: `anamnesis variante ${index + 1}/${variants.size}`,
|
||||
message: `Zones ${zones.join(', ')} : ${children}.`,
|
||||
}))
|
||||
}
|
||||
|
||||
function collectIds(nodes: readonly LegacyNode[], into: Set<string>): void {
|
||||
for (const node of nodes) {
|
||||
into.add(node.id)
|
||||
collectIds(node.children ?? [], into)
|
||||
}
|
||||
}
|
||||
|
||||
/** Node ids are unique among siblings only; a finding is (zone, path). */
|
||||
function crossZoneDuplicates(catalog: LegacyCatalog): Anomaly[] {
|
||||
const zonesById = new Map<string, number>()
|
||||
for (const zone of Object.values(catalog.zones)) {
|
||||
const ids = new Set<string>()
|
||||
collectIds(zone.categories, ids)
|
||||
for (const id of ids) zonesById.set(id, (zonesById.get(id) ?? 0) + 1)
|
||||
}
|
||||
const shared = [...zonesById.entries()].filter(([, n]) => n > 1)
|
||||
const top = [...shared].sort(
|
||||
(a, b) => b[1] - a[1] || a[0].localeCompare(b[0]),
|
||||
)
|
||||
return [
|
||||
{
|
||||
code: 'finding.id.shared_across_zones',
|
||||
level: 'informatif',
|
||||
subject: `${shared.length} identifiants`,
|
||||
message:
|
||||
'Identifiants de nœuds réutilisés entre zones (unicité entre frères ' +
|
||||
'seulement, adressage par zone + chemin). Les plus fréquents : ' +
|
||||
top
|
||||
.slice(0, 8)
|
||||
.map(([id, n]) => `${id} (${n})`)
|
||||
.join(', ') +
|
||||
'.',
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
export function catalogAnomalies(catalog: LegacyCatalog): Anomaly[] {
|
||||
return [
|
||||
...foreignPrefixAnomalies(catalog),
|
||||
...anamnesisVariants(catalog),
|
||||
...crossZoneDuplicates(catalog),
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import type {
|
||||
FindingCategoryKind,
|
||||
FindingNodeInput,
|
||||
LocalizedOptionalText,
|
||||
SourceRef,
|
||||
} from '@faunosteo/domain'
|
||||
import { isStableId, slugify } from './ids'
|
||||
import type { Anomaly, ZoneStats } from './types'
|
||||
|
||||
/**
|
||||
* Legacy findings catalog (pathologies.json, schema 2.0) → canonical
|
||||
* finding zones in the lean authoring form: optional keys are written only
|
||||
* when the source carries them, so the document stays as small as the
|
||||
* catalog and the parser fills the defaults.
|
||||
*/
|
||||
|
||||
export interface LegacyNode {
|
||||
id: string
|
||||
name_fr: string
|
||||
name_en: string
|
||||
description_fr?: string
|
||||
description_en?: string
|
||||
requires_vet_referral?: boolean
|
||||
sources?: SourceRef[]
|
||||
children?: LegacyNode[]
|
||||
}
|
||||
|
||||
export interface LegacyZone {
|
||||
id: string
|
||||
name_fr: string
|
||||
name_en: string
|
||||
categories: LegacyNode[]
|
||||
}
|
||||
|
||||
export interface LegacyCatalog {
|
||||
schema_version: string
|
||||
scope_disclaimer?: string
|
||||
species?: { id: string; name_fr: string; name_en: string }
|
||||
zones: Record<string, LegacyZone>
|
||||
}
|
||||
|
||||
export interface CategoryInput {
|
||||
id: string
|
||||
kind: FindingCategoryKind
|
||||
name: { fr: string; en: string }
|
||||
description?: LocalizedOptionalText
|
||||
children: FindingNodeInput[]
|
||||
}
|
||||
|
||||
export interface ZoneInput {
|
||||
id: string
|
||||
name: { fr: string; en: string }
|
||||
categories: CategoryInput[]
|
||||
}
|
||||
|
||||
export interface MappedCatalog {
|
||||
zones: ZoneInput[]
|
||||
zoneStats: ZoneStats[]
|
||||
nodeIdMap: Record<string, string>
|
||||
missingDescriptionEn: number
|
||||
sources: number
|
||||
anomalies: Anomaly[]
|
||||
}
|
||||
|
||||
/** Mutable tallies of one catalog walk; never shared between runs. */
|
||||
interface WalkState {
|
||||
nodeIdMap: Record<string, string>
|
||||
anomalies: Anomaly[]
|
||||
missingDescriptionEn: number
|
||||
sources: number
|
||||
}
|
||||
|
||||
export function parseLegacyCatalog(json: string): LegacyCatalog {
|
||||
const catalog = JSON.parse(json) as LegacyCatalog
|
||||
if (typeof catalog?.zones !== 'object' || catalog.zones === null) {
|
||||
throw new Error('pathologies.json: "zones" object missing')
|
||||
}
|
||||
return catalog
|
||||
}
|
||||
|
||||
export function categoryKind(categoryId: string): FindingCategoryKind {
|
||||
if (categoryId.endsWith('-dysfunctions')) return 'dysfunction'
|
||||
if (categoryId.endsWith('-observations')) return 'consultation_reason'
|
||||
if (categoryId === 'anamnesis') return 'anamnesis'
|
||||
return 'custom'
|
||||
}
|
||||
|
||||
function description(node: LegacyNode): LocalizedOptionalText | undefined {
|
||||
if (node.description_fr === undefined && node.description_en === undefined) {
|
||||
return undefined
|
||||
}
|
||||
const text: LocalizedOptionalText = {}
|
||||
if (node.description_fr !== undefined) text.fr = node.description_fr
|
||||
if (node.description_en !== undefined) text.en = node.description_en
|
||||
return text
|
||||
}
|
||||
|
||||
function stableNodeId(id: string, path: string[], state: WalkState): string {
|
||||
if (isStableId(id)) return id
|
||||
const next = slugify(id) || 'node'
|
||||
const key = [...path, id].join('/')
|
||||
state.nodeIdMap[key] = next
|
||||
state.anomalies.push({
|
||||
code: 'finding.id.slugified',
|
||||
level: 'a_valider',
|
||||
subject: key,
|
||||
message: `Identifiant hors motif stable, remplacé par « ${next} ».`,
|
||||
})
|
||||
return next
|
||||
}
|
||||
|
||||
function tallyNode(node: LegacyNode, state: WalkState): void {
|
||||
if (node.description_fr !== undefined && node.description_en === undefined) {
|
||||
state.missingDescriptionEn += 1
|
||||
}
|
||||
state.sources += node.sources?.length ?? 0
|
||||
}
|
||||
|
||||
function mapNode(
|
||||
node: LegacyNode,
|
||||
path: string[],
|
||||
state: WalkState,
|
||||
): FindingNodeInput {
|
||||
tallyNode(node, state)
|
||||
const id = stableNodeId(node.id, path, state)
|
||||
const out: FindingNodeInput = {
|
||||
id,
|
||||
name: { fr: node.name_fr, en: node.name_en },
|
||||
}
|
||||
const text = description(node)
|
||||
if (text) out.description = text
|
||||
if (node.requires_vet_referral === true) out.requires_vet_referral = true
|
||||
if (node.sources) out.sources = node.sources.map((s) => ({ ...s }))
|
||||
if (node.children) {
|
||||
out.children = node.children.map((c) =>
|
||||
mapNode(c, [...path, node.id], state),
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function mapCategory(
|
||||
zoneId: string,
|
||||
category: LegacyNode,
|
||||
state: WalkState,
|
||||
): CategoryInput {
|
||||
tallyNode(category, state)
|
||||
const kind = categoryKind(category.id)
|
||||
if (kind === 'custom') {
|
||||
state.anomalies.push({
|
||||
code: 'finding.category.kind_unknown',
|
||||
level: 'a_valider',
|
||||
subject: `${zoneId}/${category.id}`,
|
||||
message: 'Type de catégorie non reconnu, importé en « custom ».',
|
||||
})
|
||||
}
|
||||
const path = [zoneId, category.id]
|
||||
const out: CategoryInput = {
|
||||
id: stableNodeId(category.id, [zoneId], state),
|
||||
kind,
|
||||
name: { fr: category.name_fr, en: category.name_en },
|
||||
children: (category.children ?? []).map((c) => mapNode(c, path, state)),
|
||||
}
|
||||
const text = description(category)
|
||||
if (text) out.description = text
|
||||
return out
|
||||
}
|
||||
|
||||
/** Counts categories as nodes, as the audit does (792 = 78 + 714). */
|
||||
export function countTree(
|
||||
nodes: ReadonlyArray<LegacyNode | FindingNodeInput>,
|
||||
): {
|
||||
nodes: number
|
||||
leaves: number
|
||||
vetReferrals: number
|
||||
} {
|
||||
let total = { nodes: 0, leaves: 0, vetReferrals: 0 }
|
||||
for (const node of nodes) {
|
||||
const children = node.children ?? []
|
||||
const sub = countTree(children)
|
||||
total = {
|
||||
nodes: total.nodes + 1 + sub.nodes,
|
||||
leaves: total.leaves + sub.leaves + (children.length === 0 ? 1 : 0),
|
||||
vetReferrals:
|
||||
total.vetReferrals +
|
||||
sub.vetReferrals +
|
||||
(node.requires_vet_referral ? 1 : 0),
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
function zoneStatsOf(zone: LegacyZone): ZoneStats {
|
||||
const counts = countTree(zone.categories)
|
||||
const categoryLeaves = zone.categories.filter((c) => !c.children?.length)
|
||||
return {
|
||||
zoneId: zone.id,
|
||||
nodes: counts.nodes,
|
||||
leaves: counts.leaves - categoryLeaves.length,
|
||||
vetReferrals: counts.vetReferrals,
|
||||
}
|
||||
}
|
||||
|
||||
/** Throws when the output tree does not hold exactly the input nodes. */
|
||||
function assertNothingDropped(zone: LegacyZone, mapped: ZoneInput): void {
|
||||
const before = countTree(zone.categories)
|
||||
const after = countTree(mapped.categories)
|
||||
if (before.nodes !== after.nodes || before.leaves !== after.leaves) {
|
||||
throw new Error(
|
||||
`zone ${zone.id}: ${before.nodes} nodes in, ${after.nodes} out`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function mapZone(key: string, zone: LegacyZone, state: WalkState): ZoneInput {
|
||||
if (zone.id !== key) throw new Error(`zone key ${key} ≠ id ${zone.id}`)
|
||||
const mapped: ZoneInput = {
|
||||
id: key,
|
||||
name: { fr: zone.name_fr, en: zone.name_en },
|
||||
categories: zone.categories.map((c) => mapCategory(key, c, state)),
|
||||
}
|
||||
assertNothingDropped(zone, mapped)
|
||||
return mapped
|
||||
}
|
||||
|
||||
export function mapCatalog(catalog: LegacyCatalog): MappedCatalog {
|
||||
const state: WalkState = {
|
||||
nodeIdMap: {},
|
||||
anomalies: [],
|
||||
missingDescriptionEn: 0,
|
||||
sources: 0,
|
||||
}
|
||||
const entries = Object.entries(catalog.zones)
|
||||
return {
|
||||
zones: entries.map(([key, zone]) => mapZone(key, zone, state)),
|
||||
zoneStats: entries.map(([, zone]) => zoneStatsOf(zone)),
|
||||
nodeIdMap: state.nodeIdMap,
|
||||
missingDescriptionEn: state.missingDescriptionEn,
|
||||
sources: state.sources,
|
||||
anomalies: state.anomalies,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import type { AnnotationCategory } from '@faunosteo/domain'
|
||||
import type { LegacyAnnotation } from './svg'
|
||||
import type { Anomaly } from './types'
|
||||
|
||||
/**
|
||||
* SVG annotation categories → canonical categories. The legacy editor
|
||||
* slugified labels byte-wise, so accented letters became '-'
|
||||
* ("Charnières vertébrales" → charni-res-vert-brales). Those technical
|
||||
* slugs are normalised here and every change is reported; labels the
|
||||
* importer had to write are reported as "to validate".
|
||||
*/
|
||||
|
||||
/** Degraded legacy slug → real slug. Other slugs are kept as they are. */
|
||||
const SLUG_FIXES: Readonly<Record<string, string>> = {
|
||||
'charni-res-vert-brales': 'charnieres-vertebrales',
|
||||
'cadrans-du-cr-ne': 'cadrans-du-crane',
|
||||
}
|
||||
|
||||
/** Labels authored by the importer, keyed by normalised slug. */
|
||||
const LABELS: Readonly<Record<string, { fr: string; en: string }>> = {
|
||||
articulations: { fr: 'Articulations', en: 'Joints' },
|
||||
os: { fr: 'Os', en: 'Bones' },
|
||||
'zone-colonne': { fr: 'Zone colonne', en: 'Spine' },
|
||||
'charnieres-vertebrales': {
|
||||
fr: 'Charnières vertébrales',
|
||||
en: 'Vertebral hinges',
|
||||
},
|
||||
'cadrans-du-crane': { fr: 'Cadrans du crâne', en: 'Skull quadrants' },
|
||||
}
|
||||
|
||||
export interface MappedCategories {
|
||||
categories: AnnotationCategory[]
|
||||
idMap: Record<string, string>
|
||||
anomalies: Anomaly[]
|
||||
}
|
||||
|
||||
export function normaliseCategoryId(legacy: string): string {
|
||||
return SLUG_FIXES[legacy] ?? legacy
|
||||
}
|
||||
|
||||
/**
|
||||
* data-anno-category-name is used only when it is a real label: in the
|
||||
* equine SVGs it repeats the slug ("articulations", "os"), so the readable
|
||||
* label of the table wins and the report says so.
|
||||
*/
|
||||
function frenchName(legacy: string, categoryName: string | null): string {
|
||||
const id = normaliseCategoryId(legacy)
|
||||
if (categoryName && categoryName !== legacy) return categoryName
|
||||
return LABELS[id]?.fr ?? id
|
||||
}
|
||||
|
||||
function labelAnomaly(id: string, fr: string, en: string): Anomaly {
|
||||
return {
|
||||
code: 'category.label.authored',
|
||||
level: 'a_valider',
|
||||
subject: id,
|
||||
message: `Libellé écrit par l'importateur : FR « ${fr} », EN « ${en} ».`,
|
||||
}
|
||||
}
|
||||
|
||||
function slugAnomaly(legacy: string, id: string): Anomaly {
|
||||
return {
|
||||
code: 'category.slug.normalised',
|
||||
level: 'a_valider',
|
||||
subject: legacy,
|
||||
message: `Slug technique dégradé (accents perdus) normalisé en « ${id} ».`,
|
||||
}
|
||||
}
|
||||
|
||||
function firstSeen(annotations: readonly LegacyAnnotation[]) {
|
||||
const seen = new Map<string, string | null>()
|
||||
for (const a of annotations) {
|
||||
if (a.category === null) continue
|
||||
if (!seen.has(a.category) || seen.get(a.category) === null) {
|
||||
seen.set(a.category, a.categoryName)
|
||||
}
|
||||
}
|
||||
return seen
|
||||
}
|
||||
|
||||
/** Categories in order of first appearance across the SVGs. */
|
||||
export function mapCategories(
|
||||
annotations: readonly LegacyAnnotation[],
|
||||
): MappedCategories {
|
||||
const result: MappedCategories = { categories: [], idMap: {}, anomalies: [] }
|
||||
for (const [legacy, categoryName] of firstSeen(annotations)) {
|
||||
const id = normaliseCategoryId(legacy)
|
||||
const name = {
|
||||
fr: frenchName(legacy, categoryName),
|
||||
en: LABELS[id]?.en ?? id,
|
||||
}
|
||||
result.categories.push({ id, name, color: null })
|
||||
result.idMap[legacy] = id
|
||||
if (id !== legacy) result.anomalies.push(slugAnomaly(legacy, id))
|
||||
result.anomalies.push(labelAnomaly(id, name.fr, name.en))
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { STABLE_ID_PATTERN } from '@faunosteo/domain'
|
||||
|
||||
/**
|
||||
* Deterministic identifiers. The importer must produce byte-identical
|
||||
* output across runs, so nothing here is random or time-based.
|
||||
*
|
||||
* UUIDs are name-based in the RFC 4122 version 5 style, with SHA-256 in
|
||||
* place of SHA-1: the first 16 bytes of sha256(<namespace string>), the
|
||||
* version nibble forced to 5 and the variant bits to 10xx. Assets use
|
||||
* 'faunosteo:asset:' + the file's sha256 (same bytes, same id), the sheet
|
||||
* uses 'faunosteo:sheet:<species>:v<n>'.
|
||||
*/
|
||||
|
||||
export function sha256Hex(data: Uint8Array | string): string {
|
||||
return createHash('sha256').update(data).digest('hex')
|
||||
}
|
||||
|
||||
export function deterministicUuid(name: string): string {
|
||||
const bytes = createHash('sha256').update(name).digest().subarray(0, 16)
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x50
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
||||
const hex = bytes.toString('hex')
|
||||
return [
|
||||
hex.slice(0, 8),
|
||||
hex.slice(8, 12),
|
||||
hex.slice(12, 16),
|
||||
hex.slice(16, 20),
|
||||
hex.slice(20, 32),
|
||||
].join('-')
|
||||
}
|
||||
|
||||
export function assetIdFromSha256(fileSha256: string): string {
|
||||
return deterministicUuid(`faunosteo:asset:${fileSha256}`)
|
||||
}
|
||||
|
||||
export function sheetIdFor(speciesId: string, version: number): string {
|
||||
return deterministicUuid(`faunosteo:sheet:${speciesId}:v${version}`)
|
||||
}
|
||||
|
||||
/** Lowercase, accents stripped (NFD), every other run of chars → '-'. */
|
||||
export function slugify(label: string): string {
|
||||
return label
|
||||
.normalize('NFD')
|
||||
.replace(/[̀-ͯ]/g, '')
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 64)
|
||||
}
|
||||
|
||||
export function isStableId(id: string): boolean {
|
||||
return STABLE_ID_PATTERN.test(id)
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
import {
|
||||
AnatomicalSheetDocumentSchema,
|
||||
SHEET_DOCUMENT_SCHEMA_VERSION,
|
||||
validateSheetDocument,
|
||||
type AnatomicalSheetDocumentInput,
|
||||
type Annotation,
|
||||
type SheetView,
|
||||
} from '@faunosteo/domain'
|
||||
import {
|
||||
mapAnnotation,
|
||||
zoneNameKey,
|
||||
type MappedAnnotation,
|
||||
} from './annotations'
|
||||
import {
|
||||
mapCatalog,
|
||||
parseLegacyCatalog,
|
||||
type LegacyCatalog,
|
||||
type MappedCatalog,
|
||||
} from './catalog'
|
||||
import { catalogAnomalies } from './catalog-checks'
|
||||
import { mapCategories, type MappedCategories } from './categories'
|
||||
import { assetIdFromSha256, sha256Hex, sheetIdFor } from './ids'
|
||||
import { parseAnnotatedSvg, type ParsedSvg } from './svg'
|
||||
import type {
|
||||
Anomaly,
|
||||
AssetRecord,
|
||||
EquineLegacyInput,
|
||||
ImportResult,
|
||||
ImportStats,
|
||||
LegacyIdMap,
|
||||
SourceDigest,
|
||||
SvgSource,
|
||||
} from './types'
|
||||
import {
|
||||
parseVertebralFormula,
|
||||
vertebralRegions,
|
||||
type LegacyVertebralFormula,
|
||||
} from './vertebrae'
|
||||
|
||||
/**
|
||||
* One-off, deterministic import of the historical equine assets into the
|
||||
* first canonical anatomical sheet document (Step 4b). The result is a
|
||||
* DRAFT for business review: every correction is listed in `anomalies`,
|
||||
* nothing is published.
|
||||
*/
|
||||
|
||||
export const EQUINE_SPECIES_ID = 'equine'
|
||||
export const EQUINE_SHEET_VERSION = 1
|
||||
export const MAIN_VIEW_ID = 'main'
|
||||
export const HEAD_VIEW_ID = 'head'
|
||||
|
||||
interface ParsedSources {
|
||||
assets: AssetRecord[]
|
||||
main: ParsedSvg
|
||||
head: ParsedSvg
|
||||
catalog: LegacyCatalog
|
||||
formula: LegacyVertebralFormula
|
||||
}
|
||||
|
||||
interface Mapped {
|
||||
annotations: MappedAnnotation[]
|
||||
categories: MappedCategories
|
||||
catalog: MappedCatalog
|
||||
}
|
||||
|
||||
function assetRecord(source: SvgSource): AssetRecord {
|
||||
const sha256 = sha256Hex(source.bytes)
|
||||
return {
|
||||
file: source.fileName,
|
||||
sha256,
|
||||
byte_size: source.bytes.byteLength,
|
||||
svg_asset_id: assetIdFromSha256(sha256),
|
||||
}
|
||||
}
|
||||
|
||||
function textDigest(file: string, text: string): SourceDigest {
|
||||
const bytes = new TextEncoder().encode(text)
|
||||
return { file, sha256: sha256Hex(bytes), byte_size: bytes.byteLength }
|
||||
}
|
||||
|
||||
function svgText(source: SvgSource): string {
|
||||
return new TextDecoder('utf-8', { fatal: true }).decode(source.bytes)
|
||||
}
|
||||
|
||||
function parseSources(input: EquineLegacyInput): ParsedSources {
|
||||
return {
|
||||
assets: [assetRecord(input.mainSvg), assetRecord(input.headSvg)],
|
||||
main: parseAnnotatedSvg(svgText(input.mainSvg), input.mainSvg.fileName),
|
||||
head: parseAnnotatedSvg(svgText(input.headSvg), input.headSvg.fileName),
|
||||
catalog: parseLegacyCatalog(input.catalogJson),
|
||||
formula: parseVertebralFormula(input.vertebraeSource),
|
||||
}
|
||||
}
|
||||
|
||||
function mapSources(sources: ParsedSources): Mapped {
|
||||
const catalog = mapCatalog(sources.catalog)
|
||||
const zoneByNames = new Map(
|
||||
catalog.zones.map((z) => [zoneNameKey(z.name.fr, z.name.en), z.id]),
|
||||
)
|
||||
const views = [
|
||||
{ viewId: MAIN_VIEW_ID, svg: sources.main, file: sources.assets[0]! },
|
||||
{ viewId: HEAD_VIEW_ID, svg: sources.head, file: sources.assets[1]! },
|
||||
]
|
||||
const annotations = views.flatMap(({ viewId, svg, file }) =>
|
||||
svg.annotations.map((a) =>
|
||||
mapAnnotation(a, { viewId, fileName: file.file, zoneByNames }),
|
||||
),
|
||||
)
|
||||
const legacy = [...sources.main.annotations, ...sources.head.annotations]
|
||||
return { annotations, categories: mapCategories(legacy), catalog }
|
||||
}
|
||||
|
||||
function buildViews(assets: AssetRecord[]): SheetView[] {
|
||||
return [
|
||||
{
|
||||
id: MAIN_VIEW_ID,
|
||||
kind: 'main',
|
||||
name: { fr: 'Vue générale', en: 'Overview' },
|
||||
svg_asset_id: assets[0]!.svg_asset_id,
|
||||
view_box: null,
|
||||
},
|
||||
{
|
||||
id: HEAD_VIEW_ID,
|
||||
kind: 'detail',
|
||||
parent_view_id: MAIN_VIEW_ID,
|
||||
name: { fr: 'Tête', en: 'Head' },
|
||||
svg_asset_id: assets[1]!.svg_asset_id,
|
||||
view_box: null,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function buildDocument(
|
||||
sources: ParsedSources,
|
||||
mapped: Mapped,
|
||||
): AnatomicalSheetDocumentInput {
|
||||
const disclaimer = sources.catalog.scope_disclaimer
|
||||
return {
|
||||
schema_version: SHEET_DOCUMENT_SCHEMA_VERSION,
|
||||
species_id: EQUINE_SPECIES_ID,
|
||||
name: { fr: 'Cheval', en: 'Horse' },
|
||||
description: {
|
||||
fr: 'Fiche anatomique officielle Faunosteo',
|
||||
en: 'Official Faunosteo anatomical sheet',
|
||||
},
|
||||
scope_disclaimer: disclaimer === undefined ? {} : { fr: disclaimer },
|
||||
attribution: {
|
||||
authors: ['Faunosteo'],
|
||||
license: null,
|
||||
notes:
|
||||
'Import des données historiques: Horse.svg, Horse_head.svg, ' +
|
||||
`pathologies.json (schema ${sources.catalog.schema_version})`,
|
||||
},
|
||||
vertebral_config: { regions: vertebralRegions(sources.formula) },
|
||||
categories: mapped.categories.categories,
|
||||
views: buildViews(sources.assets),
|
||||
annotations: mapped.annotations.map((m) => m.annotation),
|
||||
finding_zones: mapped.catalog.zones,
|
||||
}
|
||||
}
|
||||
|
||||
function buildIdMap(sources: ParsedSources, mapped: Mapped): LegacyIdMap {
|
||||
return {
|
||||
views: { [HEAD_VIEW_ID]: HEAD_VIEW_ID },
|
||||
annotations: Object.fromEntries(
|
||||
mapped.annotations.map((m) => [m.row.legacyId, m.row.newId]),
|
||||
),
|
||||
categories: mapped.categories.idMap,
|
||||
finding_nodes: mapped.catalog.nodeIdMap,
|
||||
assets: Object.fromEntries(
|
||||
sources.assets.map((a) => [a.file, a.svg_asset_id]),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
function countBy(
|
||||
annotations: readonly Annotation[],
|
||||
test: (a: Annotation) => boolean,
|
||||
) {
|
||||
return annotations.filter(test).length
|
||||
}
|
||||
|
||||
function buildStats(
|
||||
document: AnatomicalSheetDocumentInput,
|
||||
mapped: Mapped,
|
||||
): ImportStats {
|
||||
const annotations = document.annotations
|
||||
const totals = mapped.catalog.zoneStats
|
||||
const sum = (key: 'nodes' | 'leaves' | 'vetReferrals') =>
|
||||
totals.reduce((acc, zone) => acc + zone[key], 0)
|
||||
return {
|
||||
legacyAnnotations: mapped.annotations.length,
|
||||
annotations: annotations.length,
|
||||
annotationsByView: {
|
||||
[MAIN_VIEW_ID]: countBy(annotations, (a) => a.view_id === MAIN_VIEW_ID),
|
||||
[HEAD_VIEW_ID]: countBy(annotations, (a) => a.view_id === HEAD_VIEW_ID),
|
||||
},
|
||||
linkedAnnotations: countBy(
|
||||
annotations,
|
||||
(a) => a.kind !== 'detail_trigger' && a.finding_zone_id !== null,
|
||||
),
|
||||
triggers: countBy(annotations, (a) => a.kind === 'detail_trigger'),
|
||||
views: document.views.length,
|
||||
vertebralAnnotations: countBy(
|
||||
annotations,
|
||||
(a) => a.kind !== 'detail_trigger' && a.vertebral_region_code !== null,
|
||||
),
|
||||
bilateral: countBy(annotations, (a) => a.laterality === 'bilateral'),
|
||||
findingZones: document.finding_zones.length,
|
||||
nodes: sum('nodes'),
|
||||
leaves: sum('leaves'),
|
||||
vetReferrals: sum('vetReferrals'),
|
||||
missingDescriptionEn: mapped.catalog.missingDescriptionEn,
|
||||
sources: mapped.catalog.sources,
|
||||
}
|
||||
}
|
||||
|
||||
function sourceAnomalies(
|
||||
sources: ParsedSources,
|
||||
stats: ImportStats,
|
||||
): Anomaly[] {
|
||||
const out: Anomaly[] = []
|
||||
const add = (code: string, subject: string, message: string) =>
|
||||
out.push({ code, level: 'a_valider', subject, message })
|
||||
if (stats.missingDescriptionEn > 0) {
|
||||
add(
|
||||
'finding.description_en.missing',
|
||||
'pathologies.json',
|
||||
`${stats.missingDescriptionEn} descriptions sans traduction anglaise ` +
|
||||
`(clé « en » absente, rien d'inventé).`,
|
||||
)
|
||||
}
|
||||
if (sources.catalog.scope_disclaimer !== undefined) {
|
||||
add(
|
||||
'document.scope_disclaimer.no_en',
|
||||
'scope_disclaimer',
|
||||
'Texte de périmètre légal en français seulement : traduction anglaise à rédiger.',
|
||||
)
|
||||
}
|
||||
const range = sources.formula.variesRange ?? 'non précisée'
|
||||
add(
|
||||
'vertebral.cd.capped',
|
||||
'Cd',
|
||||
`Caudales plafonnées à ${sources.formula.counts.Cd} pour le sélecteur, ` +
|
||||
`alors que l'espèce varie (${range}) selon le commentaire source.`,
|
||||
)
|
||||
if (stats.sources === 0) {
|
||||
add(
|
||||
'finding.sources.none',
|
||||
'pathologies.json',
|
||||
'Aucune source bibliographique sur les nœuds, alors que la règle ' +
|
||||
'projet en demande au moins une par entrée.',
|
||||
)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
function informativeNotes(): Anomaly[] {
|
||||
return [
|
||||
{
|
||||
code: 'annotation.geometry.hitbox',
|
||||
level: 'informatif',
|
||||
subject: 'géométrie',
|
||||
message:
|
||||
'Géométrie lue sur le premier élément de chaque annotation (zone ' +
|
||||
"de clic), le marqueur visuel n'est pas importé.",
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
function collectAnomalies(
|
||||
sources: ParsedSources,
|
||||
mapped: Mapped,
|
||||
stats: ImportStats,
|
||||
): Anomaly[] {
|
||||
return [
|
||||
...sources.main.anomalies,
|
||||
...sources.head.anomalies,
|
||||
...mapped.annotations.flatMap((m) => m.anomalies),
|
||||
...mapped.categories.anomalies,
|
||||
...mapped.catalog.anomalies,
|
||||
...catalogAnomalies(sources.catalog),
|
||||
...sourceAnomalies(sources, stats),
|
||||
...informativeNotes(),
|
||||
]
|
||||
}
|
||||
|
||||
export function importEquineLegacy(input: EquineLegacyInput): ImportResult {
|
||||
const sources = parseSources(input)
|
||||
const mapped = mapSources(sources)
|
||||
const document = buildDocument(sources, mapped)
|
||||
const parsed = AnatomicalSheetDocumentSchema.parse(document)
|
||||
const stats = buildStats(document, mapped)
|
||||
return {
|
||||
document,
|
||||
legacyIdMap: buildIdMap(sources, mapped),
|
||||
assets: sources.assets,
|
||||
sourceDigests: [
|
||||
textDigest('pathologies.json', input.catalogJson),
|
||||
textDigest('vertebrae.ts', input.vertebraeSource),
|
||||
],
|
||||
sheetId: sheetIdFor(EQUINE_SPECIES_ID, EQUINE_SHEET_VERSION),
|
||||
viewBoxes: {
|
||||
[MAIN_VIEW_ID]: sources.main.viewBox,
|
||||
[HEAD_VIEW_ID]: sources.head.viewBox,
|
||||
},
|
||||
annotationRows: mapped.annotations.map((m) => m.row),
|
||||
regionInferences: mapped.annotations.flatMap((m) =>
|
||||
m.region ? [m.region] : [],
|
||||
),
|
||||
zoneStats: mapped.catalog.zoneStats,
|
||||
stats,
|
||||
anomalies: collectAnomalies(sources, mapped, stats),
|
||||
issues: validateSheetDocument(parsed),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
export { importEquineLegacy, HEAD_VIEW_ID, MAIN_VIEW_ID } from './importer'
|
||||
export { renderArtifacts, SEED_SQL_FILE } from './artifacts'
|
||||
export { renderImportReport } from './report'
|
||||
export { renderSeedSql, DOCUMENT_DOLLAR_TAG } from './seed'
|
||||
export {
|
||||
readEquineSources,
|
||||
EQUINE_SEED_DIR,
|
||||
EQUINE_SOURCE_PATHS,
|
||||
} from './sources'
|
||||
export {
|
||||
assetIdFromSha256,
|
||||
deterministicUuid,
|
||||
sha256Hex,
|
||||
sheetIdFor,
|
||||
slugify,
|
||||
} from './ids'
|
||||
export { inferRegionCode } from './regions'
|
||||
export type * from './types'
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Spine region inference from legacy labels, kept in the importer only
|
||||
* (ANATOMICAL_SHEET_MODEL.md §2: no label parsing at runtime). Same roots
|
||||
* and order as the legacy regionFromLabel (audit 07 §2): FR label first,
|
||||
* then EN, first root in test order wins.
|
||||
*/
|
||||
|
||||
const REGION_ROOTS: ReadonlyArray<{ code: string; roots: string[] }> = [
|
||||
{ code: 'C', roots: ['cervic'] },
|
||||
{ code: 'T', roots: ['thorac', 'dors'] },
|
||||
{ code: 'L', roots: ['lombair', 'lumbar'] },
|
||||
{ code: 'S', roots: ['sacral', 'sacre'] },
|
||||
{ code: 'Cd', roots: ['caudal', 'coccyg'] },
|
||||
]
|
||||
|
||||
export interface RegionMatch {
|
||||
code: string
|
||||
root: string
|
||||
label: string
|
||||
}
|
||||
|
||||
function normalise(label: string): string {
|
||||
return label.normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()
|
||||
}
|
||||
|
||||
function matchLabel(label: string): RegionMatch | null {
|
||||
const text = normalise(label)
|
||||
for (const { code, roots } of REGION_ROOTS) {
|
||||
const root = roots.find((candidate) => text.includes(candidate))
|
||||
if (root) return { code, root, label }
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Null when neither label carries a known root: the caller reports it. */
|
||||
export function inferRegionCode(
|
||||
nameFr: string | null,
|
||||
nameEn: string | null,
|
||||
): RegionMatch | null {
|
||||
const labels = [nameFr, nameEn].filter((l): l is string => Boolean(l))
|
||||
for (const label of labels) {
|
||||
const match = matchLabel(label)
|
||||
if (match) return match
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
import { countTree } from './catalog'
|
||||
import type { Anomaly, ImportResult } from './types'
|
||||
|
||||
/**
|
||||
* French Markdown import report, written for an osteopath (what to
|
||||
* validate) and for the developer (what was mapped and how). No dates and
|
||||
* no environment data: the report is a committed, byte-stable artifact.
|
||||
*/
|
||||
|
||||
function cell(value: string | number | null): string {
|
||||
if (value === null) return '-'
|
||||
return String(value).replace(/\|/g, '\\|').replace(/\n/g, ' ')
|
||||
}
|
||||
|
||||
function table(
|
||||
head: string[],
|
||||
rows: Array<Array<string | number | null>>,
|
||||
): string {
|
||||
const lines = [head, head.map(() => '---'), ...rows.map((r) => r.map(cell))]
|
||||
return lines.map((line) => `| ${line.join(' | ')} |`).join('\n')
|
||||
}
|
||||
|
||||
function code(value: string | null): string {
|
||||
return value === null ? '-' : `\`${value}\``
|
||||
}
|
||||
|
||||
function intro(result: ImportResult): string {
|
||||
return [
|
||||
"# Rapport d'import : fiche anatomique équine v1",
|
||||
'',
|
||||
'Généré par `pnpm import:equine` à partir des données historiques. ' +
|
||||
'Ne pas modifier à la main : relancer la commande.',
|
||||
'',
|
||||
`Statut : **brouillon** (version 1 en \`draft\`), jamais publié par ` +
|
||||
`le seed. Fiche \`${result.sheetId}\`, espèce \`${result.document.species_id}\`.`,
|
||||
'',
|
||||
'Les éléments de la section « Anomalies à valider » demandent une ' +
|
||||
'décision métier avant toute publication.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function sourcesSection(result: ImportResult): string {
|
||||
const assetRows = result.assets.map((a) => [
|
||||
code(a.file),
|
||||
a.byte_size,
|
||||
code(a.sha256),
|
||||
code(a.svg_asset_id),
|
||||
])
|
||||
const otherRows = result.sourceDigests.map((d) => [
|
||||
code(d.file),
|
||||
d.byte_size,
|
||||
code(d.sha256),
|
||||
'-',
|
||||
])
|
||||
const viewBoxes = Object.entries(result.viewBoxes).map(
|
||||
([view, box]) =>
|
||||
`- vue \`${view}\` : viewBox \`${box ?? 'absent'}\` (view_box du ` +
|
||||
`document laissé à null, le SVG porte le sien)`,
|
||||
)
|
||||
return [
|
||||
'## 1. Sources et empreintes',
|
||||
'',
|
||||
table(
|
||||
['Fichier', 'Octets', 'sha256', "Id d'asset"],
|
||||
[...assetRows, ...otherRows],
|
||||
),
|
||||
'',
|
||||
"Les ids d'asset sont dérivés du sha256 du fichier (UUID déterministe), " +
|
||||
"les deux SVG sont copiés à l'identique dans `assets/`.",
|
||||
'',
|
||||
...viewBoxes,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function volumesSection(result: ImportResult): string {
|
||||
const s = result.stats
|
||||
const out = countTree(
|
||||
result.document.finding_zones.flatMap((z) => z.categories),
|
||||
)
|
||||
const rows: Array<[string, number]> = [
|
||||
['Annotations', s.annotations],
|
||||
['dont vue `main` (Horse.svg)', s.annotationsByView.main ?? 0],
|
||||
['dont vue `head` (Horse_head.svg)', s.annotationsByView.head ?? 0],
|
||||
['Annotations reliées à une zone de constats', s.linkedAnnotations],
|
||||
['Déclencheurs de vue détail', s.triggers],
|
||||
['Vues', s.views],
|
||||
['Zones vertébrales avec code de région', s.vertebralAnnotations],
|
||||
['Annotations bilatérales', s.bilateral],
|
||||
['Zones de constats (catalogue)', s.findingZones],
|
||||
['Nœuds (catégories incluses)', s.nodes],
|
||||
['Feuilles', s.leaves],
|
||||
['Orientations vétérinaires', s.vetReferrals],
|
||||
]
|
||||
return [
|
||||
'## 2. Volumes',
|
||||
'',
|
||||
table(['Mesure', 'Valeur'], rows),
|
||||
'',
|
||||
`Contrôle entrée = sortie : ${s.legacyAnnotations} annotations lues, ` +
|
||||
`${s.annotations} écrites ; ${s.nodes} nœuds lus, ${out.nodes} écrits. ` +
|
||||
`L'importateur s'arrête si un nœud manque.`,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function annotationsSection(result: ImportResult): string {
|
||||
const rows = result.annotationRows.map((r) => [
|
||||
code(r.legacyId),
|
||||
code(r.newId),
|
||||
r.viewId,
|
||||
r.kind,
|
||||
r.laterality,
|
||||
r.regionCode,
|
||||
r.findingZoneId === null ? '-' : code(r.findingZoneId),
|
||||
r.geometry,
|
||||
])
|
||||
return [
|
||||
'## 3. Annotations',
|
||||
'',
|
||||
table(
|
||||
[
|
||||
'Id historique',
|
||||
'Nouvel id',
|
||||
'Vue',
|
||||
'Type',
|
||||
'Latéralité',
|
||||
'Région',
|
||||
'Zone de constats',
|
||||
'Géométrie',
|
||||
],
|
||||
rows,
|
||||
),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function categoriesSection(result: ImportResult): string {
|
||||
const legacyOf = Object.fromEntries(
|
||||
Object.entries(result.legacyIdMap.categories).map(([legacy, id]) => [
|
||||
id,
|
||||
legacy,
|
||||
]),
|
||||
)
|
||||
const authored = new Set(
|
||||
result.anomalies
|
||||
.filter((a) => a.code === 'category.label.authored')
|
||||
.map((a) => a.subject),
|
||||
)
|
||||
const rows = result.document.categories.map((c) => [
|
||||
code(legacyOf[c.id] ?? c.id),
|
||||
code(c.id),
|
||||
c.name.fr,
|
||||
c.name.en,
|
||||
authored.has(c.id) ? 'importateur, à valider' : 'SVG',
|
||||
])
|
||||
return [
|
||||
"## 4. Catégories d'annotation",
|
||||
'',
|
||||
table(
|
||||
['Id SVG', 'Id', 'Libellé FR', 'Libellé EN', 'Origine du libellé'],
|
||||
rows,
|
||||
),
|
||||
'',
|
||||
"Couleur : `null` partout (les couleurs du SVG restent dans l'asset). " +
|
||||
'Dans les SVG, `data-anno-category-name` répète le slug (`articulations`, ' +
|
||||
"`os`) : ce n'est pas un libellé, le libellé lisible de la table " +
|
||||
"de l'importateur est utilisé.",
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function vertebralSection(result: ImportResult): string {
|
||||
const regions = result.document.vertebral_config.regions.map((r) => [
|
||||
code(r.code),
|
||||
r.name.fr,
|
||||
r.name.en,
|
||||
r.count,
|
||||
])
|
||||
const inferences = result.regionInferences.map((i) => [
|
||||
code(result.legacyIdMap.annotations[i.annotationId] ?? i.annotationId),
|
||||
i.label,
|
||||
i.root === null ? '-' : code(i.root),
|
||||
code(i.code),
|
||||
])
|
||||
return [
|
||||
'## 5. Configuration vertébrale',
|
||||
'',
|
||||
table(['Code', 'Nom FR', 'Nom EN', 'Vertèbres'], regions),
|
||||
'',
|
||||
'Codes de région déduits des libellés (racines `cervic`, `thorac`/`dors`, ' +
|
||||
'`lombair`/`lumbar`, `sacral`/`sacre`, `caudal`/`coccyg`, FR puis ' +
|
||||
'EN). Déduction faite une fois ici, le document porte le code :',
|
||||
'',
|
||||
table(['Annotation', 'Libellé lu', 'Racine', 'Code'], inferences),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function findingsSection(result: ImportResult): string {
|
||||
const names = new Map(
|
||||
result.document.finding_zones.map((z) => [z.id, z.name.fr]),
|
||||
)
|
||||
const rows = result.zoneStats.map((z) => [
|
||||
code(z.zoneId),
|
||||
names.get(z.zoneId) ?? '-',
|
||||
z.nodes,
|
||||
z.leaves,
|
||||
z.vetReferrals,
|
||||
])
|
||||
const s = result.stats
|
||||
rows.push(['**Total**', '', s.nodes, s.leaves, s.vetReferrals])
|
||||
return [
|
||||
'## 6. Arbre de constats par zone',
|
||||
'',
|
||||
'Copie fidèle du catalogue : ids, libellés, descriptions présentes, ' +
|
||||
'orientations vétérinaires et sources. Ordre des zones et des catégories ' +
|
||||
'conservé. Nœuds = catégories incluses.',
|
||||
'',
|
||||
table(['Zone', 'Nom', 'Nœuds', 'Feuilles', 'Orientations vét.'], rows),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function anomalyRows(anomalies: readonly Anomaly[]) {
|
||||
return anomalies.map((a) => [code(a.code), a.subject, a.message])
|
||||
}
|
||||
|
||||
function anomaliesSection(result: ImportResult): string {
|
||||
const toValidate = result.anomalies.filter((a) => a.level === 'a_valider')
|
||||
const informative = result.anomalies.filter((a) => a.level === 'informatif')
|
||||
return [
|
||||
'## 7. Anomalies à valider',
|
||||
'',
|
||||
`${toValidate.length} points demandent une décision, ${informative.length} sont informatifs.`,
|
||||
'',
|
||||
'### À valider',
|
||||
'',
|
||||
table(['Code', 'Objet', 'Détail'], anomalyRows(toValidate)),
|
||||
'',
|
||||
'### Informatif',
|
||||
'',
|
||||
table(['Code', 'Objet', 'Détail'], anomalyRows(informative)),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function notImportedSection(result: ImportResult): string {
|
||||
const dropped = result.annotationRows.filter((r) => r.geometry === 'aucune')
|
||||
const lines =
|
||||
dropped.length === 0
|
||||
? ['Aucune donnée métier écartée.']
|
||||
: dropped.map(
|
||||
(r) => `- géométrie de \`${r.legacyId}\` (forme non prise en charge)`,
|
||||
)
|
||||
return [
|
||||
'## 8. Données non importées',
|
||||
'',
|
||||
...lines,
|
||||
'',
|
||||
'Non repris par construction : le second élément graphique de chaque ' +
|
||||
"annotation (marqueur visuel), qui reste dans l'asset SVG copié à " +
|
||||
"l'identique.",
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function validationSection(result: ImportResult): string {
|
||||
const errors = result.issues.filter((i) => i.severity === 'error')
|
||||
const warnings = result.issues.filter((i) => i.severity === 'warning')
|
||||
const rows = result.issues.map((i) => [
|
||||
i.severity,
|
||||
code(i.code),
|
||||
code(i.path),
|
||||
i.message,
|
||||
])
|
||||
return [
|
||||
'## 9. Résultat de validation',
|
||||
'',
|
||||
'- Forme (`AnatomicalSheetDocumentSchema`) : conforme.',
|
||||
`- Intégrité (\`validateSheetDocument\`) : ${errors.length} erreur(s), ` +
|
||||
`${warnings.length} avertissement(s).`,
|
||||
...(rows.length
|
||||
? ['', table(['Gravité', 'Code', 'Chemin', 'Message'], rows)]
|
||||
: []),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export function renderImportReport(result: ImportResult): string {
|
||||
return (
|
||||
[
|
||||
intro(result),
|
||||
sourcesSection(result),
|
||||
volumesSection(result),
|
||||
annotationsSection(result),
|
||||
categoriesSection(result),
|
||||
vertebralSection(result),
|
||||
findingsSection(result),
|
||||
anomaliesSection(result),
|
||||
notImportedSection(result),
|
||||
validationSection(result),
|
||||
].join('\n\n') + '\n'
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { ImportResult } from './types'
|
||||
|
||||
/**
|
||||
* Idempotent PostgreSQL seed of the official equine sheet as a DRAFT.
|
||||
* Runs as the database owner in `supabase db reset` and in the PGlite
|
||||
* harness. It never publishes: publication is a human act through
|
||||
* publish_sheet_version once the import report is validated.
|
||||
*/
|
||||
|
||||
export const DOCUMENT_DOLLAR_TAG = '$equine_doc$'
|
||||
|
||||
const SHEET_DESCRIPTION =
|
||||
'Fiche anatomique officielle du cheval ' +
|
||||
'(import des données historiques, brouillon à valider)'
|
||||
|
||||
export interface SeedSqlParams {
|
||||
result: ImportResult
|
||||
/** document.json text, embedded verbatim in a dollar-quoted literal. */
|
||||
documentJson: string
|
||||
}
|
||||
|
||||
/** Only ever fed fixed ASCII values; doubled quotes keep it literal-safe. */
|
||||
function sqlText(value: string): string {
|
||||
return `'${value.replace(/'/g, "''")}'`
|
||||
}
|
||||
|
||||
function header(): string {
|
||||
return [
|
||||
'-- Official equine anatomical sheet, version 1, DRAFT.',
|
||||
'-- Generated by `pnpm import:equine` (packages/anatomy): do not edit by hand.',
|
||||
'-- Idempotent. Never publishes: the version stays in status draft until a',
|
||||
'-- platform admin validates IMPORT-REPORT.md and publishes it by hand.',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function sheetInsert(sheetId: string): string {
|
||||
return [
|
||||
'insert into public.anatomical_sheets',
|
||||
' (id, species_id, name, slug, description, creator_user_id, is_official, visibility)',
|
||||
'values (',
|
||||
` ${sqlText(sheetId)}, 'equine', 'Faunosteo / Cheval', 'faunosteo-cheval',`,
|
||||
` ${sqlText(SHEET_DESCRIPTION)},`,
|
||||
" null, true, 'private'",
|
||||
')',
|
||||
'on conflict (id) do nothing;',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function assetInserts(result: ImportResult): string {
|
||||
const rows = result.assets.map(
|
||||
(a) =>
|
||||
` (${sqlText(a.svg_asset_id)}, ${sqlText(result.sheetId)}, ${sqlText(a.sha256)}, ` +
|
||||
`${a.byte_size}, 'image/svg+xml', ${sqlText(a.file)})`,
|
||||
)
|
||||
return [
|
||||
'insert into public.anatomical_sheet_assets',
|
||||
' (id, sheet_id, sha256, byte_size, content_type, file_name)',
|
||||
'values',
|
||||
rows.join(',\n'),
|
||||
'on conflict (sheet_id, sha256) do nothing;',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function draftInsert(sheetId: string, documentJson: string): string {
|
||||
if (documentJson.includes(DOCUMENT_DOLLAR_TAG)) {
|
||||
throw new Error(
|
||||
`document JSON contains the dollar-quote tag ${DOCUMENT_DOLLAR_TAG}`,
|
||||
)
|
||||
}
|
||||
return [
|
||||
'select private.insert_sheet_draft(',
|
||||
' null,',
|
||||
` ${sqlText(sheetId)},`,
|
||||
` ${DOCUMENT_DOLLAR_TAG}${documentJson.trimEnd()}${DOCUMENT_DOLLAR_TAG}::jsonb,`,
|
||||
" 'Import des données équines historiques (Horse.svg, Horse_head.svg, pathologies.json)'",
|
||||
')',
|
||||
'where not exists (',
|
||||
` select 1 from public.anatomical_sheet_versions where sheet_id = ${sqlText(sheetId)}`,
|
||||
');',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
export function renderSeedSql({ result, documentJson }: SeedSqlParams): string {
|
||||
return (
|
||||
[
|
||||
header(),
|
||||
sheetInsert(result.sheetId),
|
||||
assetInserts(result),
|
||||
draftInsert(result.sheetId, documentJson),
|
||||
].join('\n\n') + '\n'
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import type { EquineLegacyInput } from './types'
|
||||
|
||||
/**
|
||||
* Locations of the legacy equine sources and of the generated seed, both
|
||||
* relative to the repository root. Shared by the CLI and the golden tests.
|
||||
*/
|
||||
|
||||
export const EQUINE_SOURCE_PATHS = {
|
||||
mainSvg: 'apps/app/public/species/equine/Horse.svg',
|
||||
headSvg: 'apps/app/public/species/equine/Horse_head.svg',
|
||||
catalog: 'apps/app/src/domain/species/equine/pathologies.json',
|
||||
vertebrae: 'apps/app/src/domain/species/equine/vertebrae.ts',
|
||||
} as const
|
||||
|
||||
export const EQUINE_SEED_DIR = 'supabase/seed/anatomical-sheets/equine/v1'
|
||||
|
||||
function fileName(path: string): string {
|
||||
return path.slice(path.lastIndexOf('/') + 1)
|
||||
}
|
||||
|
||||
export async function readEquineSources(
|
||||
repoRoot: string,
|
||||
): Promise<EquineLegacyInput> {
|
||||
const read = (path: string) => readFile(join(repoRoot, path))
|
||||
const [main, head, catalog, vertebrae] = await Promise.all([
|
||||
read(EQUINE_SOURCE_PATHS.mainSvg),
|
||||
read(EQUINE_SOURCE_PATHS.headSvg),
|
||||
read(EQUINE_SOURCE_PATHS.catalog),
|
||||
read(EQUINE_SOURCE_PATHS.vertebrae),
|
||||
])
|
||||
return {
|
||||
mainSvg: {
|
||||
fileName: fileName(EQUINE_SOURCE_PATHS.mainSvg),
|
||||
bytes: new Uint8Array(main),
|
||||
},
|
||||
headSvg: {
|
||||
fileName: fileName(EQUINE_SOURCE_PATHS.headSvg),
|
||||
bytes: new Uint8Array(head),
|
||||
},
|
||||
catalogJson: catalog.toString('utf8'),
|
||||
vertebraeSource: vertebrae.toString('utf8'),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { DOMParser, type Element } from '@xmldom/xmldom'
|
||||
import type { Geometry } from '@faunosteo/domain'
|
||||
import type { Anomaly } from './types'
|
||||
|
||||
/**
|
||||
* Reads the annotation layer of a legacy SVG (docs/ANATOMY-SVG-CONVENTION.md).
|
||||
* Each annotation is drawn by one or two elements sharing a data-anno-id
|
||||
* (hitbox first, visual marker second); the importer keeps one record per
|
||||
* id, attributes and geometry taken from the first element.
|
||||
*/
|
||||
|
||||
export interface LegacyAnnotation {
|
||||
id: string
|
||||
tagName: string
|
||||
elementCount: number
|
||||
nameFr: string | null
|
||||
nameEn: string | null
|
||||
category: string | null
|
||||
categoryName: string | null
|
||||
lateral: string | null
|
||||
special: string | null
|
||||
opensDetail: string | null
|
||||
geometry: Geometry | null
|
||||
}
|
||||
|
||||
export interface ParsedSvg {
|
||||
viewBox: string | null
|
||||
annotations: LegacyAnnotation[]
|
||||
anomalies: Anomaly[]
|
||||
}
|
||||
|
||||
function attr(element: Element, name: string): string | null {
|
||||
return element.hasAttribute(name) ? element.getAttribute(name) : null
|
||||
}
|
||||
|
||||
function parsePoints(raw: string): Array<[number, number]> {
|
||||
const numbers = raw
|
||||
.trim()
|
||||
.split(/[\s,]+/)
|
||||
.map(Number)
|
||||
const pairs: Array<[number, number]> = []
|
||||
for (let i = 0; i + 1 < numbers.length; i += 2) {
|
||||
pairs.push([numbers[i]!, numbers[i + 1]!])
|
||||
}
|
||||
return pairs
|
||||
}
|
||||
|
||||
/** Circle and polygon are the only shapes the legacy editor produces. */
|
||||
function readGeometry(element: Element): Geometry | null {
|
||||
if (element.tagName === 'circle') {
|
||||
return {
|
||||
type: 'circle',
|
||||
cx: Number(attr(element, 'cx')),
|
||||
cy: Number(attr(element, 'cy')),
|
||||
r: Number(attr(element, 'r')),
|
||||
}
|
||||
}
|
||||
if (element.tagName === 'polygon') {
|
||||
return {
|
||||
type: 'polygon',
|
||||
points: parsePoints(attr(element, 'points') ?? ''),
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function readAnnotation(element: Element, id: string): LegacyAnnotation {
|
||||
return {
|
||||
id,
|
||||
tagName: element.tagName,
|
||||
elementCount: 1,
|
||||
nameFr: attr(element, 'data-anno-name-fr'),
|
||||
nameEn: attr(element, 'data-anno-name-en'),
|
||||
category: attr(element, 'data-anno-category'),
|
||||
categoryName: attr(element, 'data-anno-category-name'),
|
||||
lateral: attr(element, 'data-anno-lateral'),
|
||||
special: attr(element, 'data-anno-special'),
|
||||
opensDetail: attr(element, 'data-anno-opens-detail'),
|
||||
geometry: readGeometry(element),
|
||||
}
|
||||
}
|
||||
|
||||
function geometryAnomaly(fileName: string, a: LegacyAnnotation): Anomaly {
|
||||
return {
|
||||
code: 'svg.geometry.unsupported',
|
||||
level: 'a_valider',
|
||||
subject: `${fileName} ${a.id}`,
|
||||
message: `Élément <${a.tagName}> non pris en charge : géométrie non importée (null).`,
|
||||
}
|
||||
}
|
||||
|
||||
/** Document order is kept: it is the order of the annotations table. */
|
||||
export function parseAnnotatedSvg(text: string, fileName: string): ParsedSvg {
|
||||
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
|
||||
const root = doc.documentElement
|
||||
const byId = new Map<string, LegacyAnnotation>()
|
||||
const elements = doc.getElementsByTagName('*')
|
||||
for (let i = 0; i < elements.length; i += 1) {
|
||||
const element = elements.item(i)!
|
||||
const id = attr(element, 'data-anno-id')
|
||||
if (id === null) continue
|
||||
const known = byId.get(id)
|
||||
if (known) known.elementCount += 1
|
||||
else byId.set(id, readAnnotation(element, id))
|
||||
}
|
||||
const annotations = [...byId.values()]
|
||||
const anomalies = annotations
|
||||
.filter((a) => a.geometry === null)
|
||||
.map((a) => geometryAnomaly(fileName, a))
|
||||
return {
|
||||
viewBox: root ? attr(root, 'viewBox') : null,
|
||||
annotations,
|
||||
anomalies,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import type {
|
||||
AnatomicalSheetDocumentInput,
|
||||
SheetIssue,
|
||||
} from '@faunosteo/domain'
|
||||
|
||||
/**
|
||||
* Shared shapes of the legacy importer. Anomalies are never silent: every
|
||||
* correction or gap the importer meets lands in the import report so an
|
||||
* osteopath can validate it before the draft is published.
|
||||
*/
|
||||
|
||||
/** 'a_valider' needs a business decision; 'informatif' only explains. */
|
||||
export type AnomalyLevel = 'a_valider' | 'informatif'
|
||||
|
||||
export interface Anomaly {
|
||||
code: string
|
||||
level: AnomalyLevel
|
||||
subject: string
|
||||
message: string
|
||||
}
|
||||
|
||||
/** One SVG file handed to the importer, bytes untouched. */
|
||||
export interface SvgSource {
|
||||
fileName: string
|
||||
bytes: Uint8Array
|
||||
}
|
||||
|
||||
/** The four legacy sources, read by the caller (CLI or tests). */
|
||||
export interface EquineLegacyInput {
|
||||
mainSvg: SvgSource
|
||||
headSvg: SvgSource
|
||||
catalogJson: string
|
||||
vertebraeSource: string
|
||||
}
|
||||
|
||||
export interface AssetRecord {
|
||||
file: string
|
||||
sha256: string
|
||||
byte_size: number
|
||||
svg_asset_id: string
|
||||
}
|
||||
|
||||
export interface LegacyIdMap {
|
||||
views: Record<string, string>
|
||||
annotations: Record<string, string>
|
||||
categories: Record<string, string>
|
||||
finding_nodes: Record<string, string>
|
||||
assets: Record<string, string>
|
||||
}
|
||||
|
||||
/** How the region code of a spine annotation was inferred from labels. */
|
||||
export interface RegionInference {
|
||||
annotationId: string
|
||||
label: string
|
||||
root: string | null
|
||||
code: string | null
|
||||
}
|
||||
|
||||
export interface AnnotationRow {
|
||||
legacyId: string
|
||||
newId: string
|
||||
viewId: string
|
||||
kind: string
|
||||
laterality: string
|
||||
regionCode: string | null
|
||||
findingZoneId: string | null
|
||||
geometry: string
|
||||
}
|
||||
|
||||
export interface ZoneStats {
|
||||
zoneId: string
|
||||
nodes: number
|
||||
leaves: number
|
||||
vetReferrals: number
|
||||
}
|
||||
|
||||
/** Digest of a non-asset source, shown in the report. */
|
||||
export interface SourceDigest {
|
||||
file: string
|
||||
sha256: string
|
||||
byte_size: number
|
||||
}
|
||||
|
||||
export interface ImportStats {
|
||||
legacyAnnotations: number
|
||||
annotations: number
|
||||
annotationsByView: Record<string, number>
|
||||
linkedAnnotations: number
|
||||
triggers: number
|
||||
views: number
|
||||
vertebralAnnotations: number
|
||||
bilateral: number
|
||||
findingZones: number
|
||||
nodes: number
|
||||
leaves: number
|
||||
vetReferrals: number
|
||||
missingDescriptionEn: number
|
||||
sources: number
|
||||
}
|
||||
|
||||
/** Everything the report and the seed need, computed once. */
|
||||
export interface ImportResult {
|
||||
document: AnatomicalSheetDocumentInput
|
||||
legacyIdMap: LegacyIdMap
|
||||
assets: AssetRecord[]
|
||||
sourceDigests: SourceDigest[]
|
||||
sheetId: string
|
||||
viewBoxes: Record<string, string | null>
|
||||
annotationRows: AnnotationRow[]
|
||||
regionInferences: RegionInference[]
|
||||
zoneStats: ZoneStats[]
|
||||
stats: ImportStats
|
||||
anomalies: Anomaly[]
|
||||
issues: SheetIssue[]
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Reads the legacy vertebral formula from the source text of
|
||||
* apps/app/src/domain/species/equine/vertebrae.ts. The file is parsed as
|
||||
* text, not imported: it depends on the app's '@/…' alias, which this
|
||||
* package does not resolve.
|
||||
*/
|
||||
|
||||
export interface LegacyVertebralFormula {
|
||||
counts: Record<string, number>
|
||||
/** "varies A–B" range from the source comment, when stated. */
|
||||
variesRange: string | null
|
||||
}
|
||||
|
||||
const REGION_ORDER = ['C', 'T', 'L', 'S', 'Cd'] as const
|
||||
|
||||
export function parseVertebralFormula(source: string): LegacyVertebralFormula {
|
||||
const body = /=\s*\{([^}]*)\}/.exec(source)?.[1]
|
||||
if (!body) throw new Error('vertebrae.ts: formula object not found')
|
||||
const counts: Record<string, number> = {}
|
||||
for (const match of body.matchAll(/(\w+)\s*:\s*(\d+)/g)) {
|
||||
counts[match[1]!] = Number(match[2])
|
||||
}
|
||||
for (const code of REGION_ORDER) {
|
||||
if (!(code in counts))
|
||||
throw new Error(`vertebrae.ts: region ${code} missing`)
|
||||
}
|
||||
const range = /varies\s+(\d+)\s*[–-]\s*(\d+)/.exec(source)
|
||||
return {
|
||||
counts,
|
||||
variesRange: range ? `${range[1]}–${range[2]}` : null,
|
||||
}
|
||||
}
|
||||
|
||||
export const VERTEBRAL_REGION_ORDER = REGION_ORDER
|
||||
|
||||
const REGION_NAMES: Readonly<Record<string, { fr: string; en: string }>> = {
|
||||
C: { fr: 'Cervicales', en: 'Cervical' },
|
||||
T: { fr: 'Thoraciques', en: 'Thoracic' },
|
||||
L: { fr: 'Lombaires', en: 'Lumbar' },
|
||||
S: { fr: 'Sacrales', en: 'Sacral' },
|
||||
Cd: { fr: 'Caudales', en: 'Caudal' },
|
||||
}
|
||||
|
||||
/** Ordered C → Cd, the order of the legacy picker tabs. */
|
||||
export function vertebralRegions(formula: LegacyVertebralFormula) {
|
||||
return REGION_ORDER.map((code) => ({
|
||||
code,
|
||||
name: { ...REGION_NAMES[code]! },
|
||||
count: formula.counts[code]!,
|
||||
}))
|
||||
}
|
||||
Reference in new issue
Block a user