Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -28,11 +28,18 @@ faixas = {
|
|
28 |
"TROPONINA": (0, 0.5)
|
29 |
}
|
30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
def classificar(nome, valor):
|
|
|
32 |
try:
|
33 |
v = float(valor.replace(">", "").replace("<", "").strip())
|
34 |
-
|
35 |
-
|
36 |
if v < lo: return f"{valor} ↓"
|
37 |
if v > hi: return f"{valor} ↑"
|
38 |
return valor
|
@@ -47,9 +54,12 @@ def melhorar_imagem(img: Image.Image) -> Image.Image:
|
|
47 |
|
48 |
# Extrai texto nativo + OCR
|
49 |
def extrair_texto_pdf(pdf_input):
|
50 |
-
if isinstance(pdf_input, dict):
|
51 |
-
|
52 |
-
|
|
|
|
|
|
|
53 |
|
54 |
texto_nativo, ocr_imgs = [], []
|
55 |
with fitz.open(pdf_path) as doc:
|
@@ -58,7 +68,7 @@ def extrair_texto_pdf(pdf_input):
|
|
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 |
|
@@ -99,61 +109,21 @@ exames = {
|
|
99 |
"CPK": r"cpk.*?resultado[:\s]*([\d.,]+)",
|
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|
|
104 |
-
"GLI UR": r"glicose\s*(ausente|
|
105 |
-
"CETONAS UR": r"corpos cet[oô]nicos.*?(ausente|
|
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*(
|
110 |
-
"HEMA EAS": r"hem[áa]cias?\s*(
|
111 |
-
"BACTERIAS UR": r"bact[ée]rias?\s*(raras|
|
112 |
}
|
113 |
|
|
|
114 |
ordem = [
|
115 |
"LEUCO","B","SS","EOS","LINF","MONO",
|
116 |
"HB","HT","PLT","AMIL","BT","BD","BI",
|
117 |
-
"CR","UREIA","
|
118 |
-
|
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()
|
|
|
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 |
|
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 |
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 |
|
|
|
109 |
"CPK": r"cpk.*?resultado[:\s]*([\d.,]+)",
|
110 |
"TROPONINA": r"troponina(?! qualitativa).*?resultado[:\s]*([>\d.,]+)",
|
111 |
"TROPONINA QUAL": r"troponina qualitativa.*?resultado[:\s]*(positivo|negativo)",
|
112 |
+
# EAS completo (Urina) apenas quando válido
|
113 |
+
"PROTEINA UR": r"prote[ií]na\s*(ausente|positivo|negativo)",
|
114 |
+
"GLI UR": r"glicose\s*(ausente|positivo|negativo)",
|
115 |
+
"CETONAS UR": r"corpos cet[oô]nicos.*?(ausente|positivo|negativo)",
|
116 |
+
"SANGUE UR": r"sangue\s*[:\-]?\s*(ausente|positivo|negativo)",
|
117 |
"LEUC ESTERASE": r"leuc[óo]cito esterase\s*[:\-]?\s*(ausente|positivo|negativo)",
|
118 |
"NITRITO UR": r"nitrito\s*(ausente|positivo|negativo)",
|
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*(ausente|raras|frequentes|positivas)"
|
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","
|
129 |
+
]}]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|