GABRIELSZK commited on
Commit
150311e
·
verified ·
1 Parent(s): de95c16

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -11
app.py CHANGED
@@ -2,7 +2,6 @@ import re
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
@@ -43,16 +42,14 @@ def classificar(nome, valor):
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,10 +68,64 @@ def classificar(nome, valor):
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):
@@ -99,14 +150,13 @@ def extrair_exames_formatado(pdf_file):
99
  line_main = ' / '.join(main_fields)
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.)")
112
  pdf_input = gr.File(file_types=[".pdf"], label="📄 PDF de exames")
 
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
 
42
  except:
43
  return valor
44
 
 
45
  # Ajustes para melhorar OCR
46
+ def melhorar_imagem(img: Image.Image) -> Image.Image:
47
  img = img.convert("L")
48
  img = ImageEnhance.Contrast(img).enhance(2)
49
  return img.filter(ImageFilter.SHARPEN)
50
 
 
51
  # Extrai texto nativo + OCR
52
+ def extrair_texto_pdf(pdf_input):
53
  if isinstance(pdf_input, dict):
54
  pdf_path = pdf_input.get("name") or pdf_input.get("file_path")
55
  elif hasattr(pdf_input, "name") and isinstance(pdf_input.name, str):
 
68
  tocr = re.sub(r"\s+", " ", " ".join(pytesseract.image_to_string(im) for im in ocr_imgs))
69
  return tn, tocr
70
 
 
71
  # Padrões de extração incluindo EAS completo
72
+ exames = {
73
+ # Hemograma
74
+ "LEUCO": r"leuc[óo]citos.*?([\d.,]+)\s*/u?l",
75
+ "B": r"bas[óo]filos.*?([\d.,]+)\s?%",
76
+ "SS": r"segmentados.*?([\d.,]+)\s?%",
77
+ "EOS": r"eosin[óo]filos.*?([\d.,]+)\s?%",
78
+ "LINF": r"linf[oó]citos.*?([\d.,]+)\s?%",
79
+ "MONO": r"mon[óo]citos.*?([\d.,]+)\s?%",
80
+ "HB": r"hemoglobina.*?([\d.,]+)\s?g/dl",
81
+ "HT": r"hemat[óo]crito.*?([\d.,]+)\s?%",
82
+ "PLT": r"plaquetas.*?([\d.,]+).*?/u?l",
83
+ # Bioquímica
84
+ "AMIL": r"amilase.*?resultado[:\s]*([\d.,]+)\s?u/l",
85
+ "BT": r"bilirrubina total.*?([\d.,]+)\s?mg/dl",
86
+ "BD": r"bilirrubina direta.*?([\d.,]+)\s?mg/dl",
87
+ "BI": r"bilirrubina indireta.*?([\d.,]+)\s?mg/dl",
88
+ "CR": r"creatinina.*?resultado[:\s]*([\d.,]+)\s?mg/dl",
89
+ "UREIA":r"ureia.*?resultado[:\s]*([\d.,]+)\s?mg/dl",
90
+ "FAL": r"fosfatase alcalina.*?resultado[:\s]*([\d.,]+)\s?u/l",
91
+ "GGT": r"ggt.*?resultado[:\s]*([\d.,]+)\s?u/l",
92
+ "TGO": r"tgo.*?resultado[:\s]*([\d.,]+)\s?u/l",
93
+ "TGP": r"tgp.*?resultado[:\s]*([\d.,]+)\s?u/l",
94
+ "GLI": r"glicose(?! qualitativa).*?resultado[:\s]*([\d.,]+)\s?mg/dl",
95
+ "LIP": r"lipase.*?resultado[:\s]*([\d.,]+)\s?u/l",
96
+ "MG++": r"magn[eé]sio.*?resultado[:\s]*([\d.,]+)\s?mg/dl",
97
+ # Coagulação
98
+ "TAP": r"tempo de protrombina.*?resultado[:\s]*([\d.,]+)",
99
+ "INR": r"inr.*?([\d.,]+)",
100
+ "TTP": r"ttpa.*?resultado[:\s]*([\d.,]+)",
101
+ "DIMERO D": r"d[ií]mero d.*?resultado[:\s]*([\d.,]+)",
102
+ # Inflamatório e Cardíacos
103
+ "PCR": r"pcr.*?resultado[:\s]*([\d.,]+)",
104
+ "CKMB": r"ck[- ]?mb.*?resultado[:\s]*([\d.,]+)",
105
+ "CPK": r"cpk.*?resultado[:\s]*([\d.,]+)",
106
+ "TROPONINA": r"troponina(?! qualitativa).*?resultado[:\s]*([>\d.,]+)",
107
+ "TROPONINA QUAL": r"troponina qualitativa.*?resultado[:\s]*(positivo|negativo)",
108
+ # EAS completo (Urina)
109
+ "PROTEINA UR": r"prote[ií]na\s*(ausente|positivo|negativo)",
110
+ "GLI UR": r"glicose\s*(ausente|positivo|negativo)",
111
+ "CETONAS UR": r"corpos cet[oô]nicos.*?(ausente|positivo|negativo)",
112
+ "SANGUE UR": r"sangue\s*(ausente|positivo|negativo)",
113
+ "LEUC ESTERASE": r"leuc[óo]citos? esterase\s*[:\-]?\s*(ausente|positivo|negativo)",
114
+ "NITRITO UR": r"nitrito\s*(ausente|positivo|negativo)",
115
+ "LEUCO EAS": r"leuc[óo]citos?\s*([\d]+[-\/–][\d]+)",
116
+ "HEMA EAS": r"hem[áa]cias?\s*([\d]+[-\/–][\d]+)",
117
+ "BACTERIAS UR": r"bact[ée]rias?\s*(raras|ausentes|positivas|negativas)"
118
+ }
119
+
120
+ ordem = [
121
+ "LEUCO","B","SS","EOS","LINF","MONO",
122
+ "HB","HT","PLT","AMIL","BT","BD","BI",
123
+ "CR","UREIA","FAL","GGT","TGO","TGP","GLI","LIP","MG++",
124
+ "PCR","CKMB","CPK","TROPONINA","TROPONINA QUAL",
125
+ "TAP","INR","TTP","DIMERO D",
126
+ # EAS
127
+ "PROTEINA UR","GLI UR","CETONAS UR","SANGUE UR","LEUC ESTERASE","NITRITO UR","LEUCO EAS","HEMA EAS","BACTERIAS UR"
128
+ ]
129
 
130
 
131
  def extrair_exames_formatado(pdf_file):
 
150
  line_main = ' / '.join(main_fields)
151
  final = '\n'.join([l for l in (line_eas, line_main) if l])
152
 
153
+ # Gera CSV
154
  df = pd.DataFrame([[k, resultados[k]] for k in resultados], columns=["Exame", "Valor"])
155
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".csv")
156
  df.to_csv(tmp.name, index=False)
157
  return final, tmp.name
158
 
159
+ # UI Gradio
 
160
  with gr.Blocks() as demo:
161
  gr.Markdown("## 🧪 Extrator Avançado com OCR + EAS + Troponina (Quant. e Qual.)")
162
  pdf_input = gr.File(file_types=[".pdf"], label="📄 PDF de exames")