Paulwalker4884 commited on
Commit
6d36bb1
·
1 Parent(s): ef6047a

Initial commit

Browse files
Files changed (1) hide show
  1. app.py +349 -204
app.py CHANGED
@@ -1,263 +1,408 @@
1
  from openai import OpenAI
2
- import easyocr
3
  import logging
4
  import sqlite3
5
- import gradio as gr
6
- import os
7
  import hashlib
8
- import datetime
9
  import base64
10
  from PIL import Image
11
- import io
12
-
13
- key = os.getenv("KEYRR")
14
- if not key:
15
- print("Error: API key not found in environment variables")
16
 
 
17
  logging.basicConfig(level=logging.INFO)
18
  logger = logging.getLogger(__name__)
19
 
20
- # Initialize OCR reader
21
- reader = easyocr.Reader(['en', 'fa'])
22
-
23
- def init_database():
24
- """Initialize database with user sessions"""
25
- conn = sqlite3.connect("daro.db")
26
- cursor = conn.cursor()
27
-
28
- cursor.execute('''
29
- CREATE TABLE IF NOT EXISTS user_sessions(
30
- session_id TEXT PRIMARY KEY,
31
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
32
- )
33
- ''')
34
-
35
- cursor.execute('''
36
- CREATE TABLE IF NOT EXISTS chat_history(
37
- id INTEGER PRIMARY KEY AUTOINCREMENT,
38
- session_id TEXT,
39
- input_text TEXT,
40
- input_image TEXT,
41
- response TEXT,
42
- created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
43
- FOREIGN KEY (session_id) REFERENCES user_sessions (session_id)
44
- )
45
- ''')
46
-
47
- conn.commit()
48
- conn.close()
49
-
50
- def generate_session_id():
51
- """Generate unique session ID for each user"""
52
- timestamp = str(datetime.datetime.now().timestamp())
53
- return hashlib.md5(timestamp.encode()).hexdigest()[:12]
54
-
55
- def save_to_database(session_id, input_text, input_image, response):
56
- """Save conversation to database"""
57
- conn = sqlite3.connect("daro.db")
58
- cursor = conn.cursor()
59
-
60
- # Convert image to base64 if exists
61
- image_data = None
62
- if input_image is not None:
63
- buffered = io.BytesIO()
64
- input_image.save(buffered, format="PNG")
65
- image_data = base64.b64encode(buffered.getvalue()).decode()
66
-
67
- cursor.execute('''
68
- INSERT INTO chat_history (session_id, input_text, input_image, response)
69
- VALUES (?, ?, ?, ?)
70
- ''', (session_id, input_text, image_data, response))
71
-
72
- conn.commit()
73
- conn.close()
74
-
75
- def get_user_history(session_id):
76
- """Get chat history for specific user session"""
77
- conn = sqlite3.connect("daro.db")
78
- cursor = conn.cursor()
79
-
80
- cursor.execute('''
81
- SELECT input_text, input_image, response, created_at
82
- FROM chat_history
83
- WHERE session_id = ?
84
- ORDER BY created_at DESC
85
- ''', (session_id,))
86
-
87
- history = cursor.fetchall()
88
- conn.close()
89
- return history
90
 
 
91
  client = OpenAI(
92
  base_url="https://openrouter.ai/api/v1",
93
- api_key=key,
94
  )
95
 
96
- def extract_text_from_image(image):
97
- """Extract text from image using OCR"""
98
  try:
99
- # Convert PIL Image to numpy array
100
- import numpy as np
101
- img_array = np.array(image)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
- # Use EasyOCR to extract text
104
- results = reader.readtext(img_array)
105
- extracted_text = " ".join([result[1] for result in results])
106
 
107
- return extracted_text
 
 
 
 
 
108
  except Exception as e:
109
- logger.error(f"Error in OCR: {str(e)}")
110
- return ""
111
 
112
- def analyze_drug_info(text_input, image_input, session_id):
113
- """Main function to analyze drug information"""
114
  try:
115
- # Combine text input with OCR text if image provided
116
- full_input = text_input or ""
 
 
 
 
 
117
 
118
- if image_input is not None:
119
- ocr_text = extract_text_from_image(image_input)
120
- if ocr_text:
121
- full_input += f"\n\nText extracted from image: {ocr_text}"
122
 
123
- if not full_input.strip():
124
- return "لطفاً متن یا تصویر وارد کنید."
 
 
 
 
125
 
126
- # Create prompt for LLM
127
- prompt = f"""You are a pharmaceutical assistant. Analyze this drug information: {full_input}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
- Please provide:
130
- 1. Drug identification (if mentioned)
131
- 2. Potential drug interactions
132
- 3. Side effects and warnings
133
- 4. Proper usage instructions
134
- 5. Any safety concerns
 
 
135
 
136
- Please respond in Persian (Farsi) and be very accurate."""
137
 
138
  completion = client.chat.completions.create(
139
  extra_headers={
140
- "HTTP-Referer": "Nursa-App",
141
- "X-Title": "Nursa Drug Assistant",
142
  },
143
- model="openai/gpt-3.5-turbo",
 
144
  messages=[
145
- {"role": "system", "content": "You are a professional pharmaceutical assistant. Always prioritize safety and accuracy."},
146
- {"role": "user", "content": prompt}
147
- ],
148
- max_tokens=2048,
149
- top_p=0.8,
150
- temperature=0.4
151
  )
152
-
153
  result = completion.choices[0].message.content
154
 
155
- # Save to database
156
- save_to_database(session_id, full_input, image_input, result)
157
 
158
- return result
159
 
160
  except Exception as e:
161
- logger.error(f"Error in analysis: {str(e)}")
162
- return f"خطا در پردازش: {str(e)}"
 
163
 
164
- def format_history(session_id):
165
- """Format user history for display"""
166
- history = get_user_history(session_id)
167
- if not history:
168
- return "تاریخچه‌ای موجود نیست."
169
 
170
- formatted_history = ""
171
- for i, (input_text, image_data, response, timestamp) in enumerate(history, 1):
172
- formatted_history += f"""
173
- **پرسش {i}** ({timestamp}):
174
- {input_text[:100]}{'...' if len(input_text) > 100 else ''}
 
 
 
 
 
 
 
 
175
 
176
- **پاسخ:**
177
- {response[:200]}{'...' if len(response) > 200 else ''}
178
 
179
- ---
180
- """
181
- return formatted_history
182
 
183
- def create_interface():
184
- """Create Gradio interface"""
185
- init_database()
186
-
187
- # Generate session ID for each user
188
- session_id = generate_session_id()
189
-
190
- with gr.Blocks(title="Nursa - دستیار دارویی هوشمند", theme=gr.themes.Soft()) as app:
191
- gr.Markdown("""
192
- # 💊 Nursa - دستیار دارویی هوشمند
193
- ### تحلیل دارو، بررسی تداخلات و راهنمایی دارویی با هوش مصنوعی
194
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
 
196
- with gr.Row():
197
- with gr.Column(scale=2):
198
- text_input = gr.Textbox(
199
- label="🔍 سوال یا اطلاعات دارو را وارد کنید",
200
- placeholder="مثال: آیا استامینوفن با ایبوپروفن تداخل دارد؟",
201
- lines=3
202
- )
203
-
204
- image_input = gr.Image(
205
- label="📸 تصویر نسخه یا دارو را آپلود کنید",
206
- type="pil"
207
- )
208
-
209
- analyze_btn = gr.Button("🔬 تحلیل کنید", variant="primary", size="lg")
210
-
211
- with gr.Column(scale=2):
212
- output = gr.Textbox(
213
- label="📋 نتیجه تحلیل",
214
- lines=15,
215
- max_lines=20
216
- )
217
 
218
- with gr.Row():
219
- with gr.Column():
220
- history_btn = gr.Button("📚 مشاهده تاریخچه", variant="secondary")
221
- history_output = gr.Textbox(
222
- label="🕐 تاریخچه شما",
223
- lines=10,
224
- visible=False
225
- )
226
 
227
- # Event handlers
228
- def analyze_and_update(text, image):
229
- result = analyze_drug_info(text, image, session_id)
230
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
- def show_history():
233
- history = format_history(session_id)
234
- return gr.Textbox(value=history, visible=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
 
 
 
 
 
236
  analyze_btn.click(
237
- fn=analyze_and_update,
238
- inputs=[text_input, image_input],
239
- outputs=output
240
  )
241
 
242
- history_btn.click(
243
- fn=show_history,
244
- outputs=history_output
 
245
  )
246
 
247
- gr.Markdown("""
248
- ---
249
- ⚠️ **هشدار مهم**: Nursa فقط جهت اطلاع‌رسانی است و جایگزین مشاوره پزشک نیست.
250
- 💡 **درباره Nursa**: دستیار دارویی هوشمند برای تحلیل دقیق داروها و تداخلات
251
- """)
 
 
 
 
 
 
 
 
 
 
 
 
252
 
253
  return app
254
 
255
-
256
  if __name__ == "__main__":
257
- app = create_interface()
258
  app.launch(
259
- share=True,
260
- server_name="0.0.0.0",
261
  server_port=7860,
262
- debug=True
 
263
  )
 
1
  from openai import OpenAI
2
+ import gradio as gr
3
  import logging
4
  import sqlite3
5
+ import easyocr
6
+ from datetime import datetime
7
  import hashlib
8
+ import io
9
  import base64
10
  from PIL import Image
11
+ import os
 
 
 
 
12
 
13
+ # تنظیمات لاگ
14
  logging.basicConfig(level=logging.INFO)
15
  logger = logging.getLogger(__name__)
16
 
17
+ print("Loading API key...")
18
+ KEY = os.getenv("KEY")
19
+ if not KEY:
20
+ logger.error("Error in token")
21
+ print("Error in token - Please set KEY environment variable")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # تنظیمات OpenAI با OpenRouter
24
  client = OpenAI(
25
  base_url="https://openrouter.ai/api/v1",
26
+ api_key=KEY,
27
  )
28
 
29
+ def extract_text_easyocr(image_path):
30
+ """استخراج متن از تصویر با EasyOCR"""
31
  try:
32
+ reader = easyocr.Reader(["en", "fa"])
33
+ result = reader.readtext(image_path)
34
+ text = ""
35
+ for ocr in result:
36
+ text += ocr[1] + " "
37
+ return text.strip()
38
+ except Exception as e:
39
+ logger.error(f"Error in EasyOCR: {e}")
40
+ return ""
41
+
42
+ def init_database():
43
+ """ایجاد دیتابیس"""
44
+ try:
45
+ conn = sqlite3.connect("nurca.db")
46
+ cursor = conn.cursor()
47
+ cursor.execute('''CREATE TABLE IF NOT EXISTS chat_history(
48
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
49
+ session_id TEXT,
50
+ input_text TEXT,
51
+ input_image TEXT,
52
+ response TEXT,
53
+ timestamp TEXT,
54
+ query_type TEXT
55
+ )''')
56
+ conn.commit()
57
+ conn.close()
58
+ logger.info("Database initialized successfully")
59
+ except Exception as e:
60
+ logger.error(f"Error in creating database: {e}")
61
+
62
+ def generate_session():
63
+ """ایجاد session ID"""
64
+ try:
65
+ timestamp = str(datetime.now().timestamp())
66
+ return hashlib.md5(timestamp.encode()).hexdigest()[:12]
67
+ except Exception as e:
68
+ logger.error(f"Error in session ID generation: {e}")
69
+ return "default_session"
70
+
71
+ def save_to_database(session_id, input_text, input_image, response, query_type):
72
+ """ذخیره در دیتابیس"""
73
+ try:
74
+ conn = sqlite3.connect("nurca.db")
75
+ cursor = conn.cursor()
76
+
77
+ image_data = None
78
+ if input_image is not None:
79
+ buffered = io.BytesIO()
80
+ input_image.save(buffered, format="PNG")
81
+ image_data = base64.b64encode(buffered.getvalue()).decode()
82
 
83
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 
 
84
 
85
+ cursor.execute('''INSERT INTO chat_history(session_id, input_text, input_image, response, timestamp, query_type)
86
+ VALUES(?, ?, ?, ?, ?, ?)''',
87
+ (session_id, input_text, image_data, response, timestamp, query_type))
88
+ conn.commit()
89
+ conn.close()
90
+ logger.info("Data saved successfully")
91
  except Exception as e:
92
+ logger.error(f"Error saving to database: {e}")
 
93
 
94
+ def get_user_history(session_id):
95
+ """دریافت تاریخچه کاربر"""
96
  try:
97
+ conn = sqlite3.connect("nurca.db")
98
+ cursor = conn.cursor()
99
+ cursor.execute('''SELECT timestamp, query_type, input_text, response
100
+ FROM chat_history WHERE session_id = ?
101
+ ORDER BY timestamp DESC LIMIT 10''', (session_id,))
102
+ results = cursor.fetchall()
103
+ conn.close()
104
 
105
+ if not results:
106
+ return "📝 هنوز تاریخچه‌ای ندارید"
 
 
107
 
108
+ history_text = "# 📊 تاریخچه شما\n\n"
109
+ for i, (timestamp, query_type, input_text, response) in enumerate(results, 1):
110
+ emoji = "💊" if query_type == "drug_interaction" else "🔬"
111
+ history_text += f"## {emoji} مورد {i} - {timestamp}\n\n"
112
+ history_text += f"**ورودی:** {input_text[:100]}...\n\n"
113
+ history_text += f"**پاسخ:** {response[:200]}...\n\n---\n\n"
114
 
115
+ return history_text
116
+ except Exception as e:
117
+ logger.error(f"Error getting history: {e}")
118
+ return "❌ خطا در دریافت تاریخچه"
119
+
120
+ def clear_user_history(session_id):
121
+ """پاک کردن تاریخچه"""
122
+ try:
123
+ conn = sqlite3.connect("nurca.db")
124
+ cursor = conn.cursor()
125
+ cursor.execute("DELETE FROM chat_history WHERE session_id = ?", (session_id,))
126
+ conn.commit()
127
+ conn.close()
128
+ return "✅ تاریخچه شما پاک شد!"
129
+ except Exception as e:
130
+ logger.error(f"Error clearing history: {e}")
131
+ return "❌ خطا در پاک کردن تاریخچه"
132
+
133
+ def analyze_drug_interaction(drug1, drug2, session_id):
134
+ """تحلیل تداخل دارویی"""
135
+ if not drug1.strip() or not drug2.strip():
136
+ return "⚠️ لطفاً نام هر دو دارو را وارد کنید"
137
+
138
+ try:
139
+ prompt = f"""شما یک متخصص داروسازی و فارماکولوژی هستید. لطفاً تداخل بین این دو دارو را به صورت کامل تحلیل کنید:
140
+
141
+ دارو اول: {drug1}
142
+ دارو دوم: {drug2}
143
 
144
+ لطفاً موارد زیر را بررسی کنید:
145
+ 1. آیا این دو دارو تداخل دارند؟
146
+ 2. نوع تداخل (فارماکوکینتیک یا فارماکودینامیک)
147
+ 3. شدت تداخل (خفیف، متوسط، شدید)
148
+ 4. مکانیسم تداخل
149
+ 5. عوارض جانبی احتمالی
150
+ 6. توصیه‌های عملی برای بیمار
151
+ 7. نیاز به تغییر دوز یا زمان‌بندی
152
 
153
+ پاسخ را به فارسی و با جزئیات کامل ارائه دهید."""
154
 
155
  completion = client.chat.completions.create(
156
  extra_headers={
157
+ "HTTP-Referer": "https://medical-ai.com",
158
+ "X-Title": "Medical Drug Interaction Checker",
159
  },
160
+ extra_body={},
161
+ model="openai/gpt-oss-20b:free",
162
  messages=[
163
+ {
164
+ "role": "user",
165
+ "content": prompt
166
+ }
167
+ ]
 
168
  )
169
+
170
  result = completion.choices[0].message.content
171
 
172
+ # ذخیره در دیتابیس
173
+ save_to_database(session_id, f"تداخل دارویی: {drug1} + {drug2}", None, result, "drug_interaction")
174
 
175
+ return f"# 💊 تحلیل تداخل دارویی\n\n## داروهای بررسی شده:\n- **{drug1}**\n- **{drug2}**\n\n## نتیجه تحلیل:\n\n{result}"
176
 
177
  except Exception as e:
178
+ error_msg = f" خطا در تحلیل: {str(e)}"
179
+ logger.error(error_msg)
180
+ return error_msg
181
 
182
+ def analyze_lab_image(image, session_id):
183
+ """تحلیل تصویر آزمایش"""
184
+ if image is None:
185
+ return "⚠️ لطفاً تصویر آزمایش را آپلود کنید"
 
186
 
187
+ try:
188
+ # ذخیره موقت تصویر برای OCR
189
+ temp_path = "temp_image.png"
190
+ image.save(temp_path)
191
+
192
+ # استخراج متن از تصویر
193
+ extracted_text = extract_text_easyocr(temp_path)
194
+
195
+ # حذف فایل موقت
196
+ if os.path.exists(temp_path):
197
+ os.remove(temp_path)
198
+
199
+ prompt = f"""شما یک متخصص آزمایشگاه و پاتولوژیست هستید. این متن از یک نتیجه آزمایش استخراج شده:
200
 
201
+ {extracted_text}
 
202
 
203
+ لطفاً این نتیجه آزمایش را تحلیل کنید:
 
 
204
 
205
+ 1. نوع آزمایش را شناسایی کنید
206
+ 2. مقادیر غیرطبیعی را مشخص کنید
207
+ 3. تفسیر بالینی نتایج
208
+ 4. نکات مهم برای بیمار
209
+ 5. نیاز به آزمایش‌های تکمیلی
210
+ 6. توصیه‌های اولیه
211
+
212
+ ⚠️ تأکید: این تحلیل صرفاً جهت اطلاع اولیه است و جایگزین مشاوره پزشک نیست.
213
+
214
+ پاسخ را به فارسی و با جزئیات کامل بدهید."""
215
+
216
+ completion = client.chat.completions.create(
217
+ extra_headers={
218
+ "HTTP-Referer": "https://medical-ai.com",
219
+ "X-Title": "Medical Lab Analysis",
220
+ },
221
+ extra_body={},
222
+ model="openai/gpt-oss-20b:free",
223
+ messages=[
224
+ {
225
+ "role": "user",
226
+ "content": prompt
227
+ }
228
+ ]
229
+ )
230
+
231
+ result = completion.choices[0].message.content
232
 
233
+ # ذخیره در دیتابیس
234
+ save_to_database(session_id, "تحلیل تصویر آزمایش", image, result, "lab_analysis")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
235
 
236
+ return f"# 🔬 تحلیل نتیجه آزمایش\n\n## متن استخراج شده:\n```\n{extracted_text}\n```\n\n## تحلیل:\n\n{result}"
 
 
 
 
 
 
 
237
 
238
+ except Exception as e:
239
+ error_msg = f"❌ خطا در تحلیل تصویر: {str(e)}"
240
+ logger.error(error_msg)
241
+ return error_msg
242
+
243
+ # راه‌اندازی دیتابیس
244
+ init_database()
245
+
246
+ # ایجاد رابط کاربری Gradio
247
+ def create_app():
248
+ with gr.Blocks(
249
+ theme=gr.themes.Soft(),
250
+ css="""
251
+ .main-header {
252
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
253
+ padding: 30px;
254
+ border-radius: 15px;
255
+ margin-bottom: 20px;
256
+ text-align: center;
257
+ color: white;
258
+ }
259
+ .feature-box {
260
+ background: white;
261
+ border-radius: 10px;
262
+ padding: 20px;
263
+ margin: 10px 0;
264
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
265
+ }
266
+ .warning-box {
267
+ background: #fff3cd;
268
+ border: 1px solid #ffeaa7;
269
+ border-radius: 8px;
270
+ padding: 15px;
271
+ margin: 15px 0;
272
+ }
273
+ """,
274
+ title="🏥Nurca دستیار هوشمند پزشکی"
275
+ ) as app:
276
+
277
+ # ایجاد session منحصر به فرد برای هر کاربر جدید
278
+ session_state = gr.State(value=generate_session())
279
+
280
+ # هدر اصلی
281
+ gr.HTML("""
282
+ <div class="main-header">
283
+ <h1>🏥 دستیار هوشمند پزشکی</h1>
284
+ <p>سیستم هوشمند تحلیل تداخلات دارویی و نتایج آزمایش</p>
285
+ </div>
286
+ """)
287
+
288
+ # هشدار مهم
289
+ gr.HTML("""
290
+ <div class="warning-box">
291
+ <h3>⚠️ هشدار مهم</h3>
292
+ <p>این سیستم صرفاً جهت اطلاع‌رسانی اولیه است و هیچ‌گاه جایگزین مشاوره پزشک نمی‌شود.
293
+ برای تصمیم‌گیری‌های درمانی حتماً با پزشک متخصص مشورت کنید.</p>
294
+ </div>
295
+ """)
296
 
297
+ with gr.Tabs():
298
+ # تب تداخل دارویی
299
+ with gr.Tab("💊 بررسی تداخل دارویی"):
300
+ with gr.Row():
301
+ with gr.Column(scale=2):
302
+ gr.HTML('<div class="feature-box"><h3>🔍 بررسی تداخل بین داروها</h3></div>')
303
+
304
+ drug1_input = gr.Textbox(
305
+ label="نام دارو اول",
306
+ placeholder="مثال: آسپرین، پاراستامول، ...",
307
+ lines=1
308
+ )
309
+
310
+ drug2_input = gr.Textbox(
311
+ label="نام دارو دوم",
312
+ placeholder="مثال: وارفارین، دیکلوفناک، ...",
313
+ lines=1
314
+ )
315
+
316
+ analyze_btn = gr.Button("🔬 تحلیل تداخل", variant="primary", size="lg")
317
+
318
+ with gr.Column(scale=3):
319
+ drug_result = gr.Markdown(
320
+ value="نتیجه تحلیل اینجا نمایش داده می‌شود...",
321
+ label="نتیجه تحلیل"
322
+ )
323
+
324
+ # تب تحلیل آزمایش
325
+ with gr.Tab("🔬 تحلیل نتایج آزمایش"):
326
+ with gr.Row():
327
+ with gr.Column(scale=2):
328
+ gr.HTML('<div class="feature-box"><h3>📋 آپلود و تحلیل نتایج آزمایش</h3></div>')
329
+
330
+ image_input = gr.Image(
331
+ label="تصویر نتیجه آزمایش",
332
+ type="pil",
333
+ height=300
334
+ )
335
+
336
+ analyze_lab_btn = gr.Button("🧪 تحلیل آزمایش", variant="primary", size="lg")
337
+
338
+ with gr.Column(scale=3):
339
+ lab_result = gr.Markdown(
340
+ value="نتیجه تحلیل آزمایش اینجا نمایش داده می‌شود...",
341
+ label="نتیجه تحلیل"
342
+ )
343
+
344
+ # تب تاریخچه
345
+ with gr.Tab("📊 تاریخچه و مدیریت"):
346
+ with gr.Row():
347
+ with gr.Column():
348
+ gr.HTML('<div class="feature-box"><h3>📝 مدیریت تاریخچه</h3></div>')
349
+
350
+ with gr.Row():
351
+ show_history_btn = gr.Button("📋 نمایش تاریخچه", variant="secondary")
352
+ clear_history_btn = gr.Button("🗑️ پاک کردن تاریخچه", variant="stop")
353
+
354
+ history_display = gr.Markdown(
355
+ value="برای نمایش تاریخچه، روی دکمه مربوطه کلیک کنید.",
356
+ label="تاریخچه کاربر"
357
+ )
358
+
359
+ session_info = gr.Textbox(
360
+ value="Session ID: جدید",
361
+ label="شناسه جلسه",
362
+ interactive=False
363
+ )
364
 
365
+ def update_session_display(session_id):
366
+ return f"Session ID: {session_id}"
367
+
368
+ # اتصال eventها
369
  analyze_btn.click(
370
+ fn=lambda d1, d2, session_id: analyze_drug_interaction(d1, d2, session_id),
371
+ inputs=[drug1_input, drug2_input, session_state],
372
+ outputs=drug_result
373
  )
374
 
375
+ analyze_lab_btn.click(
376
+ fn=lambda img, session_id: analyze_lab_image(img, session_id),
377
+ inputs=[image_input, session_state],
378
+ outputs=lab_result
379
  )
380
 
381
+ show_history_btn.click(
382
+ fn=lambda session_id: get_user_history(session_id),
383
+ inputs=session_state,
384
+ outputs=history_display
385
+ )
386
+
387
+ clear_history_btn.click(
388
+ fn=lambda session_id: clear_user_history(session_id),
389
+ inputs=session_state,
390
+ outputs=history_display
391
+ )
392
+
393
+ app.load(
394
+ fn=update_session_display,
395
+ inputs=session_state,
396
+ outputs=session_info
397
+ )
398
 
399
  return app
400
 
 
401
  if __name__ == "__main__":
402
+ app = create_app()
403
  app.launch(
404
+ server_name="0.0.0.0",
 
405
  server_port=7860,
406
+ share=True,
407
+ show_api=False
408
  )