dawit45 commited on
Commit
056969a
·
verified ·
1 Parent(s): d6aea11

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -157
app.py CHANGED
@@ -1,164 +1,87 @@
1
- import os
2
  import gradio as gr
3
- from datetime import datetime
4
  from db import models
5
- from utils import ai_engine, pdf_export, notifications
6
- from analytics import dashboard
7
 
8
- # === Secrets ===
9
- ADMIN_PASS = os.getenv("ADMIN_PASS", "admin123")
 
10
 
11
- # === Initialize Database ===
12
- models.create_tables()
 
 
13
 
14
- # === Helper Functions ===
15
 
16
- # SOAP Generation
 
 
 
17
  def generate_soap(subjective, objective, assessment, plan):
18
- note = ai_engine.generate_soap(subjective, objective, assessment, plan)
19
- return note
20
-
21
- # SOAP Analysis + Alerts
22
- def analyze_soap(note_text, patient_name="Unknown"):
23
- history = "" # Future: fetch patient history
24
- analysis, alerts = ai_engine.analyze_note(note_text, history)
25
- # Save alerts
26
- for alert_text in alerts:
27
- conn = models.get_conn()
28
- cur = conn.cursor()
29
- cur.execute("INSERT INTO alerts (note_id, user_id, alert_text) VALUES (%s,%s,%s)",
30
- (0, 0, alert_text)) # Note: user_id=0 placeholder
31
- conn.commit()
32
- cur.close()
33
- conn.close()
34
- # Send email alert (optional)
35
- notifications.send_alert_email("clinic@example.com", f"Critical Alert for {patient_name}", alert_text)
36
- return analysis + ("\n\nALERTS:\n" + "\n".join(alerts) if alerts else "")
37
-
38
- # Payment Submission
39
- def submit_payment(name, phone, method, amount, receipt):
40
- if receipt is None:
41
- return "Please upload a receipt."
42
- os.makedirs("uploads", exist_ok=True)
43
- filename = f"uploads/{datetime.now().timestamp()}_{receipt.name}"
44
- receipt.save(filename)
45
- # Insert into DB
46
- conn = models.get_conn()
47
- cur = conn.cursor()
48
- cur.execute("INSERT INTO payments (user_id, amount, method, receipt_file) VALUES (%s,%s,%s,%s)",
49
- (0, amount, method, filename))
50
- conn.commit()
51
- cur.close()
52
- conn.close()
53
- return "Payment submitted. Pending verification."
54
-
55
- # Admin Login
56
- def admin_login(password):
57
- if password == ADMIN_PASS:
58
- return gr.update(visible=True), "Login successful."
59
- return gr.update(visible=False), "Incorrect password."
60
-
61
- # Get pending payments
62
- def get_pending_payments():
63
- conn = models.get_conn()
64
- cur = conn.cursor()
65
- cur.execute("SELECT id, user_id, amount, method, receipt_file FROM payments WHERE verified=false")
66
- rows = cur.fetchall()
67
- cur.close()
68
- conn.close()
69
- return rows
70
-
71
- # Verify payment
72
- def verify_payment(payment_id):
73
- conn = models.get_conn()
74
- cur = conn.cursor()
75
- cur.execute("UPDATE payments SET verified=true WHERE id=%s", (payment_id,))
76
- conn.commit()
77
- cur.close()
78
- conn.close()
79
- return "Payment verified."
80
-
81
- # Generate PDF of Notes
82
- def export_patient_notes(patient_name="Unknown"):
83
- # Fetch notes
84
- conn = models.get_conn()
85
- cur = conn.cursor()
86
- cur.execute("SELECT patient_name, content, ai_analysis, ai_suggestion, ai_differential, created_at FROM notes")
87
- notes = [{"patient_name": row[0],
88
- "content": row[1],
89
- "ai_analysis": row[2],
90
- "ai_suggestion": row[3],
91
- "ai_differential": row[4],
92
- "created_at": row[5]} for row in cur.fetchall()]
93
- cur.close()
94
- conn.close()
95
- filename = f"uploads/{patient_name.replace(' ','_')}_notes.pdf"
96
- pdf_export.generate_pdf(patient_name, notes, filename)
97
- return filename
98
-
99
- # Analytics Dashboard
100
- def show_dashboard():
101
- fig = dashboard.generate_dashboard_figure()
102
- return fig
103
-
104
- # === Gradio UI ===
105
- with gr.Blocks(title="Selam Scribe — State-of-the-Art Healthcare AI") as demo:
106
-
107
- gr.Markdown("# Selam Scribe 🌟 Ethiopian Healthcare AI Platform")
108
- gr.Markdown("Generate SOAP notes, analyze patients, submit payments, export PDFs, view analytics.")
109
-
110
- # --- SOAP Note Generation Tab ---
111
- with gr.Tab("📝 Generate SOAP"):
112
- subjective = gr.Textbox(label="Subjective")
113
- objective = gr.Textbox(label="Objective")
114
- assessment = gr.Textbox(label="Assessment")
115
- plan = gr.Textbox(label="Plan")
116
- soap_output = gr.Textbox(label="Generated SOAP Note")
117
- gr.Button("Generate SOAP").click(generate_soap,
118
- [subjective, objective, assessment, plan],
119
- soap_output)
120
-
121
- # --- SOAP Analysis Tab ---
122
- with gr.Tab("🔍 Analyze SOAP"):
123
- note_input = gr.Textbox(label="SOAP Note", lines=12)
124
- analysis_output = gr.Textbox(label="Analysis + Alerts")
125
- gr.Button("Analyze Note").click(analyze_soap, [note_input], analysis_output)
126
-
127
- # --- Payment Tab ---
128
- with gr.Tab("💵 Payment"):
129
- pay_name = gr.Textbox(label="Full Name")
130
- pay_phone = gr.Textbox(label="Phone Number")
131
- pay_method = gr.Radio(["Telebirr", "Bank Transfer"], label="Payment Method")
132
- pay_amount = gr.Number(label="Amount (ETB)", value=299)
133
- pay_receipt = gr.File(label="Upload Receipt")
134
- pay_status = gr.Textbox(label="Status")
135
- gr.Button("Submit Payment").click(submit_payment,
136
- [pay_name, pay_phone, pay_method, pay_amount, pay_receipt],
137
- pay_status)
138
-
139
- # --- Admin Panel ---
140
- with gr.Tab("🔐 Admin"):
141
- admin_pass_input = gr.Textbox(label="Admin Password", type="password")
142
- admin_msg = gr.Textbox(label="Status")
143
- admin_panel = gr.Column(visible=False)
144
-
145
- gr.Button("Login").click(admin_login, admin_pass_input, [admin_panel, admin_msg])
146
-
147
- with admin_panel:
148
- pending_table = gr.Dataframe(headers=["ID", "User", "Amount", "Method", "Receipt"])
149
- refresh_btn = gr.Button("Refresh Pending Payments")
150
- refresh_btn.click(get_pending_payments, None, pending_table)
151
-
152
- verify_id = gr.Number(label="Payment ID to Approve")
153
- gr.Button("Verify Payment").click(verify_payment, verify_id, admin_msg)
154
-
155
- # PDF Export
156
- patient_name_pdf = gr.Textbox(label="Patient Name for PDF")
157
- pdf_file_output = gr.File(label="Download PDF")
158
- gr.Button("Export PDF").click(export_patient_notes, patient_name_pdf, pdf_file_output)
159
-
160
- # Analytics Dashboard
161
- analytics_plot = gr.Plot()
162
- gr.Button("Show Analytics Dashboard").click(show_dashboard, None, analytics_plot)
163
-
164
- demo.launch()
 
 
1
  import gradio as gr
 
2
  from db import models
3
+ from utils.ai_engine import generate_text
 
4
 
5
+ # ---------------------------------------------------
6
+ # 🛠️ Initialize Database (SQLite)
7
+ # ---------------------------------------------------
8
 
9
+ try:
10
+ models.create_tables()
11
+ except Exception as e:
12
+ print("DB init warning:", e)
13
 
 
14
 
15
+ # ---------------------------------------------------
16
+ # 🧠 AI Functions
17
+ # ---------------------------------------------------
18
+
19
  def generate_soap(subjective, objective, assessment, plan):
20
+ prompt = f"""
21
+ Generate a clinically accurate SOAP note.
22
+
23
+ Subjective:
24
+ {subjective}
25
+
26
+ Objective:
27
+ {objective}
28
+
29
+ Assessment:
30
+ {assessment}
31
+
32
+ Plan:
33
+ {plan}
34
+ """
35
+ return generate_text(prompt)
36
+
37
+
38
+ def analyze_soap(note_text):
39
+ prompt = f"""
40
+ Analyze this SOAP note and provide:
41
+
42
+ Clinical Quality Score (0–100)
43
+ Missing critical elements
44
+ Red flags
45
+ Suggested improvements
46
+ • Differential diagnoses
47
+
48
+ SOAP Note:
49
+ {note_text}
50
+ """
51
+ return generate_text(prompt)
52
+
53
+
54
+ # ---------------------------------------------------
55
+ # 🎨 Gradio UI
56
+ # ---------------------------------------------------
57
+
58
+ with gr.Blocks(title="Selam Scribe 🩺 AI Medical Assistant") as app:
59
+
60
+ gr.Markdown("## 🩺 Selam Scribe — AI Clinical Assistant")
61
+
62
+ with gr.Tab("SOAP Generator"):
63
+ subj = gr.Textbox(label="Subjective", lines=3)
64
+ obj = gr.Textbox(label="Objective", lines=3)
65
+ assess = gr.Textbox(label="Assessment", lines=3)
66
+ plan = gr.Textbox(label="Plan", lines=3)
67
+
68
+ soap_out = gr.Textbox(label="Generated SOAP Note", lines=12)
69
+
70
+ gen_btn = gr.Button("Generate SOAP")
71
+ gen_btn.click(generate_soap, [subj, obj, assess, plan], soap_out)
72
+
73
+ with gr.Tab("SOAP Analysis"):
74
+ note_in = gr.Textbox(label="SOAP Note", lines=10)
75
+ analysis_out = gr.Textbox(label="AI Analysis", lines=12)
76
+
77
+ analyze_btn = gr.Button("Analyze SOAP")
78
+ analyze_btn.click(analyze_soap, note_in, analysis_out)
79
+
80
+ gr.Markdown("⚡ Powered by Groq (primary) with OpenAI fallback")
81
+
82
+ # ---------------------------------------------------
83
+ # 🚀 Launch App
84
+ # ---------------------------------------------------
85
+
86
+ if __name__ == "__main__":
87
+ app.launch(server_name="0.0.0.0", server_port=7860)