GABRIELSZK commited on
Commit
af7acdf
·
verified ·
1 Parent(s): d9b1682

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -50
app.py CHANGED
@@ -28,18 +28,11 @@ faixas = {
28
  "TROPONINA": (0, 0.5)
29
  }
30
 
31
- # Chaves relativas à seção EAS
32
- EAS_KEYS = [
33
- "PROTEINA UR","GLI UR","CETONAS UR","SANGUE UR",
34
- "LEUC ESTERASE","NITRITO UR","LEUCO EAS","HEMA EAS","BACTERIAS UR"
35
- ]
36
-
37
  def classificar(nome, valor):
38
- """Anexa ↓/↑ se fora da faixa."""
39
  try:
40
  v = float(valor.replace(">", "").replace("<", "").strip())
41
- lo, hi = faixas.get(nome, (None, None))
42
- if lo is not None:
43
  if v < lo: return f"{valor} ↓"
44
  if v > hi: return f"{valor} ↑"
45
  return valor
@@ -54,12 +47,9 @@ def melhorar_imagem(img: Image.Image) -> Image.Image:
54
 
55
  # Extrai texto nativo + OCR
56
  def extrair_texto_pdf(pdf_input):
57
- if isinstance(pdf_input, dict):
58
- pdf_path = pdf_input.get("name") or pdf_input.get("file_path")
59
- elif hasattr(pdf_input, "name") and isinstance(pdf_input.name, str):
60
- pdf_path = pdf_input.name
61
- else:
62
- pdf_path = str(pdf_input)
63
 
64
  texto_nativo, ocr_imgs = [], []
65
  with fitz.open(pdf_path) as doc:
@@ -68,7 +58,7 @@ def extrair_texto_pdf(pdf_input):
68
  pix = page.get_pixmap(dpi=300)
69
  img = Image.open(io.BytesIO(pix.tobytes("png")))
70
  ocr_imgs.append(melhorar_imagem(img))
71
- tn = re.sub(r"\s+", " ", " ".join(texto_nativo))
72
  tocr = re.sub(r"\s+", " ", " ".join(pytesseract.image_to_string(im) for im in ocr_imgs))
73
  return tn, tocr
74
 
@@ -110,66 +100,60 @@ exames = {
110
  "TROPONINA": r"troponina(?! qualitativa).*?resultado[:\s]*([>\d.,]+)",
111
  "TROPONINA QUAL": r"troponina qualitativa.*?resultado[:\s]*(positivo|negativo)",
112
  # EAS completo (Urina)
113
- "PROTEINA UR": r"prote[ií]na\s*([A-Za-zÀ-ÿ]+)",
114
- "GLI UR": r"glicose\s*([A-Za-z()]+)",
115
- "CETONAS UR": r"corpos cet[oô]nicos.*?([A-Za-z()]+)",
116
- "SANGUE UR": r"sangue\s*[:\-]?\s*([A-Za-z]+)",
117
- "LEUC ESTERASE": r"leuc[óo]citos? esterase\s*[:\-]?\s*([A-Za-z0-9\+\-]+)",
118
- "NITRITO UR": r"nitrito\s*([A-Za-z()]+)",
119
- "LEUCO EAS": r"leuc[óo]citos?\s*([\d]+[-\/]\d+)",
120
- "HEMA EAS": r"hem[áa]cias?\s*([\d]+[-\/]\d+)",
121
- "BACTERIAS UR": r"bact[ée]rias?\s*([A-Za-z()]+)"
122
  }
123
 
124
- # Ordem para exibição
125
  ordem = [
126
  "LEUCO","B","SS","EOS","LINF","MONO",
127
  "HB","HT","PLT","AMIL","BT","BD","BI",
128
  "CR","UREIA","FAL","GGT","TGO","TGP","GLI","LIP","MG++",
129
  "PCR","CKMB","CPK","TROPONINA","TROPONINA QUAL",
130
- "TAP","INR","TTP","DIMERO D",
131
  # EAS
132
- *EAS_KEYS
133
  ]
134
 
135
  # Montagem do texto formatado
136
- def extrair_exames_formatado(pdf_file):
137
- if not pdf_file:
138
- return "Nenhum arquivo enviado.", None
139
  tn, tocr = extrair_texto_pdf(pdf_file)
140
  texto = (tn + " " + tocr).lower()
141
  resultados = {}
142
- # extrai todos os campos
143
  for nome, pat in exames.items():
144
  m = re.search(pat, texto, re.IGNORECASE)
145
- if m:
146
- raw = m.group(1).strip()
147
- resultados[nome] = raw.upper() if "QUAL" in nome else classificar(nome, raw.replace(",", "."))
148
- # detecta presença de EAS
149
- has_eas = bool(re.search(r"urina jato medio|sedimentoscopia", texto, re.IGNORECASE))
150
- if not has_eas:
151
- for k in EAS_KEYS:
152
- resultados.pop(k, None)
153
- # monta campos
154
- eas_fields = [f"{k}: {resultados[k]}" for k in ordem if k in resultados and k in EAS_KEYS]
155
- main_fields = [f"{r}: {resultados[r]}" for r in ordem if r in resultados and r not in EAS_KEYS]
156
- line_eas = f"🟤 EAS → {' / '.join(eas_fields)}" if eas_fields else ""
157
- line_main = ' / '.join(main_fields)
158
- final = '\n'.join([l for l in (line_eas, line_main) if l]).upper()
159
  # CSV
160
- df = pd.DataFrame([[k, resultados[k]] for k in resultados], columns=["Exame","Valor"])
161
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
162
  df.to_csv(tmp.name, index=False)
163
  return final, tmp.name
164
 
165
  # Gradio UI
166
  with gr.Blocks() as demo:
167
- gr.Markdown("## 🧪 Extrator Avançado com OCR + EAS + TROPONINA (Quant. e Qual.)")
168
  pdf_input = gr.File(file_types=[".pdf"], label="📄 PDF de exames")
169
  btn = gr.Button("🔍 Extrair")
170
- out_txt = gr.Textbox(lines=15, label="📋 RESULTADOS")
171
  dl = gr.File(label="📥 Baixar CSV")
172
- btn.click(extrair_exames_formatado, inputs=[pdf_input], outputs=[out_txt, dl])
173
 
174
  if __name__ == "__main__":
175
  demo.launch()
 
28
  "TROPONINA": (0, 0.5)
29
  }
30
 
 
 
 
 
 
 
31
  def classificar(nome, valor):
 
32
  try:
33
  v = float(valor.replace(">", "").replace("<", "").strip())
34
+ if nome in faixas:
35
+ lo, hi = faixas[nome]
36
  if v < lo: return f"{valor} ↓"
37
  if v > hi: return f"{valor} ↑"
38
  return valor
 
47
 
48
  # Extrai texto nativo + OCR
49
  def extrair_texto_pdf(pdf_input):
50
+ if isinstance(pdf_input, dict): pdf_path = pdf_input.get("name") or pdf_input.get("file_path")
51
+ elif hasattr(pdf_input, "name") and isinstance(pdf_input.name, str): pdf_path = pdf_input.name
52
+ else: pdf_path = str(pdf_input)
 
 
 
53
 
54
  texto_nativo, ocr_imgs = [], []
55
  with fitz.open(pdf_path) as doc:
 
58
  pix = page.get_pixmap(dpi=300)
59
  img = Image.open(io.BytesIO(pix.tobytes("png")))
60
  ocr_imgs.append(melhorar_imagem(img))
61
+ tn = re.sub(r"\s+", " ", "".join(texto_nativo))
62
  tocr = re.sub(r"\s+", " ", " ".join(pytesseract.image_to_string(im) for im in ocr_imgs))
63
  return tn, tocr
64
 
 
100
  "TROPONINA": r"troponina(?! qualitativa).*?resultado[:\s]*([>\d.,]+)",
101
  "TROPONINA QUAL": r"troponina qualitativa.*?resultado[:\s]*(positivo|negativo)",
102
  # EAS completo (Urina)
103
+ "PROTEINA UR": r"prote[ií]na\s*(ausente|[A-Za-z]+)",
104
+ "GLI UR": r"glicose\s*(ausente|[A-Za-z]+)",
105
+ "CETONAS UR": r"corpos cet[oô]nicos.*?(ausente|[A-Za-z]+)",
106
+ "SANGUE UR": r"sangue\s*(ausente|positivo|negativo)",
107
+ "LEUC ESTERASE": r"leuc[óo]cito esterase\s*[:\-]?\s*(ausente|positivo|negativo)",
108
+ "NITRITO UR": r"nitrito\s*(ausente|positivo|negativo)",
109
+ "LEUCO EAS": r"leuc[óo]citos?\s*([\d]+[-\/–][\d]+)",
110
+ "HEMA EAS": r"hem[áa]cias?\s*([\d]+[-\/–][\d]+)",
111
+ "BACTERIAS UR": r"bact[ée]rias?\s*(raras|ausentes|[A-Za-z]+)"
112
  }
113
 
 
114
  ordem = [
115
  "LEUCO","B","SS","EOS","LINF","MONO",
116
  "HB","HT","PLT","AMIL","BT","BD","BI",
117
  "CR","UREIA","FAL","GGT","TGO","TGP","GLI","LIP","MG++",
118
  "PCR","CKMB","CPK","TROPONINA","TROPONINA QUAL",
119
+ "TAP","INR","TTP","DIMERO D",
120
  # EAS
121
+ "PROTEINA UR","GLI UR","CETONAS UR","SANGUE UR","LEUC ESTERASE","NITRITO UR","LEUCO EAS","HEMA EAS","BACTERIAS UR"
122
  ]
123
 
124
  # Montagem do texto formatado
125
+ def extrair_exames_formatado(pdf_file):
126
+ if not pdf_file: return "Nenhum arquivo enviado.", None
 
127
  tn, tocr = extrair_texto_pdf(pdf_file)
128
  texto = (tn + " " + tocr).lower()
129
  resultados = {}
 
130
  for nome, pat in exames.items():
131
  m = re.search(pat, texto, re.IGNORECASE)
132
+ if not m: continue
133
+ raw = m.group(1).strip().upper()
134
+ resultados[nome] = raw if "QUAL" in nome or nome.endswith("UR") else classificar(nome, raw.replace(",", "."))
135
+
136
+ # Linhas EAS e gerais
137
+ eas_fields = [f"{k}: {resultados[k]}" for k in ordem if k in resultados and k.endswith(('UR','EAS'))]
138
+ main_fields = [f"{r}: {resultados[r]}" for r in ordem if r in resultados and not r.endswith(('UR','EAS'))]
139
+ line_eas = f"🟤 EAS → {' / '.join(eas_fields).upper()}" if eas_fields else ""
140
+ line_main = ' / '.join(main_fields).upper()
141
+ final = '\n'.join([l for l in (line_eas, line_main) if l])
142
+
 
 
 
143
  # CSV
144
+ df = pd.DataFrame([[k, exames and resultados.get(k, '')] for k in resultados], columns=["Exame","Valor"])
145
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
146
  df.to_csv(tmp.name, index=False)
147
  return final, tmp.name
148
 
149
  # Gradio UI
150
  with gr.Blocks() as demo:
151
+ gr.Markdown("## 🧪 Extrator Avançado com OCR + EAS + Troponina (Quant. e Qual.)")
152
  pdf_input = gr.File(file_types=[".pdf"], label="📄 PDF de exames")
153
  btn = gr.Button("🔍 Extrair")
154
+ out_txt = gr.Textbox(lines=15, label="📋 Resultados")
155
  dl = gr.File(label="📥 Baixar CSV")
156
+ btn.click(extrair_exames_formatado, inputs=pdf_input, outputs=[out_txt, dl])
157
 
158
  if __name__ == "__main__":
159
  demo.launch()