IFMedTechdemo commited on
Commit
8cc83a6
·
verified ·
1 Parent(s): 654a775

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -163
app.py CHANGED
@@ -1,210 +1,136 @@
1
  import gradio as gr
2
  import requests
3
- import json
4
- from docx import Document
5
- from io import BytesIO
6
  import base64
7
- from urllib.parse import quote
 
8
 
9
- # Pollinations AI Configuration
 
 
10
  POLLINATIONS_API_URL = "https://text.pollinations.ai/openai"
11
- MODEL = "openai" # Changed from "deepseek-r1" to a supported model
12
 
13
- def call_pollinations_ai(system_prompt, user_message):
14
- """Call Pollinations AI API using OpenAI-compatible POST endpoint"""
15
- headers = {
16
- "Content-Type": "application/json"
17
- }
18
-
19
  payload = {
20
- "model": MODEL,
21
  "messages": [
22
  {"role": "system", "content": system_prompt},
23
- {"role": "user", "content": user_message}
24
  ],
25
  "temperature": 0.1,
26
- # "max_tokens": 8000 # Remove if not supported by Pollinations
27
  }
28
-
29
  try:
30
- response = requests.post(POLLINATIONS_API_URL, json=payload, headers=headers, timeout=60)
31
- response.raise_for_status()
32
- result = response.json()
33
- return result["choices"][0]["message"]["content"]
34
- except Exception as e:
35
- return f"Error calling API: {str(e)}"
36
 
 
 
 
37
  def generate_diagnosis(symptoms, medical_history, age, gender, allergies, medications, family_history, lifestyle):
38
- """Generate medical diagnosis"""
39
-
40
- system_prompt = """You are an expert medical diagnostician with comprehensive knowledge of diseases, symptoms, and conditions.
41
- Provide evidence-based preliminary diagnoses using patient information. Be thorough and analytical."""
42
-
43
- user_message = f"""Analyze the patient's case and provide a preliminary diagnosis:
44
- PATIENT DEMOGRAPHICS:
45
- - Age: {age}
46
- - Gender: {gender}
47
- CURRENT SYMPTOMS:
48
- {symptoms}
49
- MEDICAL HISTORY:
50
- {medical_history}
51
- ALLERGIES:
52
- {allergies if allergies else 'None reported'}
53
- CURRENT MEDICATIONS:
54
- {medications if medications else 'None reported'}
55
- FAMILY HISTORY:
56
- {family_history if family_history else 'None reported'}
57
- LIFESTYLE FACTORS:
58
- {lifestyle if lifestyle else 'Not provided'}
59
- Please provide:
60
  1. Preliminary diagnosis with possible conditions
61
- 2. List most likely conditions in order of probability
62
- 3. Severity assessment for each condition
63
- 4. Clinical reasoning for your assessment"""
64
-
65
- return call_pollinations_ai(system_prompt, user_message)
66
 
67
  def generate_treatment_plan(symptoms, medical_history, age, gender, allergies, medications, family_history, diagnosis):
68
- """Generate treatment recommendations"""
69
-
70
- system_prompt = """You are a specialist in creating personalized treatment plans.
71
- Consider patient history, comorbidities, and current medical best practices. Focus on safe and effective recommendations."""
72
-
73
- user_message = f"""Based on the following diagnosis and patient profile, create a comprehensive treatment plan:
74
- PATIENT DEMOGRAPHICS:
75
- - Age: {age}
76
- - Gender: {gender}
77
- PRELIMINARY DIAGNOSIS:
78
- {diagnosis}
79
- MEDICAL HISTORY:
80
- {medical_history}
81
- ALLERGIES:
82
- {allergies if allergies else 'None reported'}
83
- CURRENT MEDICATIONS:
84
- {medications if medications else 'None reported'}
85
- FAMILY HISTORY:
86
- {family_history if family_history else 'None reported'}
87
- Please provide:
88
- 1. Pharmacological treatment (specific medications and dosages)
89
- 2. Lifestyle modifications
90
- 3. Dietary recommendations
91
- 4. Follow-up care schedule
92
- 5. Warning signs to watch for
93
- 6. Precautions based on medical history
94
- 7. Rationale for each recommendation"""
95
-
96
- return call_pollinations_ai(system_prompt, user_message)
97
 
98
  def generate_docx_report(diagnosis, treatment_plan, patient_data):
99
- """Generate DOCX report"""
100
  doc = Document()
101
- doc.add_heading('Healthcare Diagnosis and Treatment Recommendations', 0)
102
-
103
- doc.add_heading('Patient Information', level=1)
104
  doc.add_paragraph(f"Age: {patient_data['age']}")
105
  doc.add_paragraph(f"Gender: {patient_data['gender']}")
106
-
107
- doc.add_heading('Preliminary Diagnosis', level=1)
108
  doc.add_paragraph(diagnosis)
109
-
110
- doc.add_heading('Treatment Plan', level=1)
111
  doc.add_paragraph(treatment_plan)
112
-
113
- doc.add_heading('Disclaimer', level=1)
114
- doc.add_paragraph("This is an AI-assisted preliminary analysis and NOT a substitute for professional medical consultation. Please consult with a qualified healthcare provider.")
115
-
116
  bio = BytesIO()
117
  doc.save(bio)
118
  bio.seek(0)
119
  return bio
120
 
121
  def process_medical_analysis(symptoms, medical_history, age, gender, allergies, medications, family_history, lifestyle):
122
- """Main processing function"""
123
-
124
  if not symptoms or not medical_history:
125
- return "Error: Please provide both symptoms and medical history", "", ""
126
-
127
- # Generate diagnosis
128
- diagnosis = generate_diagnosis(symptoms, medical_history, age, gender, allergies, medications, family_history, lifestyle)
129
-
130
- # Generate treatment plan
131
- treatment_plan = generate_treatment_plan(symptoms, medical_history, age, gender, allergies, medications, family_history, diagnosis)
132
-
133
- # Generate DOCX report
134
- patient_data = {
135
- "age": age,
136
- "gender": gender,
137
- "symptoms": symptoms,
138
- "medical_history": medical_history
139
- }
140
- docx_file = generate_docx_report(diagnosis, treatment_plan, patient_data)
141
- b64 = base64.b64encode(docx_file.read()).decode()
142
- download_link = f'<a href="data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,{b64}" download="medical_analysis_report.docx">📥 Download Report</a>'
143
-
144
- return diagnosis, treatment_plan, download_link
145
 
146
- # Gradio Interface
 
 
147
  with gr.Blocks(title="Medical AI Assistant", theme=gr.themes.Soft()) as demo:
148
  gr.Markdown("# 🏥 Medical AI Assistant")
149
- gr.Markdown("AI-powered system for diagnosis and treatment recommendations powered by Pollinations AI")
150
-
151
  with gr.Row():
152
  with gr.Column():
153
- gr.Markdown("### Patient Demographics")
154
  age = gr.Slider(0, 120, value=25, step=1, label="Age")
155
  gender = gr.Radio(["Male", "Female", "Other"], value="Male", label="Gender")
156
- height = gr.Number(value=170, label="Height (cm)")
157
- weight = gr.Number(value=70, label="Weight (kg)")
158
-
159
  with gr.Column():
160
- gr.Markdown("### Current Symptoms & History")
161
- symptoms = gr.Textbox(
162
- label="Describe Symptoms",
163
- placeholder="e.g., persistent fever for 3 days, dry cough, fatigue",
164
- lines=5
165
- )
166
- medical_history = gr.Textbox(
167
- label="Medical History",
168
- placeholder="e.g., Type 2 diabetes diagnosed in 2019, hypertension",
169
- lines=5
170
- )
171
-
172
  with gr.Row():
173
  with gr.Column():
174
- gr.Markdown("### Additional Information")
175
- allergies = gr.Textbox(label="Known Allergies", placeholder="e.g., penicillin, peanuts")
176
- current_medications = gr.Textbox(label="Current Medications", placeholder="e.g., metformin 500mg twice daily")
177
-
178
  with gr.Column():
179
- family_history = gr.Textbox(label="Family History", placeholder="e.g., heart disease, diabetes")
180
- lifestyle = gr.Textbox(label="Lifestyle Factors", placeholder="e.g., smoker, exercises 3 times a week")
181
-
182
  analyze_btn = gr.Button("🔍 Generate Analysis", variant="primary", size="lg")
183
-
184
  with gr.Row():
185
- with gr.Column():
186
- gr.Markdown("### Preliminary Diagnosis")
187
- diagnosis_output = gr.Textbox(label="Diagnosis", lines=10, interactive=False)
188
-
189
- with gr.Column():
190
- gr.Markdown("### Treatment Plan")
191
- treatment_output = gr.Textbox(label="Treatment Plan", lines=10, interactive=False)
192
-
193
- with gr.Row():
194
- download_output = gr.HTML(label="Download")
195
-
196
- gr.Markdown("""
197
- ### ⚡ Disclaimer
198
- **Important:** This is a preliminary AI-assisted analysis and NOT a substitute for professional medical consultation.
199
- Always consult with a qualified healthcare provider for proper diagnosis and treatment.
200
- """)
201
-
202
- # Connect button to function
203
- analyze_btn.click(
204
- fn=process_medical_analysis,
205
- inputs=[symptoms, medical_history, age, gender, allergies, current_medications, family_history, lifestyle],
206
- outputs=[diagnosis_output, treatment_output, download_output]
207
- )
208
 
209
  if __name__ == "__main__":
210
- demo.launch(share=True, server_name="0.0.0.0", server_port=7860)
 
1
  import gradio as gr
2
  import requests
 
 
 
3
  import base64
4
+ from io import BytesIO
5
+ from docx import Document
6
 
7
+ # ------------------------------------------------------------------
8
+ # 1. Minimal Pollinations caller (your requested style)
9
+ # ------------------------------------------------------------------
10
  POLLINATIONS_API_URL = "https://text.pollinations.ai/openai"
 
11
 
12
+ def call_pollinations_ai(system_prompt: str, user_message: str) -> str:
 
 
 
 
 
13
  payload = {
14
+ "model": "openai",
15
  "messages": [
16
  {"role": "system", "content": system_prompt},
17
+ {"role": "user", "content": user_message}
18
  ],
19
  "temperature": 0.1,
20
+ "max_tokens": 1000 # tune as needed
21
  }
22
+
23
  try:
24
+ resp = requests.post(POLLINATIONS_API_URL, json=payload)
25
+ return resp.json()['choices'][0]['message']['content']
26
+ except Exception as exc:
27
+ return f"API error: {exc}"
 
 
28
 
29
+ # ------------------------------------------------------------------
30
+ # 2. Everything below is identical to your original file
31
+ # ------------------------------------------------------------------
32
  def generate_diagnosis(symptoms, medical_history, age, gender, allergies, medications, family_history, lifestyle):
33
+ system = ("You are an expert medical diagnostician with comprehensive knowledge of diseases, "
34
+ "symptoms, and conditions. Provide evidence-based preliminary diagnoses.")
35
+ user = f"""Analyse the patient:
36
+ Age: {age} | Gender: {gender}
37
+ Symptoms: {symptoms}
38
+ History: {medical_history}
39
+ Allergies: {allergies or 'None'}
40
+ Medications: {medications or 'None'}
41
+ Family history: {family_history or 'None'}
42
+ Lifestyle: {lifestyle or 'Not provided'}
43
+
44
+ Provide:
 
 
 
 
 
 
 
 
 
 
45
  1. Preliminary diagnosis with possible conditions
46
+ 2. Most-likely list ranked by probability
47
+ 3. Severity assessment
48
+ 4. Clinical reasoning"""
49
+ return call_pollinations_ai(system, user)
 
50
 
51
  def generate_treatment_plan(symptoms, medical_history, age, gender, allergies, medications, family_history, diagnosis):
52
+ system = ("You are a specialist in personalised treatment plans. "
53
+ "Consider history, comorbidities, and best practices.")
54
+ user = f"""Create a treatment plan for:
55
+ Age: {age} | Gender: {gender}
56
+ Diagnosis: {diagnosis}
57
+ History: {medical_history}
58
+ Allergies: {allergies or 'None'}
59
+ Medications: {medications or 'None'}
60
+ Family history: {family_history or 'None'}
61
+
62
+ Provide:
63
+ 1. Pharmacological treatment
64
+ 2. Lifestyle / diet
65
+ 3. Follow-up schedule
66
+ 4. Warning signs
67
+ 5. Precautions
68
+ 6. Rationale"""
69
+ return call_pollinations_ai(system, user)
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  def generate_docx_report(diagnosis, treatment_plan, patient_data):
 
72
  doc = Document()
73
+ doc.add_heading("Healthcare Diagnosis and Treatment Recommendations", 0)
74
+ doc.add_heading("Patient Information", 1)
 
75
  doc.add_paragraph(f"Age: {patient_data['age']}")
76
  doc.add_paragraph(f"Gender: {patient_data['gender']}")
77
+ doc.add_heading("Preliminary Diagnosis", 1)
 
78
  doc.add_paragraph(diagnosis)
79
+ doc.add_heading("Treatment Plan", 1)
 
80
  doc.add_paragraph(treatment_plan)
81
+ doc.add_heading("Disclaimer", 1)
82
+ doc.add_paragraph("AI-assisted preliminary analysis – not a substitute for professional medical consultation.")
83
+
 
84
  bio = BytesIO()
85
  doc.save(bio)
86
  bio.seek(0)
87
  return bio
88
 
89
  def process_medical_analysis(symptoms, medical_history, age, gender, allergies, medications, family_history, lifestyle):
 
 
90
  if not symptoms or not medical_history:
91
+ return "Error: symptoms and history required", "", ""
92
+ diagnosis = generate_diagnosis(symptoms, medical_history, age, gender,
93
+ allergies, medications, family_history, lifestyle)
94
+ treatment = generate_treatment_plan(symptoms, medical_history, age, gender,
95
+ allergies, medications, family_history, diagnosis)
96
+ docx_bio = generate_docx_report(diagnosis, treatment, {"age": age, "gender": gender})
97
+ b64 = base64.b64encode(docx_bio.read()).decode()
98
+ link = f'<a href="data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,{b64}" download="medical_analysis_report.docx">📥 Download Report</a>'
99
+ return diagnosis, treatment, link
 
 
 
 
 
 
 
 
 
 
 
100
 
101
+ # ------------------------------------------------------------------
102
+ # 3. Gradio UI (unchanged)
103
+ # ------------------------------------------------------------------
104
  with gr.Blocks(title="Medical AI Assistant", theme=gr.themes.Soft()) as demo:
105
  gr.Markdown("# 🏥 Medical AI Assistant")
106
+ gr.Markdown("AI-powered diagnosis & treatment suggestions via Pollinations AI")
 
107
  with gr.Row():
108
  with gr.Column():
 
109
  age = gr.Slider(0, 120, value=25, step=1, label="Age")
110
  gender = gr.Radio(["Male", "Female", "Other"], value="Male", label="Gender")
 
 
 
111
  with gr.Column():
112
+ symptoms = gr.Textbox(label="Describe Symptoms", lines=5,
113
+ placeholder="e.g. fever 3 days, dry cough")
114
+ medical_history = gr.Textbox(label="Medical History", lines=5,
115
+ placeholder="e.g. diabetes 2019, hypertension")
 
 
 
 
 
 
 
 
116
  with gr.Row():
117
  with gr.Column():
118
+ allergies = gr.Textbox(label="Known Allergies", placeholder="e.g. penicillin")
119
+ medications = gr.Textbox(label="Current Medications", placeholder="e.g. metformin 500 mg bid")
 
 
120
  with gr.Column():
121
+ family_history = gr.Textbox(label="Family History", placeholder="e.g. heart disease")
122
+ lifestyle = gr.Textbox(label="Lifestyle Factors", placeholder="e.g. smoker, exercise 3×/wk")
 
123
  analyze_btn = gr.Button("🔍 Generate Analysis", variant="primary", size="lg")
 
124
  with gr.Row():
125
+ diagnosis_out = gr.Textbox(label="Diagnosis", lines=10, interactive=False)
126
+ treatment_out = gr.Textbox(label="Treatment Plan", lines=10, interactive=False)
127
+ download_out = gr.HTML()
128
+ gr.Markdown("⚠️ **Disclaimer**: AI-assisted only – always consult a healthcare professional.")
129
+
130
+ analyze_btn.click(process_medical_analysis,
131
+ inputs=[symptoms, medical_history, age, gender,
132
+ allergies, medications, family_history, lifestyle],
133
+ outputs=[diagnosis_out, treatment_out, download_out])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
  if __name__ == "__main__":
136
+ demo.launch(share=True, server_name="0.0.0.0", server_port=7860)