ashhal commited on
Commit
0c0dd0e
Β·
verified Β·
1 Parent(s): 7a0cfef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -72
app.py CHANGED
@@ -1,83 +1,43 @@
1
- import fitz # PyMuPDF
2
- import re
3
  import gradio as gr
4
- import pandas as pd
5
- import matplotlib.pyplot as plt
6
- import io
7
-
8
- # Normal reference ranges
9
- normal_ranges = {
10
- "Hemoglobin": (13.5, 17.5), # g/dL
11
- "WBC": (4000, 11000), # /Β΅L
12
- "Platelets": (150000, 450000), # /Β΅L
13
- "RBC": (4.7, 6.1), # million/Β΅L
14
- "Creatinine": (0.6, 1.3), # mg/dL
15
- "Glucose": (70, 99), # mg/dL (fasting)
16
- }
17
-
18
- def extract_text(file):
19
- try:
20
- doc = fitz.open(stream=file.read(), filetype="pdf")
21
- text = ""
22
- for page in doc:
23
- text += page.get_text()
24
- return text
25
- except Exception as e:
26
- return f"❌ Error: {str(e)}"
27
-
28
- def analyze_report(file):
29
- text = extract_text(file)
30
- if "❌ Error" in text:
31
- return text, None
32
-
33
- results = {}
34
- for test, (low, high) in normal_ranges.items():
35
- pattern = rf"{test}[^0-9\-]*([\d\.]+)"
36
- match = re.search(pattern, text, re.IGNORECASE)
37
- if match:
38
- value = float(match.group(1))
39
- status = "Normal" if low <= value <= high else "Abnormal"
40
- results[test] = {"value": value, "low": low, "high": high, "status": status}
41
-
42
- if not results:
43
- return "No known lab values found in report.", None
44
 
45
- # Create dataframe
46
- df = pd.DataFrame([
47
- {
48
- "Test": test,
49
- "Value": data["value"],
50
- "Normal Range": f'{data["low"]} - {data["high"]}',
51
- "Status": data["status"]
52
- }
53
- for test, data in results.items()
54
- ])
55
 
56
- # Plot chart
57
- fig, ax = plt.subplots(figsize=(6, 4))
58
- colors = ["green" if row["Status"] == "Normal" else "red" for _, row in df.iterrows()]
59
- ax.bar(df["Test"], df["Value"], color=colors)
60
- ax.set_title("Medical Report Values")
61
- ax.set_ylabel("Measured Value")
62
- ax.tick_params(axis='x', rotation=45)
63
 
64
- buf = io.BytesIO()
65
- plt.tight_layout()
66
- plt.savefig(buf, format="png")
67
- buf.seek(0)
68
 
69
- return df, buf
 
 
 
 
 
 
 
 
 
 
70
 
 
71
  demo = gr.Interface(
72
- fn=analyze_report,
73
- inputs=gr.File(label="Upload Medical PDF Report"),
74
  outputs=[
75
- gr.Dataframe(label="Extracted Values"),
76
- gr.Image(type="pil", label="Visualization")
77
  ],
78
- title="🩺 Medical Report Analyzer",
79
- description="Upload a medical lab report (PDF). Extracted lab values will be compared with normal reference ranges. Abnormal values are flagged and visualized in red."
80
  )
81
 
82
- if __name__ == "__main__":
83
- demo.launch()
 
 
 
1
  import gradio as gr
2
+ import fitz # PyMuPDF
3
+ from transformers import pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ # Load summarization model
6
+ summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
 
 
 
 
 
 
 
 
7
 
8
+ def extract_text_from_pdf(pdf_file):
9
+ doc = fitz.open(stream=pdf_file.read(), filetype="pdf")
10
+ text = ""
11
+ for page in doc:
12
+ text += page.get_text()
13
+ return text
 
14
 
15
+ def simplify_summary(summary):
16
+ # Convert technical language to a more friendly explanation
17
+ return "🩺 Here's what the report says in simple words:\n\n" + summary.replace("\n", " ")
 
18
 
19
+ def process_report(pdf_file):
20
+ try:
21
+ text = extract_text_from_pdf(pdf_file)
22
+ if len(text.strip()) == 0:
23
+ return "❌ Couldn't extract text from the PDF.", ""
24
+
25
+ summary = summarizer(text, max_length=300, min_length=60, do_sample=False)[0]["summary_text"]
26
+ explanation = simplify_summary(summary)
27
+ return summary, explanation
28
+ except Exception as e:
29
+ return f"❌ Error: {str(e)}", ""
30
 
31
+ # Gradio Interface
32
  demo = gr.Interface(
33
+ fn=process_report,
34
+ inputs=gr.File(label="Upload your Medical Report PDF"),
35
  outputs=[
36
+ gr.Textbox(label="Summarized Report", lines=10),
37
+ gr.Textbox(label="Explanation in Simple Terms", lines=10)
38
  ],
39
+ title="πŸ“‹ Medical Report Analyzer",
40
+ description="Upload a medical report and get a simplified summary using GPT-powered summarization.",
41
  )
42
 
43
+ demo.launch()