GABRIELSZK commited on
Commit
de95c16
·
verified ·
1 Parent(s): 8171eaa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -66
app.py CHANGED
@@ -2,6 +2,7 @@ import re
2
  import fitz
3
  import gradio as gr
4
  import pandas as pd
 
5
  import tempfile
6
  import pytesseract
7
  from PIL import Image, ImageEnhance, ImageFilter
@@ -28,6 +29,7 @@ faixas = {
28
  "TROPONINA": (0, 0.5)
29
  }
30
 
 
31
  def classificar(nome, valor):
32
  try:
33
  v = float(valor.replace(">", "").replace("<", "").strip())
@@ -41,14 +43,16 @@ def classificar(nome, valor):
41
  except:
42
  return valor
43
 
 
44
  # Ajustes para melhorar OCR
45
- def melhorar_imagem(img: Image.Image) -> Image.Image:
46
  img = img.convert("L")
47
  img = ImageEnhance.Contrast(img).enhance(2)
48
  return img.filter(ImageFilter.SHARPEN)
49
 
 
50
  # Extrai texto nativo + OCR
51
- def extrair_texto_pdf(pdf_input):
52
  if isinstance(pdf_input, dict):
53
  pdf_path = pdf_input.get("name") or pdf_input.get("file_path")
54
  elif hasattr(pdf_input, "name") and isinstance(pdf_input.name, str):
@@ -67,66 +71,12 @@ def extrair_texto_pdf(pdf_input):
67
  tocr = re.sub(r"\s+", " ", " ".join(pytesseract.image_to_string(im) for im in ocr_imgs))
68
  return tn, tocr
69
 
 
70
  # Padrões de extração incluindo EAS completo
71
- exames = {
72
- # Hemograma
73
- "LEUCO": r"leuc[óo]citos.*?([\d.,]+)\s*/u?l",
74
- "B": r"bas[óo]filos.*?([\d.,]+)\s?%",
75
- "SS": r"segmentados.*?([\d.,]+)\s?%",
76
- "EOS": r"eosin[óo]filos.*?([\d.,]+)\s?%",
77
- "LINF": r"linf[oó]citos.*?([\d.,]+)\s?%",
78
- "MONO": r"mon[óo]citos.*?([\d.,]+)\s?%",
79
- "HB": r"hemoglobina.*?([\d.,]+)\s?g/dl",
80
- "HT": r"hemat[óo]crito.*?([\d.,]+)\s?%",
81
- "PLT": r"plaquetas.*?([\d.,]+).*?/u?l",
82
- # Bioquímica
83
- "AMIL": r"amilase.*?resultado[:\s]*([\d.,]+)\s?u/l",
84
- "BT": r"bilirrubina total.*?([\d.,]+)\s?mg/dl",
85
- "BD": r"bilirrubina direta.*?([\d.,]+)\s?mg/dl",
86
- "BI": r"bilirrubina indireta.*?([\d.,]+)\s?mg/dl",
87
- "CR": r"creatinina.*?resultado[:\s]*([\d.,]+)\s?mg/dl",
88
- "UREIA":r"ureia.*?resultado[:\s]*([\d.,]+)\s?mg/dl",
89
- "FAL": r"fosfatase alcalina.*?resultado[:\s]*([\d.,]+)\s?u/l",
90
- "GGT": r"ggt.*?resultado[:\s]*([\d.,]+)\s?u/l",
91
- "TGO": r"tgo.*?resultado[:\s]*([\d.,]+)\s?u/l",
92
- "TGP": r"tgp.*?resultado[:\s]*([\d.,]+)\s?u/l",
93
- "GLI": r"glicose(?! qualitativa).*?resultado[:\s]*([\d.,]+)\s?mg/dl",
94
- "LIP": r"lipase.*?resultado[:\s]*([\d.,]+)\s?u/l",
95
- "MG++": r"magn[eé]sio.*?resultado[:\s]*([\d.,]+)\s?mg/dl",
96
- # Coagulação
97
- "TAP": r"tempo de protrombina.*?resultado[:\s]*([\d.,]+)",
98
- "INR": r"inr.*?([\d.,]+)",
99
- "TTP": r"ttpa.*?resultado[:\s]*([\d.,]+)",
100
- "DIMERO D": r"d[ií]mero d.*?resultado[:\s]*([\d.,]+)",
101
- # Inflamatório e Cardíacos
102
- "PCR": r"pcr.*?resultado[:\s]*([\d.,]+)",
103
- "CKMB": r"ck[- ]?mb.*?resultado[:\s]*([\d.,]+)",
104
- "CPK": r"cpk.*?resultado[:\s]*([\d.,]+)",
105
- "TROPONINA": r"troponina(?! qualitativa).*?resultado[:\s]*([>\d.,]+)",
106
- "TROPONINA QUAL": r"troponina qualitativa.*?resultado[:\s]*(positivo|negativo)",
107
- # EAS completo (Urina)
108
- "PROTEINA UR": r"prote[ií]na\s*(ausente|positivo|negativo)",
109
- "GLI UR": r"glicose\s*(ausente|positivo|negativo)",
110
- "CETONAS UR": r"corpos cet[oô]nicos.*?(ausente|positivo|negativo)",
111
- "SANGUE UR": r"sangue\s*(ausente|positivo|negativo)",
112
- "LEUC ESTERASE": r"leuc[óo]citos? esterase\s*[:\-]?\s*(ausente|positivo|negativo)",
113
- "NITRITO UR": r"nitrito\s*(ausente|positivo|negativo)",
114
- "LEUCO EAS": r"leuc[óo]citos?\s*([\d]+[-\/–][\d]+)",
115
- "HEMA EAS": r"hem[áa]cias?\s*([\d]+[-\/–][\d]+)",
116
- "BACTERIAS UR": r"bact[ée]rias?\s*(raras|ausentes|positivas|negativas)"
117
- }
118
 
119
- ordem = [
120
- "LEUCO","B","SS","EOS","LINF","MONO",
121
- "HB","HT","PLT","AMIL","BT","BD","BI",
122
- "CR","UREIA","FAL","GGT","TGO","TGP","GLI","LIP","MG++",
123
- "PCR","CKMB","CPK","TROPONINA","TROPONINA QUAL",
124
- "TAP","INR","TTP","DIMERO D",
125
- # EAS
126
- "PROTEINA UR","GLI UR","CETONAS UR","SANGUE UR","LEUC ESTERASE","NITRITO UR","LEUCO EAS","HEMA EAS","BACTERIAS UR"
127
- ]
128
-
129
- # Montagem do texto formatado
130
  def extrair_exames_formatado(pdf_file):
131
  if not pdf_file:
132
  return "Nenhum arquivo enviado.", None
@@ -138,13 +88,11 @@ def extrair_exames_formatado(pdf_file):
138
  if not m:
139
  continue
140
  raw = m.group(1).strip().upper()
141
- # se for valor qualitativo ou EAS, mantém texto
142
  if "QUAL" in nome or nome.endswith("UR") or nome.endswith("EAS"):
143
  resultados[nome] = raw
144
  else:
145
  resultados[nome] = classificar(nome, raw.replace(",", "."))
146
 
147
- # Linhas EAS e principais
148
  eas_fields = [f"{k}: {resultados[k]}" for k in ordem if k in resultados and (k.endswith("UR") or k.endswith("EAS"))]
149
  main_fields = [f"{r}: {resultados[r]}" for r in ordem if r in resultados and not (r.endswith("UR") or r.endswith("EAS"))]
150
  line_eas = f"🟤 EAS → {' / '.join(eas_fields)}" if eas_fields else ""
@@ -152,11 +100,12 @@ def extrair_exames_formatado(pdf_file):
152
  final = '\n'.join([l for l in (line_eas, line_main) if l])
153
 
154
  # CSV
155
- df = pd.DataFrame([[k, resultados[k]] for k in resultados], columns=["Exame","Valor"])
156
- tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
157
- df.to_csv(tmp.name, index=False)
158
  return final, tmp.name
159
 
 
160
  # Gradio UI
161
  with gr.Blocks() as demo:
162
  gr.Markdown("## 🧪 Extrator Avançado com OCR + EAS + Troponina (Quant. e Qual.)")
@@ -167,4 +116,4 @@ with gr.Blocks() as demo:
167
  btn.click(extrair_exames_formatado, inputs=pdf_input, outputs=[out_txt, dl])
168
 
169
  if __name__ == "__main__":
170
- demo.launch()
 
2
  import fitz
3
  import gradio as gr
4
  import pandas as pd
5
+ tmpfile = None
6
  import tempfile
7
  import pytesseract
8
  from PIL import Image, ImageEnhance, ImageFilter
 
29
  "TROPONINA": (0, 0.5)
30
  }
31
 
32
+
33
  def classificar(nome, valor):
34
  try:
35
  v = float(valor.replace(">", "").replace("<", "").strip())
 
43
  except:
44
  return valor
45
 
46
+
47
  # Ajustes para melhorar OCR
48
+ def melhorar_imagem(img: Image.Image) -> Image.Image:
49
  img = img.convert("L")
50
  img = ImageEnhance.Contrast(img).enhance(2)
51
  return img.filter(ImageFilter.SHARPEN)
52
 
53
+
54
  # Extrai texto nativo + OCR
55
+ def extrair_texto_pdf(pdf_input):
56
  if isinstance(pdf_input, dict):
57
  pdf_path = pdf_input.get("name") or pdf_input.get("file_path")
58
  elif hasattr(pdf_input, "name") and isinstance(pdf_input.name, str):
 
71
  tocr = re.sub(r"\s+", " ", " ".join(pytesseract.image_to_string(im) for im in ocr_imgs))
72
  return tn, tocr
73
 
74
+
75
  # Padrões de extração incluindo EAS completo
76
+ exames = { ... } # mantêm definição existente
77
+ ordem = [ ... ] # mantêm definição existente
78
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
 
 
 
 
 
 
 
 
 
 
 
 
80
  def extrair_exames_formatado(pdf_file):
81
  if not pdf_file:
82
  return "Nenhum arquivo enviado.", None
 
88
  if not m:
89
  continue
90
  raw = m.group(1).strip().upper()
 
91
  if "QUAL" in nome or nome.endswith("UR") or nome.endswith("EAS"):
92
  resultados[nome] = raw
93
  else:
94
  resultados[nome] = classificar(nome, raw.replace(",", "."))
95
 
 
96
  eas_fields = [f"{k}: {resultados[k]}" for k in ordem if k in resultados and (k.endswith("UR") or k.endswith("EAS"))]
97
  main_fields = [f"{r}: {resultados[r]}" for r in ordem if r in resultados and not (r.endswith("UR") or r.endswith("EAS"))]
98
  line_eas = f"🟤 EAS → {' / '.join(eas_fields)}" if eas_fields else ""
 
100
  final = '\n'.join([l for l in (line_eas, line_main) if l])
101
 
102
  # CSV
103
+ df = pd.DataFrame([[k, resultados[k]] for k in resultados], columns=["Exame", "Valor"])
104
+ tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
105
+ df.to_csv(tmp.name, index=False)
106
  return final, tmp.name
107
 
108
+
109
  # Gradio UI
110
  with gr.Blocks() as demo:
111
  gr.Markdown("## 🧪 Extrator Avançado com OCR + EAS + Troponina (Quant. e Qual.)")
 
116
  btn.click(extrair_exames_formatado, inputs=pdf_input, outputs=[out_txt, dl])
117
 
118
  if __name__ == "__main__":
119
+ demo.launch()