Spaces:
Sleeping
Sleeping
Commit
·
b55f8aa
1
Parent(s):
998eef9
Initial commit
Browse files
app.py
CHANGED
|
@@ -1,92 +1,103 @@
|
|
| 1 |
-
from openai import OpenAI
|
| 2 |
import gradio as gr
|
| 3 |
-
import logging
|
| 4 |
import sqlite3
|
| 5 |
-
import
|
|
|
|
| 6 |
from datetime import datetime
|
|
|
|
| 7 |
import hashlib
|
| 8 |
-
import
|
|
|
|
| 9 |
import base64
|
| 10 |
from PIL import Image
|
| 11 |
-
import
|
| 12 |
-
|
| 13 |
|
| 14 |
logging.basicConfig(level=logging.INFO)
|
| 15 |
-
logger
|
| 16 |
|
| 17 |
-
print("
|
| 18 |
-
KEY
|
|
|
|
| 19 |
if not KEY:
|
| 20 |
-
|
| 21 |
-
|
| 22 |
|
| 23 |
-
|
|
|
|
| 24 |
base_url="https://openrouter.ai/api/v1",
|
| 25 |
-
api_key=KEY
|
|
|
|
| 26 |
)
|
| 27 |
|
| 28 |
def init():
|
| 29 |
try:
|
| 30 |
-
c
|
| 31 |
-
cursor
|
| 32 |
cursor.execute('''CREATE TABLE IF NOT EXISTS history(
|
| 33 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
| 40 |
c.commit()
|
| 41 |
c.close()
|
| 42 |
except Exception as e:
|
| 43 |
-
logger.error(f"error in database:
|
|
|
|
| 44 |
|
| 45 |
-
def
|
| 46 |
try:
|
| 47 |
-
reader
|
| 48 |
-
result
|
| 49 |
-
text
|
| 50 |
for ocr in result:
|
| 51 |
text += ocr[1] + " "
|
| 52 |
-
return text.strip()
|
| 53 |
except Exception as e:
|
| 54 |
-
|
|
|
|
| 55 |
return ""
|
| 56 |
|
| 57 |
-
def
|
| 58 |
try:
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
return
|
| 63 |
except Exception as e:
|
| 64 |
-
|
|
|
|
| 65 |
return "default_session"
|
| 66 |
-
|
| 67 |
-
def save_to_database(session_id, input_text, input_image, response, query_type):
|
| 68 |
-
try:
|
| 69 |
-
c = sqlite3.connect("nursa.db")
|
| 70 |
-
cursor = c.cursor()
|
| 71 |
-
image_data = None
|
| 72 |
-
if input_image is not None:
|
| 73 |
-
buffered = io.BytesIO()
|
| 74 |
-
input_image.save(buffered, format="PNG")
|
| 75 |
-
image_data = base64.b64encode(buffered.getvalue()).decode()
|
| 76 |
-
|
| 77 |
-
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
cursor.execute('''INSERT INTO history(session_id, input_text, input_image, response, timestamp, query_type)
|
| 80 |
-
|
| 81 |
-
|
|
|
|
| 82 |
c.commit()
|
| 83 |
c.close()
|
|
|
|
| 84 |
except Exception as e:
|
| 85 |
-
logger.error(f"
|
|
|
|
| 86 |
|
| 87 |
def get_user_history(session_id):
|
| 88 |
try:
|
| 89 |
-
conn = sqlite3.connect("
|
| 90 |
cursor = conn.cursor()
|
| 91 |
cursor.execute('''SELECT timestamp, query_type, input_text, response
|
| 92 |
FROM history WHERE session_id = ?
|
|
@@ -97,21 +108,21 @@ def get_user_history(session_id):
|
|
| 97 |
if not results:
|
| 98 |
return "📝 هنوز تاریخچهای ندارید"
|
| 99 |
|
| 100 |
-
history_text = "📊 تاریخچه شما\n\n"
|
| 101 |
for i, (timestamp, query_type, input_text, response) in enumerate(results, 1):
|
| 102 |
-
emoji = "💊" if query_type == "drug_interaction" else "🔬"
|
| 103 |
-
history_text += f"{emoji} مورد {i} - {timestamp}\n"
|
| 104 |
-
history_text += f"**ورودی:** {input_text[:100]}...\n"
|
| 105 |
history_text += f"**پاسخ:** {response[:200]}...\n\n---\n\n"
|
| 106 |
|
| 107 |
return history_text
|
| 108 |
except Exception as e:
|
| 109 |
logger.error(f"Error getting history: {e}")
|
| 110 |
-
return "❌ خطا در دریافت تاریخچه"
|
| 111 |
|
| 112 |
def clear_user_history(session_id):
|
| 113 |
try:
|
| 114 |
-
conn = sqlite3.connect("
|
| 115 |
cursor = conn.cursor()
|
| 116 |
cursor.execute("DELETE FROM history WHERE session_id = ?", (session_id,))
|
| 117 |
conn.commit()
|
|
@@ -120,9 +131,10 @@ def clear_user_history(session_id):
|
|
| 120 |
except Exception as e:
|
| 121 |
logger.error(f"Error clearing history: {e}")
|
| 122 |
return "❌ خطا در پاک کردن تاریخچه"
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
| 126 |
"drug_interaction": f"""شما یک متخصص داروسازی و فارماکولوژی هستید. لطفاً تداخل بین این دو دارو را به صورت کامل تحلیل کنید:
|
| 127 |
|
| 128 |
دارو اول: {data['drug1']}
|
|
@@ -138,8 +150,7 @@ def medical_ai_assistant(request_type, data, session_id):
|
|
| 138 |
7. نیاز به تغییر دوز یا زمانبندی
|
| 139 |
|
| 140 |
پاسخ را به فارسی و با جزئیات کامل ارائه دهید.""",
|
| 141 |
-
|
| 142 |
-
"lab_analysis": f"""شما یک متخصص آزمایشگاه و پاتولوژیست هستید. این متن از یک نتیجه آزمایش استخراج شده:
|
| 143 |
|
| 144 |
{data['extracted_text']}
|
| 145 |
|
|
@@ -171,40 +182,30 @@ def medical_ai_assistant(request_type, data, session_id):
|
|
| 171 |
⚠️ تأکید شود که این تشخیص اولیه است و حتماً باید با پزشک مشورت شود.
|
| 172 |
|
| 173 |
پاسخ را به زبان فارسی، مهربان و کامل بدهید."""
|
|
|
|
| 174 |
}
|
| 175 |
-
|
| 176 |
try:
|
| 177 |
-
prompt
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
extra_headers={
|
| 181 |
-
"HTTP-Referer": "https://medical-ai.com",
|
| 182 |
-
"X-Title": "Medical AI Assistant",
|
| 183 |
-
},
|
| 184 |
-
extra_body={},
|
| 185 |
-
model="openai/gpt-oss-20b:free",
|
| 186 |
messages=[
|
| 187 |
-
{
|
| 188 |
-
|
| 189 |
-
"content": prompt
|
| 190 |
-
}
|
| 191 |
]
|
| 192 |
)
|
| 193 |
-
|
| 194 |
-
result = completion.choices[0].message.content
|
| 195 |
-
|
| 196 |
input_text = ""
|
| 197 |
input_image = None
|
| 198 |
|
| 199 |
-
if
|
| 200 |
input_text = f"تداخل دارویی: {data['drug1']} + {data['drug2']}"
|
| 201 |
-
elif
|
| 202 |
input_text = "تحلیل تصویر آزمایش"
|
| 203 |
input_image = data.get('image')
|
| 204 |
-
elif
|
| 205 |
input_text = f"علائم: {data['symptoms']}"
|
| 206 |
|
| 207 |
-
|
| 208 |
|
| 209 |
return result
|
| 210 |
|
|
@@ -213,181 +214,109 @@ def medical_ai_assistant(request_type, data, session_id):
|
|
| 213 |
logger.error(error_msg)
|
| 214 |
return error_msg
|
| 215 |
|
| 216 |
-
|
| 217 |
-
def check_drug_interaction(drug1, drug2, session_id):
|
| 218 |
if not drug1 or not drug2:
|
| 219 |
-
return "⚠️ لطفاً هر دو دارو را وارد کنید"
|
| 220 |
|
| 221 |
-
data = {
|
| 222 |
-
|
|
|
|
| 223 |
|
| 224 |
-
def
|
| 225 |
if image is None:
|
| 226 |
return "⚠️ لطفاً تصویر آزمایش را آپلود کنید"
|
| 227 |
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
if os.path.exists(temp_path):
|
| 236 |
-
os.remove(temp_path)
|
| 237 |
-
|
| 238 |
-
if not extracted_text:
|
| 239 |
-
return "❌ متنی از تصویر استخراج نشد. لطفاً تصویر واضحتری آپلود کنید"
|
| 240 |
-
|
| 241 |
-
data = {'extracted_text': extracted_text, 'image': pil_image}
|
| 242 |
-
return medical_ai_assistant("lab_analysis", data, session_id)
|
| 243 |
-
|
| 244 |
-
except Exception as e:
|
| 245 |
-
logger.error(f"Error in analyze_lab_image: {e}")
|
| 246 |
-
return f"❌ خطا در پردازش تصویر: {str(e)}"
|
| 247 |
|
| 248 |
-
def
|
| 249 |
if not symptoms:
|
| 250 |
return "⚠️ لطفاً علائم خود را وارد کنید"
|
| 251 |
|
| 252 |
-
data = {
|
| 253 |
-
|
|
|
|
| 254 |
|
| 255 |
-
|
| 256 |
-
init()
|
| 257 |
-
|
| 258 |
-
# Gradio Interface
|
| 259 |
-
with gr.Blocks(theme=gr.themes.Soft(), css="""
|
| 260 |
-
.gradio-container {
|
| 261 |
-
font-family: 'Vazir', 'B Nazanin', sans-serif;
|
| 262 |
-
direction: rtl;
|
| 263 |
-
}
|
| 264 |
-
.tab-nav button {
|
| 265 |
-
font-size: 16px;
|
| 266 |
-
padding: 10px 20px;
|
| 267 |
-
}
|
| 268 |
-
#session-display {
|
| 269 |
-
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 270 |
-
color: white;
|
| 271 |
-
padding: 10px;
|
| 272 |
-
border-radius: 10px;
|
| 273 |
-
text-align: center;
|
| 274 |
-
margin-bottom: 20px;
|
| 275 |
-
}
|
| 276 |
-
""") as demo:
|
| 277 |
-
|
| 278 |
-
# Session Management
|
| 279 |
-
session_id = gr.State(value=generate_session)
|
| 280 |
-
|
| 281 |
-
gr.Markdown("# 🏥 دستیار هوش مصنوعی پزشکی - Nursa")
|
| 282 |
-
gr.Markdown("### سیستم هوشمند تحلیل پزشکی و دارویی")
|
| 283 |
-
|
| 284 |
-
# Display Session ID
|
| 285 |
-
with gr.Row():
|
| 286 |
-
session_display = gr.Textbox(
|
| 287 |
-
value=lambda: f"شناسه نشست شما: {generate_session()}",
|
| 288 |
-
label="",
|
| 289 |
-
interactive=False,
|
| 290 |
-
elem_id="session-display"
|
| 291 |
-
)
|
| 292 |
-
new_session_btn = gr.Button("🔄 نشست جدید", scale=0)
|
| 293 |
|
| 294 |
-
with gr.
|
| 295 |
-
|
| 296 |
-
with gr.TabItem("💊 تداخل دارویی"):
|
| 297 |
-
gr.Markdown("### بررسی تداخل بین داروها")
|
| 298 |
-
with gr.Row():
|
| 299 |
-
drug1_input = gr.Textbox(
|
| 300 |
-
label="دارو اول",
|
| 301 |
-
placeholder="مثال: آسپرین",
|
| 302 |
-
lines=1
|
| 303 |
-
)
|
| 304 |
-
drug2_input = gr.Textbox(
|
| 305 |
-
label="دارو دوم",
|
| 306 |
-
placeholder="مثال: وارفارین",
|
| 307 |
-
lines=1
|
| 308 |
-
)
|
| 309 |
-
|
| 310 |
-
drug_btn = gr.Button("🔍 بررسی تداخل", variant="primary")
|
| 311 |
-
drug_output = gr.Markdown()
|
| 312 |
-
|
| 313 |
-
drug_btn.click(
|
| 314 |
-
fn=check_drug_interaction,
|
| 315 |
-
inputs=[drug1_input, drug2_input, session_id],
|
| 316 |
-
outputs=drug_output
|
| 317 |
-
)
|
| 318 |
|
| 319 |
-
#
|
| 320 |
-
with gr.TabItem("🔬 تحلیل آزمایش"):
|
| 321 |
-
gr.Markdown("### تحلیل تصویر نتیجه آزمایش")
|
| 322 |
-
lab_image = gr.Image(
|
| 323 |
-
label="تصویر آزمایش را آپلود کنید",
|
| 324 |
-
type="numpy"
|
| 325 |
-
)
|
| 326 |
-
lab_btn = gr.Button("📊 تحلیل آزمایش", variant="primary")
|
| 327 |
-
lab_output = gr.Markdown()
|
| 328 |
-
|
| 329 |
-
lab_btn.click(
|
| 330 |
-
fn=analyze_lab_image,
|
| 331 |
-
inputs=[lab_image, session_id],
|
| 332 |
-
outputs=lab_output
|
| 333 |
-
)
|
| 334 |
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
gr.Markdown("### بررسی علائم و تشخیص احتمالی")
|
| 338 |
-
symptoms_input = gr.Textbox(
|
| 339 |
-
label="علائم خود را شرح دهید",
|
| 340 |
-
placeholder="مثال: سردرد، تب، گلودرد از دیروز",
|
| 341 |
-
lines=4
|
| 342 |
-
)
|
| 343 |
-
symptom_btn = gr.Button("🏥 تشخیص اولیه", variant="primary")
|
| 344 |
-
symptom_output = gr.Markdown()
|
| 345 |
-
|
| 346 |
-
symptom_btn.click(
|
| 347 |
-
fn=diagnose_symptoms,
|
| 348 |
-
inputs=[symptoms_input, session_id],
|
| 349 |
-
outputs=symptom_output
|
| 350 |
-
)
|
| 351 |
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 364 |
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
|
| 381 |
-
|
| 382 |
-
---
|
| 383 |
-
⚠️ **توجه مهم:** این سیستم صرفاً جهت راهنمایی اولیه است و جایگزین مشاوره پزشک نمیباشد.
|
| 384 |
-
در صورت مشاهده علائم جدی، حتماً به پزشک مراجعه کنید.
|
| 385 |
-
""")
|
| 386 |
|
| 387 |
-
# Launch the app
|
| 388 |
if __name__ == "__main__":
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
server_port=7860,
|
| 392 |
-
share=True
|
| 393 |
-
)
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
|
|
|
| 2 |
import sqlite3
|
| 3 |
+
import logging
|
| 4 |
+
import secrets
|
| 5 |
from datetime import datetime
|
| 6 |
+
import easyocr
|
| 7 |
import hashlib
|
| 8 |
+
import os
|
| 9 |
+
import io
|
| 10 |
import base64
|
| 11 |
from PIL import Image
|
| 12 |
+
from openai import OpenAI
|
| 13 |
+
|
| 14 |
|
| 15 |
logging.basicConfig(level=logging.INFO)
|
| 16 |
+
logger=logging.getLogger(__name__)
|
| 17 |
|
| 18 |
+
print("api key")
|
| 19 |
+
KEY=os.getenv("KEY")
|
| 20 |
+
logger.error("error in api key")
|
| 21 |
if not KEY:
|
| 22 |
+
print("error in loading api")
|
| 23 |
+
|
| 24 |
|
| 25 |
+
|
| 26 |
+
client=OpenAI(
|
| 27 |
base_url="https://openrouter.ai/api/v1",
|
| 28 |
+
api_key=KEY
|
| 29 |
+
|
| 30 |
)
|
| 31 |
|
| 32 |
def init():
|
| 33 |
try:
|
| 34 |
+
c= sqlite3.connect("N.db")
|
| 35 |
+
cursor=c.cursor()
|
| 36 |
cursor.execute('''CREATE TABLE IF NOT EXISTS history(
|
| 37 |
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 38 |
+
session_id TEXT,
|
| 39 |
+
input_text TEXT,
|
| 40 |
+
input_image TEXT,
|
| 41 |
+
response TEXT,
|
| 42 |
+
timestamp TEXT,
|
| 43 |
+
query_type TEXT )
|
| 44 |
+
|
| 45 |
+
''')
|
| 46 |
c.commit()
|
| 47 |
c.close()
|
| 48 |
except Exception as e:
|
| 49 |
+
logger.error(f"error in database:{e}")
|
| 50 |
+
print("error in sqlite3")
|
| 51 |
|
| 52 |
+
def image_ocr(path):
|
| 53 |
try:
|
| 54 |
+
reader=easyocr.Reader(["fa","en"])
|
| 55 |
+
result=reader.readtext(path)
|
| 56 |
+
text=""
|
| 57 |
for ocr in result:
|
| 58 |
text += ocr[1] + " "
|
| 59 |
+
return text.strip()
|
| 60 |
except Exception as e:
|
| 61 |
+
print("error in easyocr")
|
| 62 |
+
logger.error(f"error in easyocr :{e}")
|
| 63 |
return ""
|
| 64 |
|
| 65 |
+
def session():
|
| 66 |
try:
|
| 67 |
+
x=datetime.utcnow().isoformat()
|
| 68 |
+
n=secrets.token_hex(8)
|
| 69 |
+
s=hashlib.sha256((str(x+n)).encode()).hexdigest()
|
| 70 |
+
return s[:15]
|
| 71 |
except Exception as e:
|
| 72 |
+
print("error session")
|
| 73 |
+
logger.error(f"error session:{e}")
|
| 74 |
return "default_session"
|
| 75 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
def save_database(session_id,text_input,image_input,response,query_type):
|
| 78 |
+
try:
|
| 79 |
+
c=sqlite3.connect("N.db")
|
| 80 |
+
cursor=c.cursor()
|
| 81 |
+
image_data=None
|
| 82 |
+
if image_input is not None:
|
| 83 |
+
buffered=io.BytesIO()
|
| 84 |
+
image_input.save(buffered,format="PNG")
|
| 85 |
+
image_data=base64.b64encode(buffered.getvalue()).decode()
|
| 86 |
+
timestamp=datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
|
| 87 |
cursor.execute('''INSERT INTO history(session_id, input_text, input_image, response, timestamp, query_type)
|
| 88 |
+
VALUES(?, ?, ?, ?, ?, ?)''',
|
| 89 |
+
|
| 90 |
+
(session_id, text_input, image_data, response, timestamp, query_type))
|
| 91 |
c.commit()
|
| 92 |
c.close()
|
| 93 |
+
logger.info("Data saved successfully")
|
| 94 |
except Exception as e:
|
| 95 |
+
logger.error(f"Error saving to database: {e}")
|
| 96 |
+
|
| 97 |
|
| 98 |
def get_user_history(session_id):
|
| 99 |
try:
|
| 100 |
+
conn = sqlite3.connect("N.db")
|
| 101 |
cursor = conn.cursor()
|
| 102 |
cursor.execute('''SELECT timestamp, query_type, input_text, response
|
| 103 |
FROM history WHERE session_id = ?
|
|
|
|
| 108 |
if not results:
|
| 109 |
return "📝 هنوز تاریخچهای ندارید"
|
| 110 |
|
| 111 |
+
history_text = "# 📊 تاریخچه شما\n\n"
|
| 112 |
for i, (timestamp, query_type, input_text, response) in enumerate(results, 1):
|
| 113 |
+
emoji = "💊" if query_type == "drug_interaction" else "🔬"
|
| 114 |
+
history_text += f"## {emoji} مورد {i} - {timestamp}\n\n"
|
| 115 |
+
history_text += f"**ورودی:** {input_text[:100]}...\n\n"
|
| 116 |
history_text += f"**پاسخ:** {response[:200]}...\n\n---\n\n"
|
| 117 |
|
| 118 |
return history_text
|
| 119 |
except Exception as e:
|
| 120 |
logger.error(f"Error getting history: {e}")
|
| 121 |
+
return "❌ خطا در دریافت تاریخچه"
|
| 122 |
|
| 123 |
def clear_user_history(session_id):
|
| 124 |
try:
|
| 125 |
+
conn = sqlite3.connect("N.db")
|
| 126 |
cursor = conn.cursor()
|
| 127 |
cursor.execute("DELETE FROM history WHERE session_id = ?", (session_id,))
|
| 128 |
conn.commit()
|
|
|
|
| 131 |
except Exception as e:
|
| 132 |
logger.error(f"Error clearing history: {e}")
|
| 133 |
return "❌ خطا در پاک کردن تاریخچه"
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def ai(requests,session_id,data):
|
| 137 |
+
prompts={
|
| 138 |
"drug_interaction": f"""شما یک متخصص داروسازی و فارماکولوژی هستید. لطفاً تداخل بین این دو دارو را به صورت کامل تحلیل کنید:
|
| 139 |
|
| 140 |
دارو اول: {data['drug1']}
|
|
|
|
| 150 |
7. نیاز به تغییر دوز یا زمانبندی
|
| 151 |
|
| 152 |
پاسخ را به فارسی و با جزئیات کامل ارائه دهید.""",
|
| 153 |
+
"lab_analysis": f"""شما یک متخصص آزمایشگاه و پاتولوژیست هستید. این متن از یک نتیجه آزمایش استخراج شده:
|
|
|
|
| 154 |
|
| 155 |
{data['extracted_text']}
|
| 156 |
|
|
|
|
| 182 |
⚠️ تأکید شود که این تشخیص اولیه است و حتماً باید با پزشک مشورت شود.
|
| 183 |
|
| 184 |
پاسخ را به زبان فارسی، مهربان و کامل بدهید."""
|
| 185 |
+
|
| 186 |
}
|
|
|
|
| 187 |
try:
|
| 188 |
+
prompt=prompts.get(requests)
|
| 189 |
+
response=client.chat.completions.create(
|
| 190 |
+
model="openai/gpt-oss-20b:free",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
messages=[
|
| 192 |
+
{"role":"system","content":prompt}
|
| 193 |
+
|
|
|
|
|
|
|
| 194 |
]
|
| 195 |
)
|
| 196 |
+
result=response.choices[0].message.content
|
|
|
|
|
|
|
| 197 |
input_text = ""
|
| 198 |
input_image = None
|
| 199 |
|
| 200 |
+
if requests == "drug_interaction":
|
| 201 |
input_text = f"تداخل دارویی: {data['drug1']} + {data['drug2']}"
|
| 202 |
+
elif requests == "lab_analysis":
|
| 203 |
input_text = "تحلیل تصویر آزمایش"
|
| 204 |
input_image = data.get('image')
|
| 205 |
+
elif requests == "symptom_diagnosis":
|
| 206 |
input_text = f"علائم: {data['symptoms']}"
|
| 207 |
|
| 208 |
+
save_database(session_id, input_text, input_image, result, requests)
|
| 209 |
|
| 210 |
return result
|
| 211 |
|
|
|
|
| 214 |
logger.error(error_msg)
|
| 215 |
return error_msg
|
| 216 |
|
| 217 |
+
def drug_interaction_check(drug1, drug2, session_id):
|
|
|
|
| 218 |
if not drug1 or not drug2:
|
| 219 |
+
return "⚠️ لطفاً نام هر دو دارو را وارد کنید"
|
| 220 |
|
| 221 |
+
data = {"drug1": drug1, "drug2": drug2}
|
| 222 |
+
result = ai("drug_interaction", session_id, data)
|
| 223 |
+
return result
|
| 224 |
|
| 225 |
+
def lab_analysis_check(image, session_id):
|
| 226 |
if image is None:
|
| 227 |
return "⚠️ لطفاً تصویر آزمایش را آپلود کنید"
|
| 228 |
|
| 229 |
+
extracted_text = image_ocr(image)
|
| 230 |
+
if not extracted_text:
|
| 231 |
+
return "❌ متاسفانه نتوانستم متن را از تصویر استخراج کنم"
|
| 232 |
+
|
| 233 |
+
data = {"extracted_text": extracted_text, "image": image}
|
| 234 |
+
result = ai("lab_analysis", session_id, data)
|
| 235 |
+
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
|
| 237 |
+
def symptom_diagnosis_check(symptoms, session_id):
|
| 238 |
if not symptoms:
|
| 239 |
return "⚠️ لطفاً علائم خود را وارد کنید"
|
| 240 |
|
| 241 |
+
data = {"symptoms": symptoms}
|
| 242 |
+
result = ai("symptom_diagnosis", session_id, data)
|
| 243 |
+
return result
|
| 244 |
|
| 245 |
+
def create_interface():
|
| 246 |
+
init()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
+
with gr.Blocks(title="Nursa", theme=gr.themes.Soft()) as app:
|
| 249 |
+
session_id = gr.State(session())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
|
| 251 |
+
gr.Markdown("# 🏥 Nursa")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
+
with gr.Row():
|
| 254 |
+
gr.Markdown(f"**شناسه جلسه شما:** `{session().replace('-', '').upper()[:8]}`")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 255 |
|
| 256 |
+
with gr.Tabs():
|
| 257 |
+
with gr.Tab("💊 بررسی تداخل دارویی"):
|
| 258 |
+
with gr.Column():
|
| 259 |
+
drug1_input = gr.Textbox(label="نام دارو اول", placeholder="مثال: آسپرین")
|
| 260 |
+
drug2_input = gr.Textbox(label="نام دارو دوم", placeholder="مثال: وارفارین")
|
| 261 |
+
drug_check_btn = gr.Button("بررسی تداخل", variant="primary")
|
| 262 |
+
drug_output = gr.Markdown()
|
| 263 |
+
|
| 264 |
+
drug_check_btn.click(
|
| 265 |
+
drug_interaction_check,
|
| 266 |
+
inputs=[drug1_input, drug2_input, session_id],
|
| 267 |
+
outputs=[drug_output]
|
| 268 |
+
)
|
| 269 |
|
| 270 |
+
with gr.Tab("🔬 تحلیل آزمایش"):
|
| 271 |
+
with gr.Column():
|
| 272 |
+
lab_image = gr.Image(type="pil", label="تصویر نتیجه آزمایش")
|
| 273 |
+
lab_check_btn = gr.Button("تحلیل آزمایش", variant="primary")
|
| 274 |
+
lab_output = gr.Markdown()
|
| 275 |
+
|
| 276 |
+
lab_check_btn.click(
|
| 277 |
+
lab_analysis_check,
|
| 278 |
+
inputs=[lab_image, session_id],
|
| 279 |
+
outputs=[lab_output]
|
| 280 |
+
)
|
| 281 |
|
| 282 |
+
with gr.Tab("🩺 تشخیص علائم"):
|
| 283 |
+
with gr.Column():
|
| 284 |
+
symptoms_input = gr.Textbox(
|
| 285 |
+
label="علائم شما",
|
| 286 |
+
placeholder="مثال: سردرد، تب، گلودرد",
|
| 287 |
+
lines=3
|
| 288 |
+
)
|
| 289 |
+
symptom_check_btn = gr.Button("تشخیص علائم", variant="primary")
|
| 290 |
+
symptom_output = gr.Markdown()
|
| 291 |
+
|
| 292 |
+
symptom_check_btn.click(
|
| 293 |
+
symptom_diagnosis_check,
|
| 294 |
+
inputs=[symptoms_input, session_id],
|
| 295 |
+
outputs=[symptom_output]
|
| 296 |
+
)
|
| 297 |
+
|
| 298 |
+
with gr.Tab("📋 تاریخچه"):
|
| 299 |
+
with gr.Column():
|
| 300 |
+
history_btn = gr.Button("نمایش تاریخچه")
|
| 301 |
+
clear_btn = gr.Button("پاک کردن تاریخچه", variant="secondary")
|
| 302 |
+
history_output = gr.Markdown()
|
| 303 |
+
|
| 304 |
+
history_btn.click(
|
| 305 |
+
get_user_history,
|
| 306 |
+
inputs=[session_id],
|
| 307 |
+
outputs=[history_output]
|
| 308 |
+
)
|
| 309 |
+
|
| 310 |
+
clear_btn.click(
|
| 311 |
+
clear_user_history,
|
| 312 |
+
inputs=[session_id],
|
| 313 |
+
outputs=[history_output]
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
gr.Markdown("⚠️ **توجه:** این سیستم صرفاً جهت اطلاع اولیه است و جایگزین مشاوره پزشک نیست.")
|
| 317 |
|
| 318 |
+
return app
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
|
|
|
|
| 320 |
if __name__ == "__main__":
|
| 321 |
+
app = create_interface()
|
| 322 |
+
app.launch(server_name="0.0.0.0", server_port=7860, share=True)
|
|
|
|
|
|
|
|
|