kseth9852 commited on
Commit
f8b54f3
·
verified ·
1 Parent(s): 23863d5
Files changed (1) hide show
  1. app.py +92 -54
app.py CHANGED
@@ -1,7 +1,11 @@
1
  import streamlit as st
2
  import fitz # PyMuPDF
3
  from transformers import pipeline
4
- from datetime import datetime
 
 
 
 
5
 
6
  # Streamlit page setup
7
  st.set_page_config(page_title="Health Report Analyzer", page_icon="🩺")
@@ -18,64 +22,98 @@ def extract_text(file):
18
  text += page.get_text()
19
  return text
20
 
21
- # Load models from HuggingFace
22
  @st.cache_resource
23
- def load_models():
24
- summarizer = pipeline("summarization", model="philschmid/bart-large-cnn-samsum")
25
- explainer = pipeline("text2text-generation", model="google/flan-t5-base")
26
- return summarizer, explainer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  # Main logic
29
  if uploaded_file:
30
  text_data = extract_text(uploaded_file)
31
- st.success("PDF Text Extracted Successfully!")
32
- st.text_area("Extracted Text", text_data, height=300)
33
-
34
- summarizer, explainer = load_models()
35
-
36
- if st.button("Summarize & Explain"):
37
- with st.spinner("Generating Summary & Explanation..."):
38
- chunks = [text_data[i:i+1000] for i in range(0, len(text_data), 1000)]
39
-
40
- summary = ""
41
- for chunk in chunks:
42
- result = summarizer(chunk, max_length=300, min_length=80, do_sample=False)
43
- summary += result[0]['summary_text'] + " "
44
-
45
- explanation = explainer(f"Explain in simple words: {summary}")[0]['generated_text']
46
-
47
- st.subheader("Summary")
48
- st.write(summary)
49
-
50
- st.subheader("Explanation")
51
- st.write(explanation)
52
-
53
- # Store in session
54
- st.session_state['summary'] = summary
55
- st.session_state['explanation'] = explanation
56
-
57
- # AI Chatbot
58
- st.subheader("💬 AI Chatbot: Ask Anything About Your Report or Medical Terms")
59
-
60
- if 'summary' in st.session_state and 'explanation' in st.session_state:
61
- user_question = st.text_input("Ask a question (e.g. 'meaning of CT scan', 'explain cholecystectomy'):")
62
-
63
- if st.button("Get AI Answer") and user_question:
64
- with st.spinner("Thinking..."):
65
- context = st.session_state['summary'] + "\n" + st.session_state['explanation']
66
- prompt = (
67
- f"You are a helpful medical assistant. "
68
- f"If the report context below doesn't help, use your general medical knowledge.\n\n"
69
- f"Context:\n{context}\n\n"
70
- f"Question: What is the meaning of '{user_question}'?\n"
71
- f"Explain it simply as if talking to a non-medical person."
72
- )
73
- response = explainer(prompt)[0]['generated_text']
74
-
75
- st.success("AI's Response:")
76
- st.write(response)
77
- else:
78
- st.info("Please generate the summary and explanation first to enable the chatbot.")
 
 
 
 
 
 
 
 
79
 
80
  else:
81
  st.info("Upload a PDF Health Report to begin.")
 
1
  import streamlit as st
2
  import fitz # PyMuPDF
3
  from transformers import pipeline
4
+ from gtts import gTTS
5
+ import base64
6
+ import os
7
+ from fpdf import FPDF
8
+ import urllib.parse
9
 
10
  # Streamlit page setup
11
  st.set_page_config(page_title="Health Report Analyzer", page_icon="🩺")
 
22
  text += page.get_text()
23
  return text
24
 
25
+ # Load Hugging Face model for medical explanation
26
  @st.cache_resource
27
+ def load_explainer():
28
+ return pipeline("text2text-generation", model="google/flan-t5-base")
29
+
30
+ # Text-to-Speech helper
31
+ def text_to_speech_base64(text):
32
+ tts = gTTS(text)
33
+ tts.save("response.mp3")
34
+ with open("response.mp3", "rb") as audio_file:
35
+ audio_bytes = audio_file.read()
36
+ b64 = base64.b64encode(audio_bytes).decode()
37
+ audio_html = f"""
38
+ <audio controls autoplay>
39
+ <source src="data:audio/mp3;base64,{b64}" type="audio/mp3">
40
+ Your browser does not support the audio element.
41
+ </audio>
42
+ """
43
+ return audio_html
44
+
45
+ # PDF Export helper
46
+ def generate_pdf(name, explanation_text):
47
+ pdf = FPDF()
48
+ pdf.add_page()
49
+ pdf.set_font("Arial", "B", 16)
50
+ pdf.cell(200, 10, "Medical Explanation", ln=True, align="C")
51
+ pdf.ln(10)
52
+ pdf.set_font("Arial", size=12)
53
+ pdf.multi_cell(0, 10, explanation_text)
54
+ filename = f"{name.replace(' ', '_')}_Explanation.pdf"
55
+ pdf.output(filename)
56
+ return filename
57
 
58
  # Main logic
59
  if uploaded_file:
60
  text_data = extract_text(uploaded_file)
61
+ st.success("Health Report Uploaded Successfully!")
62
+
63
+ st.markdown("### 📄 Health Report Content")
64
+ st.write(text_data)
65
+
66
+ explainer = load_explainer()
67
+ st.session_state['report_text'] = text_data
68
+
69
+ st.subheader("💬 Ask About Any Medical Term or Part of the Report")
70
+
71
+ user_question = st.text_input("Enter a medical term or question (e.g. 'CT scan', 'Explain creatinine'):")
72
+
73
+ if st.button("Get AI Explanation") and user_question:
74
+ with st.spinner("Thinking..."):
75
+
76
+ prompt = (
77
+ f"You are a helpful medical assistant. "
78
+ f"Please explain the following medical term or phrase in very simple words, "
79
+ f"as if you're talking to someone with no medical background.\n\n"
80
+ f"Health Report Content:\n{st.session_state['report_text']}\n\n"
81
+ f"Term or Question: {user_question}\n\n"
82
+ f"Give a clear, beginner-friendly explanation."
83
+ )
84
+
85
+ response = explainer(prompt)[0]['generated_text']
86
+
87
+ st.success("Explanation:")
88
+ st.write(response)
89
+
90
+ st.markdown("🔊 **Hear the Explanation**")
91
+ audio_html = text_to_speech_base64(response)
92
+ st.markdown(audio_html, unsafe_allow_html=True)
93
+
94
+ if os.path.exists("response.mp3"):
95
+ os.remove("response.mp3")
96
+
97
+ st.markdown("---")
98
+ st.subheader("📤 Export or Share This Explanation")
99
+
100
+ user_name = st.text_input("Enter your name to personalize export", value="Patient")
101
+
102
+ # PDF Export
103
+ if st.button("📄 Download as PDF"):
104
+ pdf_file = generate_pdf(user_name, response)
105
+ with open(pdf_file, "rb") as f:
106
+ st.download_button("Download PDF", f, file_name=pdf_file, mime="application/pdf")
107
+ os.remove(pdf_file)
108
+
109
+ # WhatsApp Share
110
+ whatsapp_msg = urllib.parse.quote(f"Hey! I just got this medical explanation:\n\n{response}")
111
+ whatsapp_url = f"https://wa.me/?text={whatsapp_msg}"
112
+ st.markdown(f"[💬 Share via WhatsApp]({whatsapp_url})", unsafe_allow_html=True)
113
+
114
+ # Email Copy
115
+ st.markdown("📧 Copy this text for email:")
116
+ st.code(f"Subject: Medical Report Explanation\n\nHello,\n\nI wanted to share this:\n\n{response}", language="text")
117
 
118
  else:
119
  st.info("Upload a PDF Health Report to begin.")