GenPatientProfile 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. genpatientprofile/__init__.py +17 -0
  2. genpatientprofile/base.py +57 -0
  3. genpatientprofile/config.py +11 -0
  4. genpatientprofile/core.py +116 -0
  5. genpatientprofile/fictive.py +52 -0
  6. genpatientprofile/registry.py +31 -0
  7. genpatientprofile/scenario.py +51 -0
  8. genpatientprofile/sites/__init__.py +0 -0
  9. genpatientprofile/sites/aphp/__init__.py +17 -0
  10. genpatientprofile/sites/aphp/code_cards.py +311 -0
  11. genpatientprofile/sites/aphp/constants.py +75 -0
  12. genpatientprofile/sites/aphp/fictive.py +159 -0
  13. genpatientprofile/sites/aphp/loader.py +388 -0
  14. genpatientprofile/sites/aphp/managment.py +500 -0
  15. genpatientprofile/sites/aphp/pipeline.py +221 -0
  16. genpatientprofile/sites/aphp/prompt.py +427 -0
  17. genpatientprofile/sites/aphp/prompt_sets.py +118 -0
  18. genpatientprofile/sites/aphp/sampler.py +291 -0
  19. genpatientprofile/sites/aphp/scenario.py +674 -0
  20. genpatientprofile/sites/aphp/templates/default/manifest.yaml +6 -0
  21. genpatientprofile/sites/aphp/templates/default/one_stage/delivery_inpatient_csection_hospit.txt +163 -0
  22. genpatientprofile/sites/aphp/templates/default/one_stage/delivery_inpatient_csection_urg.txt +163 -0
  23. genpatientprofile/sites/aphp/templates/default/one_stage/delivery_inpatient_hospit.txt +157 -0
  24. genpatientprofile/sites/aphp/templates/default/one_stage/delivery_inpatient_urg.txt +157 -0
  25. genpatientprofile/sites/aphp/templates/default/one_stage/medical_inpatient.txt +146 -0
  26. genpatientprofile/sites/aphp/templates/default/one_stage/medical_inpatient_obsteric.txt +147 -0
  27. genpatientprofile/sites/aphp/templates/default/one_stage/medical_inpatient_onco.txt +169 -0
  28. genpatientprofile/sites/aphp/templates/default/one_stage/medical_outpatient.txt +138 -0
  29. genpatientprofile/sites/aphp/templates/default/one_stage/medical_outpatient_onco.txt +168 -0
  30. genpatientprofile/sites/aphp/templates/default/one_stage/surgery_inpatient.txt +159 -0
  31. genpatientprofile/sites/aphp/templates/default/one_stage/surgery_inpatient_onco.txt +184 -0
  32. genpatientprofile/sites/aphp/templates/default/one_stage/surgery_outpatient.txt +131 -0
  33. genpatientprofile/sites/aphp/templates/default/one_stage/surgery_outpatient_onco.txt +141 -0
  34. genpatientprofile/sites/aphp/templates/default/prefix.txt +1 -0
  35. genpatientprofile/sites/aphp/templates/old/final/delivery_inpatient_csection_hospit.txt +170 -0
  36. genpatientprofile/sites/aphp/templates/old/final/delivery_inpatient_csection_urg.txt +170 -0
  37. genpatientprofile/sites/aphp/templates/old/final/delivery_inpatient_hospit.txt +164 -0
  38. genpatientprofile/sites/aphp/templates/old/final/delivery_inpatient_urg.txt +164 -0
  39. genpatientprofile/sites/aphp/templates/old/final/medical_inpatient.txt +152 -0
  40. genpatientprofile/sites/aphp/templates/old/final/medical_inpatient_obsteric.txt +154 -0
  41. genpatientprofile/sites/aphp/templates/old/final/medical_inpatient_onco.txt +175 -0
  42. genpatientprofile/sites/aphp/templates/old/final/medical_outpatient.txt +144 -0
  43. genpatientprofile/sites/aphp/templates/old/final/medical_outpatient_onco.txt +174 -0
  44. genpatientprofile/sites/aphp/templates/old/final/surgery_inpatient.txt +164 -0
  45. genpatientprofile/sites/aphp/templates/old/final/surgery_inpatient_onco.txt +190 -0
  46. genpatientprofile/sites/aphp/templates/old/final/surgery_outpatient.txt +140 -0
  47. genpatientprofile/sites/aphp/templates/old/final/surgery_outpatient_onco.txt +150 -0
  48. genpatientprofile/sites/aphp/templates/old/manifest.yaml +6 -0
  49. genpatientprofile/sites/aphp/templates/old/one_stage/delivery_inpatient_csection_hospit.txt +151 -0
  50. genpatientprofile/sites/aphp/templates/old/one_stage/delivery_inpatient_csection_urg.txt +151 -0
  51. genpatientprofile/sites/aphp/templates/old/one_stage/delivery_inpatient_hospit.txt +145 -0
  52. genpatientprofile/sites/aphp/templates/old/one_stage/delivery_inpatient_urg.txt +145 -0
  53. genpatientprofile/sites/aphp/templates/old/one_stage/medical_inpatient.txt +134 -0
  54. genpatientprofile/sites/aphp/templates/old/one_stage/medical_inpatient_obsteric.txt +135 -0
  55. genpatientprofile/sites/aphp/templates/old/one_stage/medical_inpatient_onco.txt +157 -0
  56. genpatientprofile/sites/aphp/templates/old/one_stage/medical_outpatient.txt +126 -0
  57. genpatientprofile/sites/aphp/templates/old/one_stage/medical_outpatient_onco.txt +156 -0
  58. genpatientprofile/sites/aphp/templates/old/one_stage/surgery_inpatient.txt +146 -0
  59. genpatientprofile/sites/aphp/templates/old/one_stage/surgery_inpatient_onco.txt +172 -0
  60. genpatientprofile/sites/aphp/templates/old/one_stage/surgery_outpatient.txt +122 -0
  61. genpatientprofile/sites/aphp/templates/old/one_stage/surgery_outpatient_onco.txt +132 -0
  62. genpatientprofile/sites/aphp/templates/old/summary/delivery_inpatient_csection_hospit.txt +96 -0
  63. genpatientprofile/sites/aphp/templates/old/summary/delivery_inpatient_csection_urg.txt +96 -0
  64. genpatientprofile/sites/aphp/templates/old/summary/delivery_inpatient_hospit.txt +96 -0
  65. genpatientprofile/sites/aphp/templates/old/summary/delivery_inpatient_urg.txt +96 -0
  66. genpatientprofile/sites/aphp/templates/old/summary/medical_inpatient.txt +94 -0
  67. genpatientprofile/sites/aphp/templates/old/summary/medical_inpatient_obsteric.txt +96 -0
  68. genpatientprofile/sites/aphp/templates/old/summary/medical_inpatient_onco.txt +94 -0
  69. genpatientprofile/sites/aphp/templates/old/summary/medical_outpatient.txt +94 -0
  70. genpatientprofile/sites/aphp/templates/old/summary/medical_outpatient_onco.txt +94 -0
  71. genpatientprofile/sites/aphp/templates/old/summary/surgery_inpatient.txt +94 -0
  72. genpatientprofile/sites/aphp/templates/old/summary/surgery_inpatient_onco.txt +94 -0
  73. genpatientprofile/sites/aphp/templates/old/summary/surgery_outpatient.txt +94 -0
  74. genpatientprofile/sites/aphp/templates/old/summary/surgery_outpatient_onco.txt +94 -0
  75. genpatientprofile/sites/aphp/templates/regles_atih.yml +482 -0
  76. genpatientprofile/sites/brest/__init__.py +0 -0
  77. genpatientprofile/sites/brest/constants.py +16 -0
  78. genpatientprofile/sites/brest/fictive.py +175 -0
  79. genpatientprofile/sites/brest/pipeline.py +104 -0
  80. genpatientprofile/sites/brest/sampler.py +89 -0
  81. genpatientprofile/sites/brest/scenario.py +113 -0
  82. genpatientprofile-0.1.0.dist-info/METADATA +258 -0
  83. genpatientprofile-0.1.0.dist-info/RECORD +86 -0
  84. genpatientprofile-0.1.0.dist-info/WHEEL +5 -0
  85. genpatientprofile-0.1.0.dist-info/licenses/LICENSE.md +353 -0
  86. genpatientprofile-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,17 @@
1
+ from genpatientprofile.core import generate
2
+ from genpatientprofile.registry import (
3
+ CONFIG_DIR,
4
+ PIPELINE_ALIASES,
5
+ PIPELINE_NAMES,
6
+ PIPELINES,
7
+ resolve_pipeline_name,
8
+ )
9
+
10
+ __all__ = [
11
+ "CONFIG_DIR",
12
+ "PIPELINE_ALIASES",
13
+ "PIPELINE_NAMES",
14
+ "PIPELINES",
15
+ "generate",
16
+ "resolve_pipeline_name",
17
+ ]
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ from abc import ABC, abstractmethod
4
+ from pathlib import Path
5
+
6
+ import polars as pl
7
+
8
+ REPORT_SCHEMA = {
9
+ "generation_id": pl.Utf8,
10
+ "scenario": pl.Utf8,
11
+ "report": pl.Utf8,
12
+ "model": pl.Utf8,
13
+ "timestamp": pl.Datetime,
14
+ }
15
+
16
+
17
+ class BasePipeline(ABC):
18
+ """Base class for synthetic medical-report generation pipelines.
19
+
20
+ Provides shared building blocks (LLM wrappers, generation loop, Parquet
21
+ persistence) and defines the interface that each concrete pipeline must
22
+ implement.
23
+ """
24
+
25
+ name: str = "base"
26
+
27
+ def __init__(
28
+ self,
29
+ config: dict,
30
+ prompt_workflow: str = "one_stage",
31
+ prompt_set: str = "default",
32
+ prompt_dir: str | Path | None = None,
33
+ ) -> None:
34
+ self.config = config
35
+ if prompt_workflow not in {"one_stage", "two_stage"}:
36
+ raise ValueError(
37
+ "prompt_workflow doit valoir 'one_stage' ou 'two_stage'"
38
+ )
39
+ self.prompt_workflow = prompt_workflow
40
+ self.prompt_set = prompt_set
41
+ self.prompt_dir = prompt_dir
42
+
43
+ @abstractmethod
44
+ def check_data(self) -> None:
45
+ """Verify that source data is present and prepare it if needed."""
46
+
47
+ @abstractmethod
48
+ def load_data(self) -> dict[str, pl.LazyFrame]:
49
+ """Load prepared data as LazyFrames."""
50
+
51
+ @abstractmethod
52
+ def get_fictive(self, data: dict[str, pl.LazyFrame], **kwargs) -> pl.DataFrame:
53
+ """Generate fictitious hospital stays from loaded data."""
54
+
55
+ @abstractmethod
56
+ def get_scenario(self, df: pl.DataFrame) -> pl.DataFrame:
57
+ """Transform fictitious stays into text scenarios for the LLM."""
@@ -0,0 +1,11 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+
5
+ import yaml
6
+
7
+
8
+ def load_config(path: str | Path) -> dict:
9
+ """Load a YAML configuration file and return its contents as a dict."""
10
+ with open(path, "r", encoding="utf-8") as f:
11
+ return yaml.safe_load(f)
@@ -0,0 +1,116 @@
1
+ from datetime import datetime
2
+ from pathlib import Path
3
+
4
+ import polars as pl
5
+
6
+ from genpatientprofile.config import load_config
7
+ from genpatientprofile.registry import (
8
+ CONFIG_DIR,
9
+ PIPELINE_ALIASES,
10
+ PIPELINE_NAMES,
11
+ PIPELINES,
12
+ resolve_pipeline_name,
13
+ )
14
+
15
+
16
+ def generate(
17
+ pipeline_name: str,
18
+ n_sejours: int = 1000,
19
+ n_ccam: int = 1,
20
+ n_das: int = 5,
21
+ ghm5_pattern: str | None = None,
22
+ config_file: str | None = None,
23
+ prompt_workflow: str = "one_stage",
24
+ prompt_set: str = "default",
25
+ prompt_dir: str | Path | None = None,
26
+ ) -> pl.DataFrame:
27
+ """Orchestrate an end-to-end synthetic medical-report generation run."""
28
+ requested_pipeline_name = pipeline_name
29
+ pipeline_name = resolve_pipeline_name(pipeline_name)
30
+ if pipeline_name not in PIPELINES:
31
+ raise ValueError(
32
+ f"Pipeline inconnu : '{requested_pipeline_name}'. "
33
+ f"Valeurs acceptées : {list(PIPELINE_NAMES)}"
34
+ )
35
+ if pipeline_name != "profile_generation" and (
36
+ prompt_workflow != "one_stage"
37
+ or prompt_set != "default"
38
+ or prompt_dir is not None
39
+ ):
40
+ raise ValueError(
41
+ "Les options prompt_workflow, prompt_set et prompt_dir "
42
+ "sont réservées au pipeline profile_generation"
43
+ )
44
+ if config_file:
45
+ config = load_config(config_file)
46
+ else:
47
+ config = load_config(CONFIG_DIR / "servers.yaml")
48
+
49
+ pipeline_configs = config["pipelines"]
50
+ config_name = pipeline_name
51
+ if config_name not in pipeline_configs:
52
+ legacy_name = next(
53
+ (
54
+ alias
55
+ for alias, canonical in PIPELINE_ALIASES.items()
56
+ if canonical == pipeline_name and alias in pipeline_configs
57
+ ),
58
+ None,
59
+ )
60
+ if legacy_name is None:
61
+ raise KeyError(
62
+ f"Configuration absente pour le pipeline '{pipeline_name}'"
63
+ )
64
+ config_name = legacy_name
65
+
66
+ pipeline = PIPELINES[pipeline_name](
67
+ config=pipeline_configs[config_name],
68
+ prompt_workflow=prompt_workflow,
69
+ prompt_set=prompt_set,
70
+ prompt_dir=prompt_dir,
71
+ )
72
+
73
+ pipeline.check_data()
74
+ data = pipeline.load_data()
75
+
76
+ df = pipeline.get_fictive(
77
+ data,
78
+ n_sejours=n_sejours,
79
+ n_ccam=n_ccam,
80
+ n_das=n_das,
81
+ ghm5_pattern=ghm5_pattern,
82
+ )
83
+ df = pipeline.get_scenario(df)
84
+
85
+ output_dir = pipeline.config.get("data", {}).get("output")
86
+ if output_dir:
87
+ output_dir = Path(output_dir)
88
+ output_dir.mkdir(parents=True, exist_ok=True)
89
+
90
+ output_path = output_dir / (
91
+ f"{pipeline_name}_scenarios_{df.height}_"
92
+ f"{datetime.now().strftime('%Y%m%d_%H%M%S')}.parquet"
93
+ )
94
+
95
+ df.write_parquet(output_path)
96
+ print(f"Scénarios sauvegardés dans {output_path}")
97
+
98
+ if pipeline_name == "profile_generation" and prompt_dir is not None:
99
+ from genpatientprofile.sites.aphp.prompt_sets import (
100
+ resolve_prompt_set,
101
+ snapshot_external_prompt_set,
102
+ )
103
+
104
+ resolved_prompt_set = resolve_prompt_set(
105
+ prompt_set=prompt_set,
106
+ prompt_dir=prompt_dir,
107
+ workflow=prompt_workflow,
108
+ )
109
+ snapshot_path = snapshot_external_prompt_set(
110
+ resolved_prompt_set,
111
+ output_dir,
112
+ )
113
+ if snapshot_path is not None:
114
+ print(f"Jeu de prompts sauvegardé dans {snapshot_path}")
115
+
116
+ return df
@@ -0,0 +1,52 @@
1
+ """Fictive stay generation — common primitives for sampling hospital stays.
2
+
3
+ This module provides shared building blocks for generating fictitious
4
+ hospital stays from PMSI data. It is used by both the Brest and AP-HP
5
+ pipelines to ensure consistent sampling logic and reduce code duplication.
6
+
7
+ Responsibilities:
8
+ - Generate fictitious hospital stays from PMSI data (Brest/AP-HP).
9
+ - Ensure consistent sampling logic across pipelines.
10
+ - Reduce code duplication between pipelines.
11
+
12
+ Public API:
13
+ - :func:`generate_fictive_stays`: Generate fictitious stays for a given pipeline.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Any
19
+
20
+ import polars as pl
21
+
22
+ # ---------------------------------------------------------------------------
23
+ # Common fictive-generation helpers
24
+ # ---------------------------------------------------------------------------
25
+
26
+
27
+ def generate_fictive_stays(
28
+ data: dict[str, pl.LazyFrame],
29
+ generate_fn,
30
+ n_sejours: int = 1000,
31
+ **kwargs: Any,
32
+ ) -> pl.DataFrame:
33
+ """Generate fictitious stays via weighted PMSI sampling.
34
+
35
+ Parameters
36
+ ----------
37
+ data:
38
+ Dict of LazyFrames returned by the pipeline's ``load_data`` method.
39
+ n_sejours:
40
+ Number of fictitious stays to generate.
41
+ generate_fn:
42
+ Function to generate dictive stay
43
+ **kwargs:
44
+ Additional pipeline-specific arguments (e.g., ``n_ccam``, ``n_das``
45
+ for Brest; ``seed`` for AP-HP).
46
+
47
+ Returns
48
+ -------
49
+ pl.DataFrame
50
+ One row per fictitious stay. Columns depend on the pipeline type.
51
+ """
52
+ return generate_fn(data, n_sejours, **kwargs)
@@ -0,0 +1,31 @@
1
+ import warnings
2
+ from pathlib import Path
3
+
4
+ from genpatientprofile.sites.aphp.pipeline import APHPPipeline
5
+ from genpatientprofile.sites.brest.pipeline import BrestPipeline
6
+
7
+ PIPELINES = {
8
+ "pmsi_sampling": BrestPipeline,
9
+ "profile_generation": APHPPipeline,
10
+ }
11
+
12
+ PIPELINE_ALIASES = {
13
+ "brest": "pmsi_sampling",
14
+ "aphp": "profile_generation",
15
+ }
16
+
17
+ PIPELINE_NAMES = (*PIPELINES, *PIPELINE_ALIASES)
18
+
19
+
20
+ def resolve_pipeline_name(name: str) -> str:
21
+ canonical_name = PIPELINE_ALIASES.get(name, name)
22
+ if name in PIPELINE_ALIASES:
23
+ warnings.warn(
24
+ f"Le pipeline '{name}' est déprécié ; utiliser '{canonical_name}'.",
25
+ FutureWarning,
26
+ stacklevel=2,
27
+ )
28
+ return canonical_name
29
+
30
+
31
+ CONFIG_DIR = Path(__file__).resolve().parent / "config"
@@ -0,0 +1,51 @@
1
+ """Scenario transformation — common primitives for formatting clinical scenarios.
2
+
3
+ This module provides shared building blocks for transforming fictitious
4
+ hospital stays into text scenarios ready for LLM prompting. It is used
5
+ by both the Brest and AP-HP pipelines to ensure consistent formatting
6
+ logic and reduce code duplication.
7
+
8
+ Responsibilities:
9
+ - Transform fictitious stays into text scenarios for LLM prompting.
10
+ - Ensure consistent formatting logic across pipelines.
11
+ - Reduce code duplication between pipelines.
12
+
13
+ Public API:
14
+ - :func:`format_scenarios`: Format scenarios for a given pipeline.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Any
20
+
21
+ import polars as pl
22
+
23
+ # ---------------------------------------------------------------------------
24
+ # Common scenario-transformation helpers
25
+ # ---------------------------------------------------------------------------
26
+
27
+
28
+ def format_scenarios(
29
+ df: pl.DataFrame,
30
+ scenario_fn,
31
+ **kwargs: Any,
32
+ ) -> pl.DataFrame:
33
+ """Format fictitious stays as text scenarios for the LLM.
34
+
35
+ Parameters
36
+ ----------
37
+ df:
38
+ DataFrame of fictitious stays (output of ``generate_fictive_stays``).
39
+ scenario_fn:
40
+ Fucntion to generate scenario
41
+ **kwargs:
42
+ Additional pipeline-specific arguments (e.g., ``cancer_codes``,
43
+ ``atih_rules`` for AP-HP).
44
+
45
+ Returns
46
+ -------
47
+ pl.DataFrame
48
+ Input DataFrame with an added ``scenario`` column containing the
49
+ formatted text prompt.
50
+ """
51
+ return scenario_fn(df, **kwargs)
File without changes
@@ -0,0 +1,17 @@
1
+ """AP-HP pipeline modules.
2
+
3
+ This package exposes the AP-HP-specific modules used by the AP-HP pipeline.
4
+ """
5
+
6
+ from genpatientprofile.sites.aphp import (
7
+ loader,
8
+ scenario,
9
+ managment,
10
+ prompt,
11
+ sampler,
12
+ constants,
13
+ )
14
+
15
+ from genpatientprofile.sites.aphp.pipeline import APHPPipeline
16
+
17
+ __all__ = ["loader", "scenario", "managment", "prompt", "sampler", "constants", "APHPPipeline"]
@@ -0,0 +1,311 @@
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import json
5
+ import re
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Any, Iterable, Mapping
9
+
10
+
11
+ _MISSING_VALUES = {"", "NA", "NAN", "NONE", "NULL"}
12
+ _CODE_RE = re.compile(r"\b[A-Z][0-9]{2}\.?[0-9A-Z]*\b")
13
+
14
+
15
+ def normalize_icd_code(value: Any) -> str:
16
+ """Return a canonical ICD-10 code.
17
+
18
+ Examples
19
+ --------
20
+ A014 -> A01.4
21
+ A01.4 -> A01.4
22
+ C50. -> C50
23
+ C50 -> C50
24
+ D839 -> D83.9
25
+ """
26
+ if value is None:
27
+ return ""
28
+
29
+ code = str(value).strip().upper()
30
+ code = code.strip("()[]{};:,")
31
+ code = code.replace(" ", "")
32
+ code = code.rstrip(".")
33
+ code = code.rstrip("+*")
34
+
35
+ if code in _MISSING_VALUES:
36
+ return ""
37
+
38
+ if not re.fullmatch(r"[A-Z][0-9]{2}\.?[0-9A-Z]*", code):
39
+ return ""
40
+
41
+ if "." in code:
42
+ return code
43
+
44
+ if len(code) > 3:
45
+ return f"{code[:3]}.{code[3:]}"
46
+
47
+ return code
48
+
49
+
50
+ def category_code(value: Any) -> str:
51
+ code = normalize_icd_code(value)
52
+ if len(code) < 3:
53
+ return ""
54
+ return code[:3]
55
+
56
+
57
+ def _read_index(index_path: Path) -> list[dict[str, str]]:
58
+ if not index_path.exists():
59
+ return []
60
+
61
+ text = index_path.read_text(encoding="utf-8-sig")
62
+ sample = text[:4096]
63
+
64
+ try:
65
+ dialect = csv.Sniffer().sniff(sample, delimiters="\t,;")
66
+ except csv.Error:
67
+ dialect = csv.excel_tab
68
+
69
+ rows: list[dict[str, str]] = []
70
+ for row in csv.DictReader(text.splitlines(), dialect=dialect):
71
+ rows.append({str(k): str(v) for k, v in row.items() if k is not None})
72
+ return rows
73
+
74
+
75
+ def _extract_codes_from_value(value: Any) -> list[str]:
76
+ if value is None:
77
+ return []
78
+
79
+ if isinstance(value, (list, tuple, set)):
80
+ codes: list[str] = []
81
+ for item in value:
82
+ codes.extend(_extract_codes_from_value(item))
83
+ return codes
84
+
85
+ text = str(value).strip()
86
+ if text.upper() in _MISSING_VALUES:
87
+ return []
88
+
89
+ codes = []
90
+ for match in _CODE_RE.findall(text.upper()):
91
+ code = normalize_icd_code(match)
92
+ if code:
93
+ codes.append(code)
94
+ return codes
95
+
96
+
97
+ def extract_icd_codes_from_scenario(row: Mapping[str, Any]) -> list[str]:
98
+ """Extract ICD-10 codes from a generated AP-HP scenario row.
99
+
100
+ Prefer structured fields. Fallback to text_secondary_icd_official only for DAS.
101
+ """
102
+ ordered_keys = [
103
+ # DP
104
+ "icd_primary_code",
105
+ "diagnostic_principal_code",
106
+ "primary_icd_code",
107
+ "dp",
108
+ # DR / MDP if present
109
+ "icd_related_code",
110
+ "related_icd_code",
111
+ "diagnostic_relie_code",
112
+ "dr",
113
+ "mdp",
114
+ # DAS
115
+ "icd_secondary_code",
116
+ "secondary_icd_codes",
117
+ "diagnostic_associes",
118
+ "diagnostics_associes",
119
+ "das",
120
+ "secondary_diagnoses",
121
+ ]
122
+
123
+ codes: list[str] = []
124
+
125
+ for key in ordered_keys:
126
+ if key in row:
127
+ codes.extend(_extract_codes_from_value(row.get(key)))
128
+
129
+ if not codes and "text_secondary_icd_official" in row:
130
+ codes.extend(_extract_codes_from_value(row.get("text_secondary_icd_official")))
131
+
132
+ deduped: list[str] = []
133
+ seen: set[str] = set()
134
+
135
+ for code in codes:
136
+ if code and code not in seen:
137
+ deduped.append(code)
138
+ seen.add(code)
139
+
140
+ return deduped
141
+
142
+
143
+ @dataclass(frozen=True)
144
+ class CodeCard:
145
+ input_code: str
146
+ card_code: str
147
+ card_type: str
148
+ path: Path
149
+ text: str
150
+
151
+
152
+ @dataclass(frozen=True)
153
+ class CodeCardsResult:
154
+ codes: list[str]
155
+ found_codes: list[str]
156
+ missing_codes: list[str]
157
+ text: str
158
+
159
+
160
+ @dataclass
161
+ class CodeCardsRegistry:
162
+ exact_dir: Path
163
+ category_dir: Path
164
+ exact_index: dict[str, Path]
165
+ category_index: dict[str, Path]
166
+
167
+ @classmethod
168
+ def from_dirs(
169
+ cls,
170
+ exact_dir: Path,
171
+ category_dir: Path,
172
+ ) -> CodeCardsRegistry:
173
+ exact_index: dict[str, Path] = {}
174
+ category_index: dict[str, Path] = {}
175
+
176
+ # Contrat recode-icd (docs/livraison/CONTRAT.md, format_version 1) :
177
+ # la colonne canonique du chemin est `fichier` ; `filepath` est le
178
+ # nom historique, accepté en repli pour les bibliothèques
179
+ # antérieures au contrat.
180
+ for row in _read_index(exact_dir / "index.csv"):
181
+ code = normalize_icd_code(row.get("code"))
182
+ filepath = row.get("fichier") or row.get("filepath")
183
+ if code and filepath:
184
+ exact_index[code] = exact_dir / filepath
185
+
186
+ for row in _read_index(category_dir / "index.csv"):
187
+ code = category_code(row.get("code"))
188
+ filepath = row.get("fichier") or row.get("filepath")
189
+ if code and filepath:
190
+ category_index[code] = category_dir / filepath
191
+
192
+ return cls(
193
+ exact_dir=exact_dir,
194
+ category_dir=category_dir,
195
+ exact_index=exact_index,
196
+ category_index=category_index,
197
+ )
198
+
199
+ def find(self, code: str) -> CodeCard | None:
200
+ normalized = normalize_icd_code(code)
201
+ if not normalized:
202
+ return None
203
+
204
+ exact_path = self.exact_index.get(normalized)
205
+ if exact_path and exact_path.exists():
206
+ return CodeCard(
207
+ input_code=code,
208
+ card_code=normalized,
209
+ card_type="code",
210
+ path=exact_path,
211
+ text=exact_path.read_text(encoding="utf-8"),
212
+ )
213
+
214
+ cat = category_code(normalized)
215
+ category_path = self.category_index.get(cat)
216
+ if cat and category_path and category_path.exists():
217
+ return CodeCard(
218
+ input_code=code,
219
+ card_code=cat,
220
+ card_type="category",
221
+ path=category_path,
222
+ text=category_path.read_text(encoding="utf-8"),
223
+ )
224
+
225
+ return None
226
+
227
+ def build_prompt_section(self, codes: Iterable[str]) -> CodeCardsResult:
228
+ found: list[CodeCard] = []
229
+ missing: list[str] = []
230
+
231
+ seen_cards: set[tuple[str, str]] = set()
232
+ normalized_codes: list[str] = []
233
+
234
+ for raw_code in codes:
235
+ code = normalize_icd_code(raw_code)
236
+ if not code:
237
+ continue
238
+
239
+ normalized_codes.append(code)
240
+ card = self.find(code)
241
+
242
+ if card is None:
243
+ missing.append(code)
244
+ continue
245
+
246
+ key = (card.card_type, card.card_code)
247
+ if key not in seen_cards:
248
+ found.append(card)
249
+ seen_cards.add(key)
250
+
251
+ if not found:
252
+ return CodeCardsResult(
253
+ codes=normalized_codes,
254
+ found_codes=[],
255
+ missing_codes=missing,
256
+ text="",
257
+ )
258
+
259
+ parts = [
260
+ "**FICHES DESCRIPTIVES DES CODES CIM-10 DU SCÉNARIO :**",
261
+ "",
262
+ "Les fiches ci-dessous précisent le périmètre des codes CIM-10 présents dans le scénario.",
263
+ "Elles doivent être utilisées pour choisir des formulations compatibles avec les codes, sans ajouter de diagnostic non codé.",
264
+ "",
265
+ ]
266
+
267
+ for card in found:
268
+ parts.append(card.text.strip())
269
+ parts.append("")
270
+
271
+ return CodeCardsResult(
272
+ codes=normalized_codes,
273
+ found_codes=[card.card_code for card in found],
274
+ missing_codes=missing,
275
+ text="\n".join(parts).strip(),
276
+ )
277
+
278
+
279
+ def append_code_cards_to_user_prompt(
280
+ user_prompt: str,
281
+ cards_text: str,
282
+ ) -> str:
283
+ if not cards_text:
284
+ return user_prompt
285
+ return user_prompt.rstrip() + "\n\n" + cards_text.strip() + "\n"
286
+
287
+
288
+ def add_code_cards_to_row(
289
+ row: Mapping[str, Any],
290
+ registry: CodeCardsRegistry,
291
+ ) -> dict[str, Any]:
292
+ out = dict(row)
293
+
294
+ codes = extract_icd_codes_from_scenario(out)
295
+ result = registry.build_prompt_section(codes)
296
+
297
+ out["code_cards_codes"] = json.dumps(result.codes, ensure_ascii=False)
298
+ out["code_cards_found_codes"] = json.dumps(result.found_codes, ensure_ascii=False)
299
+ out["code_cards_missing_codes"] = json.dumps(
300
+ result.missing_codes,
301
+ ensure_ascii=False,
302
+ )
303
+ out["code_cards_text"] = result.text
304
+
305
+ if result.text and out.get("user_prompt"):
306
+ out["user_prompt"] = append_code_cards_to_user_prompt(
307
+ str(out["user_prompt"]),
308
+ result.text,
309
+ )
310
+
311
+ return out