-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlatex_generator.py
More file actions
853 lines (712 loc) · 39.1 KB
/
Copy pathlatex_generator.py
File metadata and controls
853 lines (712 loc) · 39.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
#!/usr/bin/env python3
"""
Générateur LaTeX EXHAUSTIF - Version ManualMiner
Utilise TOUTES les données extraites par Gemini avec branding ManualMiner
"""
import os
import json
import subprocess
import tempfile
import shutil
from pathlib import Path
from datetime import datetime
from typing import Dict, List
import logging
logger = logging.getLogger(__name__)
class LatexSynthesisGenerator:
"""Générateur LaTeX EXHAUSTIF - Toutes les informations médicales avec branding ManualMiner"""
def __init__(self):
"""Initialise avec vérification LaTeX optimisée"""
self.verify_latex_installation()
def verify_latex_installation(self):
"""Vérifie LaTeX avec vérification minimale"""
try:
result = subprocess.run(['pdflatex', '--version'],
capture_output=True, text=True, timeout=5)
if result.returncode != 0:
raise RuntimeError("LaTeX installé mais non fonctionnel")
logger.info("✅ LaTeX détecté et prêt pour ManualMiner")
except FileNotFoundError:
raise RuntimeError(
"❌ ERREUR CRITIQUE: LaTeX non installé\n"
"Installation requise pour ManualMiner:\n"
"- Windows: MiKTeX (https://miktex.org/download)\n"
"- Linux: sudo apt-get install texlive-latex-base texlive-latex-extra\n"
"- Mac: MacTeX (https://tug.org/mactex/)\n"
"AUCUNE alternative possible pour matériel médical"
)
except subprocess.TimeoutExpired:
raise RuntimeError("❌ ERREUR: LaTeX ne répond pas")
except Exception as e:
raise RuntimeError(f"❌ ERREUR LaTeX: {e}")
def generate_latex_synthesis(self, synthesis: Dict, output_path: Path, manual_name: str, language: str = 'fr') -> bool:
"""Génère un PDF médical EXHAUSTIF avec branding ManualMiner"""
try:
# Validation des données
self.validate_synthesis_data(synthesis, manual_name)
# Créer document LaTeX COMPLET avec branding ManualMiner
latex_content = self.create_comprehensive_latex_document(synthesis, manual_name, language)
# Compilation avec timeout généreux
success = self.compile_latex_comprehensive(latex_content, output_path, manual_name)
if not success:
logger.error("❌ ÉCHEC COMPILATION LaTeX ManualMiner")
return False
# Validation finale
if not output_path.exists() or output_path.stat().st_size < 10000:
logger.error("❌ PDF ManualMiner généré trop petit")
if output_path.exists():
output_path.unlink()
return False
logger.info(f"✅ SYNTHÈSE MÉDICALE ManualMiner PDF GÉNÉRÉE: {output_path}")
return True
except Exception as e:
logger.error(f"❌ ERREUR GÉNÉRATION ManualMiner: {e}")
if output_path.exists():
try:
output_path.unlink()
except:
pass
return False
def validate_synthesis_data(self, synthesis: Dict, manual_name: str):
"""Validation rapide des données"""
if not synthesis:
raise ValueError("❌ Données de synthèse vides")
if not manual_name or not manual_name.strip():
raise ValueError("❌ Nom du manuel manquant")
logger.info("✅ Données validées pour génération ManualMiner")
def create_comprehensive_latex_document(self, synthesis: Dict, manual_name: str, language: str = 'fr') -> str:
"""Crée un document LaTeX EXHAUSTIF avec TOUTES les informations médicales et branding ManualMiner"""
# Traductions pour les sections
translations = {
'fr': {
'title_prefix': 'SYNTHÈSE MÉDICALE',
'generated_by': 'Généré par',
'executive_summary': 'RÉSUMÉ EXÉCUTIF',
'general_info': 'INFORMATIONS GÉNÉRALES',
'procedures': 'PROCÉDURES D\'ANALYSE',
'maintenance': 'MAINTENANCE PRÉVENTIVE',
'daily_usage': 'GUIDE D\'UTILISATION QUOTIDIENNE',
'technical_specs': 'SPÉCIFICATIONS TECHNIQUES',
'security': 'PRÉCAUTIONS DE SÉCURITÉ',
'validation': 'VALIDATION CLINIQUE',
'troubleshooting': 'DÉPANNAGE',
'conclusion': 'CONCLUSION'
},
'en': {
'title_prefix': 'MEDICAL SYNTHESIS',
'generated_by': 'Generated by',
'executive_summary': 'EXECUTIVE SUMMARY',
'general_info': 'GENERAL INFORMATION',
'procedures': 'ANALYSIS PROCEDURES',
'maintenance': 'PREVENTIVE MAINTENANCE',
'daily_usage': 'DAILY USAGE GUIDE',
'technical_specs': 'TECHNICAL SPECIFICATIONS',
'security': 'SAFETY PRECAUTIONS',
'validation': 'CLINICAL VALIDATION',
'troubleshooting': 'TROUBLESHOOTING',
'conclusion': 'CONCLUSION'
}
}
t = translations.get(language, translations['fr'])
# En-tête LaTeX PROFESSIONNEL pour document médical ManualMiner
latex_header = r"""
\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[margin=1.8cm]{geometry}
\usepackage[table,xcdraw]{xcolor}
\usepackage{array}
\usepackage{longtable}
\usepackage{fancyhdr}
\usepackage{enumitem}
\usepackage{multicol}
\usepackage{titlesec}
% Couleurs ManualMiner médicales professionnelles
\definecolor{manualblue}{RGB}{0,100,200}
\definecolor{manualred}{RGB}{180,0,0}
\definecolor{manualgreen}{RGB}{0,120,0}
\definecolor{manualorange}{RGB}{230,120,0}
\definecolor{lightblue}{RGB}{240,248,255}
\definecolor{lightgreen}{RGB}{245,255,245}
\definecolor{lightred}{RGB}{255,245,245}
\definecolor{lightorange}{RGB}{255,250,240}
% En-têtes professionnels ManualMiner
\pagestyle{fancy}
\fancyhf{}
\rhead{\textcolor{manualblue}{\textbf{ManualMiner - SYNTHÈSE INSTRUMENT MÉDICAL}}}
\lhead{\textcolor{manualblue}{\small\today}}
\rfoot{\textcolor{manualblue}{\textbf{\thepage}}}
\lfoot{\textcolor{manualgreen}{\textbf{© Paul Archer - ManualMiner}}}
% Formatage des sections
\titleformat{\section}{\large\bfseries\color{manualblue}}{\thesection}{1em}{}
\titleformat{\subsection}{\normalsize\bfseries\color{manualgreen}}{\thesubsection}{1em}{}
\title{\textcolor{manualblue}{\Large\textbf{ManualMiner}} \\ \vspace{0.2cm} \textcolor{manualblue}{\large FICHE TECHNIQUE MÉDICALE} \\ \vspace{0.3cm} \textcolor{manualblue}{\large """ + self.escape_latex_advanced(manual_name[:70]) + r"""}}
\author{}
\date{\today}
\begin{document}
\maketitle
\thispagestyle{fancy}
% Avertissement médical professionnel ManualMiner
\begin{center}
\colorbox{lightred}{\parbox{0.95\textwidth}{\centering
\textcolor{manualred}{\textbf{DOCUMENT TECHNIQUE PROFESSIONNEL ManualMiner}} \\
Synthèse technique automatique complète - Vérification recommandée avant usage \\
Respecter impérativement les procédures du manuel complet \\
\textbf{ManualMiner v1.0 - Paul Archer}}}
\end{center}
\vspace{0.5cm}
"""
latex_body = ""
# 1. Résumé exécutif COMPLET avec branding
if synthesis.get("resume_executif"):
latex_body += rf"""
\section*{{{t['executive_summary']}}}
\colorbox{{lightblue}}{{\parbox{{0.98\textwidth}}{{\textbf{{ManualMiner - {t['generated_by']}:}} """ + self.escape_latex_advanced(synthesis["resume_executif"]) + r"""}}}}
\vspace{0.5cm}
"""
# 2. Informations générales DÉTAILLÉES
if synthesis.get("informations_generales"):
latex_body += self.generate_detailed_info_section(synthesis["informations_generales"])
# 3. Procédures d'analyse EXHAUSTIVES
if synthesis.get("procedures_analyses"):
latex_body += self.generate_exhaustive_procedures_section(synthesis["procedures_analyses"])
# 4. Maintenance préventive COMPLÈTE
if synthesis.get("maintenance_preventive"):
latex_body += self.generate_complete_maintenance_section(synthesis["maintenance_preventive"])
# 5. Guide d'utilisation quotidienne
if synthesis.get("guide_utilisation_quotidienne"):
latex_body += self.generate_daily_usage_section(synthesis["guide_utilisation_quotidienne"])
# 6. Spécifications techniques
if synthesis.get("specifications_techniques"):
latex_body += self.generate_technical_specs_section(synthesis["specifications_techniques"])
# Pied de document médical professionnel ManualMiner
latex_footer = r"""
\vfill
\begin{center}
\colorbox{lightred}{\parbox{0.95\textwidth}{\centering
\textcolor{manualred}{\textbf{RESPONSABILITÉ TECHNIQUE PROFESSIONNELLE}} \\
L'utilisateur reste entièrement responsable de la validation des informations, \\
de la sécurité d'utilisation et de l'interprétation des données. \\
Toujours vérifier les procédures critiques dans le manuel complet.}}
\end{center}
\vspace{0.3cm}
\begin{center}
\textcolor{manualblue}{\textbf{© Paul Archer - ManualMiner}} \\
\textcolor{manualblue}{\small Synthèse automatique générée le """ + datetime.now().strftime("%d/%m/%Y à %H:%M") + r"""}
\end{center>
\end{document}
"""
return latex_header + latex_body + latex_footer
# [Le reste des méthodes reste identique à votre version originale,
# mais avec les couleurs ManualMiner et les références mises à jour]
def escape_latex_advanced(self, text: str) -> str:
"""Échappement LaTeX AVANCÉ pour préserver toutes les informations"""
if not isinstance(text, str):
text = str(text)
if not text.strip():
return "Non spécifié"
# Échappement complet pour préserver toutes les informations
replacements = {
'\\': r'\textbackslash{}',
'&': r'\&',
'%': r'\%',
'$': r'\$',
'#': r'\#',
'_': r'\_',
'{': r'\{',
'}': r'\}',
'^': r'\textasciicircum{}',
'~': r'\textasciitilde{}',
'°': r'$^\circ$',
'µ': r'$\mu$',
'≤': r'$\leq$',
'≥': r'$\geq$',
'±': r'$\pm$',
'→': r'$\rightarrow$',
'←': r'$\leftarrow$',
'↔': r'$\leftrightarrow$'
}
for char, escaped in replacements.items():
text = text.replace(char, escaped)
# Nettoyer les caractères de contrôle mais préserver les retours à la ligne
import re
text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]', ' ', text)
return text
def generate_detailed_info_section(self, info: Dict) -> str:
"""Section informations générales EXHAUSTIVE avec branding ManualMiner"""
section = r"""
\section*{INFORMATIONS TECHNIQUES GÉNÉRALES}
\begin{longtable}{|>{\bfseries}p{4cm}|p{11cm}|}
\hline
\rowcolor{lightblue}
\multicolumn{2}{|c|}{\textcolor{manualblue}{\textbf{IDENTIFICATION INSTRUMENT - ManualMiner}}} \\
\hline
\endfirsthead
\hline
\rowcolor{lightblue}
\multicolumn{2}{|c|}{\textcolor{manualblue}{\textbf{IDENTIFICATION INSTRUMENT (suite)}}} \\
\hline
\endhead
"""
fields = {
"nom_instrument": "Instrument",
"fabricant": "Fabricant",
"modele": "Modèle",
"type_instrument": "Type/Technologie",
"principe_fonctionnement": "Principe technique",
"approche_diagnostique": "Méthodologie diagnostique"
}
for key, label in fields.items():
if key in info and info[key]:
value = str(info[key])
section += f"{label} & {self.escape_latex_advanced(value)} \\\\\n\\hline\n"
# Applications cliniques DÉTAILLÉES
if info.get("applications_principales"):
section += "Applications cliniques & "
apps_list = []
for i, app in enumerate(info["applications_principales"][:8]):
apps_list.append(f"\\textbf{{{i+1}.}} {self.escape_latex_advanced(str(app))}")
apps_text = " \\\\ ".join(apps_list)
section += f"{apps_text} \\\\\n\\hline\n"
section += r"""
\end{longtable}
\vspace{0.5cm}
"""
return section
# [Inclure toutes les autres méthodes de votre fichier original avec les ajustements de couleurs ManualMiner]
def compile_latex_comprehensive(self, latex_content: str, output_path: Path, manual_name: str) -> bool:
"""Compilation LaTeX EXHAUSTIVE avec timeout généreux et branding ManualMiner"""
try:
with tempfile.TemporaryDirectory() as temp_dir:
temp_dir_path = Path(temp_dir)
# Fichier LaTeX
tex_file = temp_dir_path / "manualminer_synthesis.tex"
with open(tex_file, 'w', encoding='utf-8') as f:
f.write(latex_content)
logger.info(f"📄 Compilation LaTeX ManualMiner: {manual_name[:50]}")
# Configuration optimisée pour document médical ManualMiner
env = dict(os.environ)
env.update({
'MIKTEX_AUTOINSTALL': 'No',
'MIKTEX_UPDATE_CHECK': 'No',
'max_print_line': '2000',
'error_line': '500',
'half_error_line': '100'
})
cmd = [
'pdflatex',
'-interaction=batchmode',
'-file-line-error',
'-no-shell-escape',
'-output-directory', str(temp_dir_path),
str(tex_file)
]
logger.info("⏱️ Démarrage compilation ManualMiner (timeout 120s)...")
# Première passe
result1 = subprocess.run(
cmd,
capture_output=True,
text=True,
cwd=temp_dir_path,
timeout=120,
env=env
)
# Deuxième passe pour les références croisées
logger.info("Deuxième passe LaTeX ManualMiner...")
result2 = subprocess.run(
cmd,
capture_output=True,
text=True,
cwd=temp_dir_path,
timeout=120,
env=env
)
# Vérifier PDF généré (priorité au résultat)
pdf_file = temp_dir_path / "manualminer_synthesis.pdf"
if pdf_file.exists() and pdf_file.stat().st_size > 5000:
logger.info(f"PDF ManualMiner généré: {pdf_file.stat().st_size:,} bytes")
# Copie vers destination
shutil.copy2(pdf_file, output_path)
if output_path.exists():
final_size = output_path.stat().st_size
logger.info(f"PDF médical ManualMiner créé: {final_size:,} bytes")
return True
# Échec - diagnostics détaillés
logger.error(f"Compilation échouée ManualMiner (codes {result1.returncode}, {result2.returncode})")
# Diagnostics spécifiques pour document exhaustif
stderr1 = result1.stderr.lower()
stdout1 = result1.stdout.lower()
if "memory" in stderr1 or "capacity exceeded" in stderr1:
logger.error("Document trop volumineux pour LaTeX")
logger.error(" 1. Le document ManualMiner est très complet, normal pour usage médical")
logger.error(" 2. Augmenter la mémoire LaTeX si possible")
elif "emergency stop" in stdout1 or "fatal error" in stdout1:
logger.error("Erreur dans le document LaTeX ManualMiner")
logger.error(" Document très détaillé, certains caractères spéciaux posent problème")
else:
logger.error("Diagnostic: Document LaTeX ManualMiner complexe")
logger.error(f" STDERR: {result1.stderr[:300]}")
return False
except subprocess.TimeoutExpired:
logger.error("TIMEOUT compilation LaTeX ManualMiner (120s)")
logger.error("Document médical très complet, compilation longue normale")
logger.error(" Solutions:")
logger.error(" 1. Le document contient beaucoup d'informations (normal)")
logger.error(" 2. Augmenter le timeout si nécessaire")
return False
except Exception as e:
logger.error(f"ERREUR critique compilation ManualMiner: {e}")
return False
def generate_exhaustive_procedures_section(self, procedures: List[Dict]) -> str:
"""Section procédures d'analyse EXHAUSTIVE avec toutes les informations"""
section = r"""
\section*{PROCÉDURES D'ANALYSE MÉDICALES}
"""
for i, proc in enumerate(procedures[:6]): # Maximum 6 procédures pour éviter PDF trop long
section += f"\\subsection*{{\\textcolor{{manualgreen}}{{{i+1}. {self.escape_latex_advanced(proc.get('nom_analyse', f'Analyse {i+1}')[:60])}}}}}\n\n"
# Indication clinique
if proc.get('indication_clinique'):
section += f"\\textbf{{\\textcolor{{manualorange}}{{Indication clinique:}}}} {self.escape_latex_advanced(proc['indication_clinique'][:200])}\n\n"
section += "\\vspace{0.3cm}\n"
# Informations échantillon COMPLÈTES
echantillon = proc.get('echantillon', {})
if echantillon and isinstance(echantillon, dict):
section += "\\textbf{\\textcolor{manualblue}{ÉCHANTILLON DÉTAILLÉ:}}\n"
section += "\\begin{itemize}[leftmargin=1cm]\n"
for field, label in [
('type', 'Type'), ('volume_minimum', 'Volume minimum'),
('volume_traitement', 'Volume traitement'), ('anticoagulant', 'Anticoagulant')
]:
if echantillon.get(field):
section += f"\\item \\textbf{{{label}:}} {self.escape_latex_advanced(str(echantillon[field])[:100])}\n"
section += "\\end{itemize}\n\n"
section += "\\vspace{0.3cm}\n"
# Préparation détaillée COMPLÈTE
preparation = proc.get('preparation_detaillee', {})
if preparation and isinstance(preparation, dict):
if preparation.get('etapes'):
section += "\\textbf{\\textcolor{manualgreen}{PRÉPARATION ÉCHANTILLON:}}\n"
section += "\\begin{enumerate}[leftmargin=1cm]\n"
for j, step in enumerate(preparation['etapes'][:8]): # Max 8 étapes
section += f"\\item {self.escape_latex_advanced(str(step)[:150])}\n"
section += "\\end{enumerate}\n"
# Conditions de stockage/stabilité
if preparation.get('stabilite'):
section += f"\\textbf{{Stabilité:}} {self.escape_latex_advanced(str(preparation['stabilite'])[:200])}\n\n"
if preparation.get('stockage'):
section += f"\\textbf{{Stockage:}} {self.escape_latex_advanced(str(preparation['stockage'])[:200])}\n\n"
section += "\\vspace{0.3cm}\n"
# Procédure analytique
procedure_ana = proc.get('procedure_analytique', {})
if procedure_ana and isinstance(procedure_ana, dict):
if procedure_ana.get('workflow'):
section += "\\textbf{\\textcolor{manualgreen}{PROCÉDURE ANALYTIQUE:}}\n"
section += "\\begin{enumerate}[leftmargin=1cm]\n"
for j, step in enumerate(procedure_ana['workflow'][:10]): # Max 10 étapes
section += f"\\item {self.escape_latex_advanced(str(step)[:180])}\n"
section += "\\end{enumerate}\n"
if procedure_ana.get('duree_totale'):
section += f"\\textbf{{Durée totale:}} {self.escape_latex_advanced(str(procedure_ana['duree_totale']))}\n\n"
if procedure_ana.get('conditions_techniques'):
section += f"\\textbf{{Conditions techniques:}} {self.escape_latex_advanced(str(procedure_ana['conditions_techniques'])[:200])}\n\n"
section += "\\vspace{0.3cm}\n"
# Performance analytique (CRITIQUE)
performance = proc.get('performance_analytique', {})
if performance and isinstance(performance, dict):
section += "\\colorbox{lightorange}{\\parbox{0.98\\textwidth}{\n"
section += "\\textbf{\\textcolor{manualorange}{PERFORMANCE ANALYTIQUE:}} \\\\\n"
for field, label in [
('gamme_mesure', 'Gamme mesure'), ('limite_detection', 'Limite détection'),
('limite_quantification', 'Limite quantification'), ('precision', 'Précision'),
('sensibilite_clinique', 'Sensibilité clinique'), ('specificite_clinique', 'Spécificité clinique')
]:
if performance.get(field):
section += f"\\textbf{{{label}:}} {self.escape_latex_advanced(str(performance[field])[:120])} \\\\\n"
section += "}}\n\n"
section += "\\vspace{0.3cm}\n"
# Contrôles qualité
controles = proc.get('controles_qualite', {})
if controles and isinstance(controles, dict):
if controles.get('types_controles'):
section += "\\textbf{\\textcolor{manualblue}{CONTRÔLES QUALITÉ:}}\n"
section += "\\begin{itemize}[leftmargin=1cm]\n"
for ctrl in controles['types_controles'][:6]:
section += f"\\item {self.escape_latex_advanced(str(ctrl)[:120])}\n"
if controles.get('frequence'):
section += f"\\item \\textbf{{Fréquence:}} {self.escape_latex_advanced(str(controles['frequence'])[:80])}\n"
section += "\\end{itemize}\n\n"
section += "\\vspace{0.3cm}\n"
# Précautions critiques (SÉCURITÉ)
if proc.get('precautions_critiques'):
section += "\\begin{center}\n"
section += "\\colorbox{lightred}{\\parbox{0.95\\textwidth}{\n"
section += "\\textbf{\\textcolor{manualred}{PRÉCAUTIONS CRITIQUES:}} \\\\\n"
for j, prec in enumerate(proc['precautions_critiques'][:5]):
section += f"\\textbf{{{j+1}.}} {self.escape_latex_advanced(str(prec)[:150])} \\\\\n"
section += "}}\n"
section += "\\end{center}\n\n"
section += "\\vspace{0.4cm}\n"
# Saut de page après 3 procédures pour lisibilité
if i == 2 and len(procedures) > 3:
section += "\\newpage\n"
return section
def generate_complete_maintenance_section(self, maintenance: List[Dict]) -> str:
"""Section maintenance préventive EXHAUSTIVE"""
if not maintenance:
return ""
section = r"""
\section*{MAINTENANCE PRÉVENTIVE}
\colorbox{lightorange}{\parbox{0.98\textwidth}{
\textbf{\textcolor{manualorange}{IMPORTANCE CRITIQUE:}} La maintenance préventive est essentielle pour garantir la fiabilité diagnostique, la sécurité des analyses et la validité des résultats.}}
\vspace{0.3cm}
"""
for i, maint in enumerate(maintenance[:8]): # Maximum 8 maintenances
if not isinstance(maint, dict):
continue
section += f"\\subsection*{{\\textcolor{{manualorange}}{{{i+1}. {self.escape_latex_advanced(maint.get('type_maintenance', f'Maintenance {i+1}')[:50])}}}}}\n\n"
# Informations générales DÉTAILLÉES
section += "\\begin{itemize}[leftmargin=1cm]\n"
if maint.get('frequence_precise'):
section += f"\\item \\textbf{{Fréquence:}} {self.escape_latex_advanced(str(maint['frequence_precise'])[:80])}\n"
if maint.get('duree_estimee'):
section += f"\\item \\textbf{{Durée estimée:}} {self.escape_latex_advanced(str(maint['duree_estimee'])[:60])}\n"
if maint.get('niveau'):
section += f"\\item \\textbf{{Niveau:}} {self.escape_latex_advanced(str(maint.get('niveau', 'Personnel qualifié'))[:80])}\n"
section += "\\end{itemize}\n\n"
# Procédure step-by-step COMPLÈTE
procedure = maint.get('procedure_step_by_step', {})
if procedure and isinstance(procedure, dict):
if procedure.get('preparation'):
section += "\\textbf{\\textcolor{manualgreen}{Préparation:}}\n"
section += "\\begin{enumerate}[leftmargin=1cm]\n"
for step in procedure['preparation'][:6]:
section += f"\\item {self.escape_latex_advanced(str(step)[:120])}\n"
section += "\\end{enumerate}\n\n"
if procedure.get('execution'):
section += "\\textbf{\\textcolor{manualgreen}{Exécution:}}\n"
section += "\\begin{enumerate}[leftmargin=1cm]\n"
for step in procedure['execution'][:8]:
section += f"\\item {self.escape_latex_advanced(str(step)[:120])}\n"
section += "\\end{enumerate}\n\n"
if procedure.get('verification'):
section += "\\textbf{\\textcolor{manualblue}{Vérifications:}}\n"
section += "\\begin{itemize}[leftmargin=1cm]\n"
for verif in procedure['verification'][:6]:
section += f"\\item {self.escape_latex_advanced(str(verif)[:100])}\n"
section += "\\end{itemize}\n\n"
# Matériels requis DÉTAILLÉS
if maint.get('materiels_specifiques'):
materials = maint['materiels_specifiques']
if materials:
section += f"\\textbf{{Matériels requis:}} "
materials_text = ', '.join([self.escape_latex_advanced(str(mat)[:60]) for mat in materials[:8]])
section += f"{materials_text}\n\n"
section += "\\vspace{0.3cm}\n"
return section
def generate_daily_usage_section(self, guide: Dict) -> str:
"""Section guide d'utilisation quotidienne EXHAUSTIF"""
section = r"""
\section*{GUIDE D'UTILISATION QUOTIDIENNE}
"""
# Démarrage système COMPLET
if guide.get('demarrage_systeme'):
section += "\\subsection*{\\textcolor{manualgreen}{Démarrage système}}\n"
section += "\\colorbox{lightgreen}{\\parbox{0.98\\textwidth}{\n"
section += "\\begin{enumerate}[leftmargin=0.5cm]\n"
for step in guide['demarrage_systeme'][:8]:
section += f"\\item {self.escape_latex_advanced(str(step)[:120])}\n"
section += "\\end{enumerate}\n"
section += "}}\n\n"
# Workflows disponibles
if guide.get('workflow_type'):
section += "\\subsection*{\\textcolor{manualblue}{Workflows disponibles}}\n"
section += "\\begin{itemize}[leftmargin=1cm]\n"
for workflow in guide['workflow_type'][:6]:
section += f"\\item {self.escape_latex_advanced(str(workflow)[:150])}\n"
section += "\\end{itemize}\n\n"
# Arrêt système COMPLET
if guide.get('arret_systeme'):
section += "\\subsection*{\\textcolor{manualorange}{Arrêt système}}\n"
section += "\\colorbox{lightorange}{\\parbox{0.98\\textwidth}{\n"
section += "\\begin{enumerate}[leftmargin=0.5cm]\n"
for step in guide['arret_systeme'][:8]:
section += f"\\item {self.escape_latex_advanced(str(step)[:120])}\n"
section += "\\end{enumerate}\n"
section += "}}\n\n"
# Contrôle qualité routine DÉTAILLÉ
if guide.get('controle_qualite_routine'):
section += "\\subsection*{\\textcolor{manualblue}{Contrôles qualité routine}}\n"
section += "\\begin{itemize}[leftmargin=1cm]\n"
for ctrl in guide['controle_qualite_routine'][:8]:
section += f"\\item {self.escape_latex_advanced(str(ctrl)[:120])}\n"
section += "\\end{itemize}\n\n"
# Maintenance quotidienne
if guide.get('maintenance_quotidienne'):
section += "\\subsection*{\\textcolor{manualgreen}{Maintenance quotidienne}}\n"
section += "\\begin{itemize}[leftmargin=1cm]\n"
for task in guide['maintenance_quotidienne'][:6]:
section += f"\\item {self.escape_latex_advanced(str(task)[:100])}\n"
section += "\\end{itemize}\n\n"
return section
def generate_technical_specs_section(self, specs: List[Dict]) -> str:
"""Section spécifications techniques (si disponibles)"""
if not specs:
return ""
section = r"""
\section*{SPÉCIFICATIONS TECHNIQUES}
"""
for spec in specs[:4]: # Maximum 4 catégories
if not isinstance(spec, dict):
continue
if spec.get('categorie') and spec.get('parametres_detailles'):
section += f"\\subsection*{{\\textcolor{{manualblue}}{{{self.escape_latex_advanced(spec['categorie'][:50])}}}}}\n\n"
section += "\\begin{longtable}{|>{\\bfseries}p{4cm}|p{5cm}|p{2cm}|p{3cm}|}\n"
section += "\\hline\n"
section += "\\rowcolor{lightblue}\n"
section += "\\textcolor{manualblue}{\\textbf{PARAMÈTRE}} & \\textcolor{manualblue}{\\textbf{VALEUR}} & \\textcolor{manualblue}{\\textbf{UNITÉ}} & \\textcolor{manualblue}{\\textbf{CONDITIONS}} \\\\\n"
section += "\\hline\n"
for param in spec['parametres_detailles'][:10]: # Max 10 paramètres par catégorie
if isinstance(param, dict):
nom = self.escape_latex_advanced(str(param.get('nom', 'Paramètre'))[:35])
valeur = self.escape_latex_advanced(str(param.get('valeur', 'N/A'))[:45])
unite = self.escape_latex_advanced(str(param.get('unite', ''))[:15])
conditions = self.escape_latex_advanced(str(param.get('conditions_mesure', ''))[:30])
section += f"{nom} & {valeur} & {unite} & {conditions} \\\\\n\\hline\n"
section += "\\end{longtable}\n\n"
return section
def test_latex_manualminer():
"""Test du générateur ManualMiner"""
test_synthesis = {
"resume_executif": "Test de génération PDF médical ManualMiner avec toutes les informations détaillées extraites par Gemini 2.0 Flash. Ce document contient l'ensemble des procédures, maintenances et spécifications techniques critiques pour usage médical professionnel avec le nouveau branding ManualMiner.",
"informations_generales": {
"nom_instrument": "Analyseur Test ManualMiner",
"fabricant": "Test Medical Corp",
"modele": "Model-X Pro Advanced",
"type_instrument": "Analyseur médical automatisé haute performance",
"applications_principales": [
"Diagnostic médical de précision",
"Analyses quantitatives en routine",
"Contrôle qualité laboratoire",
"Suivi thérapeutique patient"
],
"principe_fonctionnement": "Principe technique avancé basé sur la technologie de pointe pour analyses médicales de haute précision avec validation clinique complète",
"approche_diagnostique": "Méthodologie diagnostique intégrée avec workflow optimisé pour usage clinique quotidien"
},
"procedures_analyses": [
{
"nom_analyse": "Analyse Test Complète ManualMiner",
"indication_clinique": "Diagnostic et suivi médical pour population cible spécifique avec indications cliniques précises",
"echantillon": {
"type": "Échantillon sanguin EDTA",
"volume_minimum": "500 µL minimum requis",
"volume_traitement": "200 µL pour traitement",
"anticoagulant": "EDTA K3 recommandé"
},
"preparation_detaillee": {
"etapes": [
"Prélèvement selon procédure standard avec précautions aseptiques",
"Centrifugation à 3000 rpm pendant 10 minutes à température ambiante",
"Séparation du plasma avec pipetage soigneux évitant contamination",
"Stockage temporaire à 2-8°C maximum 4 heures avant analyse"
],
"stabilite": "Stable 24h à 2-8°C, 1 semaine à -20°C, 6 mois à -80°C",
"stockage": "Conditions de stockage strictes selon température et durée spécifiées"
},
"procedure_analytique": {
"workflow": [
"Initialisation système avec contrôles qualité obligatoires",
"Chargement échantillons selon protocole validé",
"Analyse automatisée avec surveillance continue paramètres",
"Validation résultats avec contrôles intégrés",
"Génération rapport avec interprétation technique"
],
"duree_totale": "45 minutes par série incluant contrôles",
"conditions_techniques": "Température 18-25°C, humidité <60%, vibrations minimales"
},
"performance_analytique": {
"gamme_mesure": "0.1 - 1000 UI/mL avec linéarité validée",
"limite_detection": "0.05 UI/mL (IC 95%)",
"precision": "CV intra-série <3%, inter-série <5%"
},
"controles_qualite": {
"types_controles": [
"Contrôle négatif: <0.1 UI/mL attendu",
"Contrôle positif bas: 50±15 UI/mL",
"Contrôle positif haut: 500±50 UI/mL"
],
"frequence": "Chaque série d'analyse, minimum quotidien"
},
"precautions_critiques": [
"SÉCURITÉ BIOLOGIQUE: Manipulation échantillons infectieux - EPI complet obligatoire",
"QUALITÉ ANALYTIQUE: Prévention contamination croisée - nettoyage système entre séries"
]
}
],
"maintenance_preventive": [
{
"type_maintenance": "Maintenance quotidienne ManualMiner",
"frequence_precise": "Chaque jour d'utilisation obligatoire",
"duree_estimee": "15-20 minutes selon complexité",
"procedure_step_by_step": {
"preparation": [
"Arrêt complet système selon procédure sécurisée",
"Préparation solutions nettoyage selon concentrations",
"Vérification disponibilité matériels maintenance"
],
"execution": [
"Nettoyage surfaces externes avec solution désinfectante",
"Vidange et rinçage circuits fluidiques internes",
"Contrôle visuel composants critiques usure",
"Test fonctionnel rapide avant remise en service"
],
"verification": [
"Vérification étanchéité circuits après nettoyage",
"Test alarmes et sécurités système",
"Validation paramètres techniques nominaux"
]
},
"materiels_specifiques": [
"Solution nettoyage spécialisée référence XYZ-123",
"Kits consommables maintenance hebdomadaire"
]
}
],
"guide_utilisation_quotidienne": {
"demarrage_systeme": [
"Vérification alimentation électrique et connexions réseau",
"Contrôle niveaux réactifs et consommables disponibles",
"Test fonctionnel système avec séquence diagnostic",
"Validation contrôles qualité journaliers obligatoires"
],
"arret_systeme": [
"Finalisation toutes analyses en cours avec sauvegarde",
"Nettoyage automatique circuits selon programme",
"Sauvegarde données et rapports journaliers",
"Mise en sécurité système pour arrêt prolongé"
],
"maintenance_quotidienne": [
"Contrôle visuel général instrument et accessoires",
"Nettoyage surfaces externes selon produits autorisés",
"Vérification niveaux et péremption réactifs",
"Documentation observations dans registre maintenance"
]
}
}
try:
generator = LatexSynthesisGenerator()
output_path = Path("test_manualminer.pdf")
print("Test générateur LaTeX ManualMiner")
print("=" * 50)
success = generator.generate_latex_synthesis(
test_synthesis, output_path, "Test Médical ManualMiner"
)
if success:
print(f"SUCCÈS: PDF ManualMiner généré")
print(f"Fichier: {output_path}")
print(f"Taille: {output_path.stat().st_size:,} bytes")
print(f"Document complet avec branding ManualMiner")
else:
print("ÉCHEC: Génération impossible")
except Exception as e:
print(f"ERREUR: {e}")
if __name__ == "__main__":
test_latex_manualminer()