Files changed (1) hide show
  1. app.py +24 -23
app.py CHANGED
@@ -24,8 +24,8 @@ from reportlab.pdfbase.ttfonts import TTFont
24
  # 1) Configuration & Setup
25
  # ============================================
26
 
27
- # 🔑 API KEY
28
- GOOGLE_API_KEY = os.getenv("AIzaSyBYksOq03N5V2MjSYicHdsk4ESdyR9FABw")
29
  if GOOGLE_API_KEY:
30
  genai.configure(api_key=GOOGLE_API_KEY)
31
 
@@ -48,17 +48,23 @@ def force_download_font(url, filename):
48
  if not os.path.exists(filename):
49
  print(f"📥 Downloading {filename}...")
50
  try:
51
- r = requests.get(url, allow_redirects=True)
52
- with open(filename, 'wb') as f:
53
- f.write(r.content)
 
 
 
 
 
 
54
  except Exception as e:
55
  print(f"❌ Error downloading {filename}: {e}")
56
  return False
57
  return True
58
 
59
  font_urls = [
60
- ("https://github.com/nutjunkie/thaifonts_sipa/raw/master/sipa_fonts/THSarabunNew/THSarabunNew.ttf", "THSarabunNew.ttf"),
61
- ("https://github.com/nutjunkie/thaifonts_sipa/raw/master/sipa_fonts/THSarabunNew/THSarabunNew%20Bold.ttf", "THSarabunNew-Bold.ttf")
62
  ]
63
 
64
  for url, fname in font_urls:
@@ -98,8 +104,6 @@ def create_medical_report(pt_name, pt_id, diagnosis, conf):
98
  try:
99
  filename = tempfile.mktemp(suffix=".pdf")
100
  c = canvas.Canvas(filename, pagesize=A4)
101
-
102
- # Use registered font if available, else standard
103
  font_name = 'THSarabun-Bold' if 'THSarabun-Bold' in pdfmetrics.getRegisteredFontNames() else 'Helvetica-Bold'
104
 
105
  c.setFont(font_name, 24)
@@ -119,22 +123,20 @@ def create_medical_report(pt_name, pt_id, diagnosis, conf):
119
  return None
120
 
121
  # ============================================
122
- # [FIXED] Chat Function
123
  # ============================================
124
  def chat_fn(message, history, crop_img, info_text, diagnosis):
125
- # เปลี่ยนจาก history = [] เป็นการรับค่า list ของ dict
126
  if history is None: history = []
127
 
128
- # 1. เช็ค API Key
129
  if not GOOGLE_API_KEY:
130
- response = "❌ ไม่พบ API KEY: กรุณาไปที่ Settings > Secrets แล้วตั้งค่า 'GOOGLE_API_KEY' จากั้นกด Restart Space"
131
- # เพิ่มข้อความลง history แบบ Dictionary (ตามมาตรฐานใหม่ Huggingface/Gradio)
132
  history.append({"role": "user", "content": message})
133
  history.append({"role": "assistant", "content": response})
134
  return history, ""
135
 
136
  try:
137
- # 2. สร้าง Prompt
138
  context_prompt = f"""
139
  บทบาท: คุณคือผู้ช่วยทางการแพทย์อัจฉริยะ (AI Medical Assistant)
140
 
@@ -150,8 +152,8 @@ def chat_fn(message, history, crop_img, info_text, diagnosis):
150
  - *สำคัญ*: ต้องลงท้ายเสมอว่า "ควรปรึกษาแพทย์ผู้เชี่ยวชาญเพื่อการวินิจฉัยที่แม่นยำที่สุด"
151
  """
152
 
153
- # 3. เรียกใช้ Gemini
154
- model = genai.GenerativeModel('gemini-1.5-flash')
155
  response = model.generate_content(context_prompt)
156
  bot_reply = response.text
157
 
@@ -159,11 +161,10 @@ def chat_fn(message, history, crop_img, info_text, diagnosis):
159
  bot_reply = f"เกิดข้อผิดพลาด (System Error): {str(e)}"
160
  print(f"DEBUG ERROR: {e}")
161
 
162
- # [FIX] เพิ่มข้อความลงใน History แบบ Dictionary
163
  history.append({"role": "user", "content": message})
164
  history.append({"role": "assistant", "content": bot_reply})
165
 
166
- # คืนค่า history และ string ว่าง ("") เพื่อลบข้อความในช่องพิมพ์
167
  return history, ""
168
 
169
  # ============================================
@@ -344,13 +345,13 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css, title="Ovarian Tumor AI") as dem
344
  with gr.Tab("3. Gallery History"):
345
  gallery_ui = gr.Gallery(columns=4, height=600)
346
 
347
- # --- [FIXED] Floating Chatbot ---
348
  with gr.Column(elem_id="floating_container"):
349
  with gr.Column(elem_id="chat_window"):
350
  gr.HTML(f"<div style='background:linear-gradient(90deg, #0072ff, #00c6ff); color:white; padding:15px; border-radius:15px 15px 0 0;'><b>💬 ปรึกษาน้องดูแล</b></div>")
351
 
352
- # [FIX] เพิ่ม type="messages" เพื่อบอก Gradio ว่าใช้ format ใหม่
353
- chatbot = gr.Chatbot(height=400, show_label=False, avatar_images=(None, LOGO_RAMA_URL), type="messages")
354
 
355
  msg = gr.Textbox(placeholder="พิมพ์คำถามที่นี่...", show_label=False)
356
  btn_send = gr.Button("ส่งข้อความ", variant="primary")
@@ -374,7 +375,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css, title="Ovarian Tumor AI") as dem
374
 
375
  btn_pdf.click(pdf_wrapper, [inp_pt_name, inp_pt_id, state_diag, state_conf], out_pdf)
376
 
377
- # [FIX] Chat interaction: เพิ่ม outputs ตัวที่ 2 (msg) เพื่อล้างข้อความ
378
  btn_send.click(chat_fn, [msg, chatbot, state_crop, state_info, state_diag], [chatbot, msg])
379
  msg.submit(chat_fn, [msg, chatbot, state_crop, state_info, state_diag], [chatbot, msg])
380
 
 
24
  # 1) Configuration & Setup
25
  # ============================================
26
 
27
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
28
+
29
  if GOOGLE_API_KEY:
30
  genai.configure(api_key=GOOGLE_API_KEY)
31
 
 
48
  if not os.path.exists(filename):
49
  print(f"📥 Downloading {filename}...")
50
  try:
51
+ session = requests.Session()
52
+ session.headers.update({'User-Agent': 'Mozilla/5.0'})
53
+ r = session.get(url, allow_redirects=True)
54
+ if r.status_code == 200 and len(r.content) > 1000:
55
+ with open(filename, 'wb') as f:
56
+ f.write(r.content)
57
+ else:
58
+ print(f"❌ Failed to download {filename} (Status: {r.status_code})")
59
+ return False
60
  except Exception as e:
61
  print(f"❌ Error downloading {filename}: {e}")
62
  return False
63
  return True
64
 
65
  font_urls = [
66
+ ("https://raw.githubusercontent.com/nutjunkie/thaifonts_sipa/master/sipa_fonts/THSarabunNew/THSarabunNew.ttf", "THSarabunNew.ttf"),
67
+ ("https://raw.githubusercontent.com/nutjunkie/thaifonts_sipa/master/sipa_fonts/THSarabunNew/THSarabunNew%20Bold.ttf", "THSarabunNew-Bold.ttf")
68
  ]
69
 
70
  for url, fname in font_urls:
 
104
  try:
105
  filename = tempfile.mktemp(suffix=".pdf")
106
  c = canvas.Canvas(filename, pagesize=A4)
 
 
107
  font_name = 'THSarabun-Bold' if 'THSarabun-Bold' in pdfmetrics.getRegisteredFontNames() else 'Helvetica-Bold'
108
 
109
  c.setFont(font_name, 24)
 
123
  return None
124
 
125
  # ============================================
126
+ # [FIXED] Chat Function (Dictionary Format)
127
  # ============================================
128
  def chat_fn(message, history, crop_img, info_text, diagnosis):
 
129
  if history is None: history = []
130
 
131
+ # 1. API Key Check
132
  if not GOOGLE_API_KEY:
133
+ response = "❌ ไม่พบ API KEY: กรุณาตรจสอบการตั้งค่า GOOGLE_API_KEY ไฟล์ app.py"
 
134
  history.append({"role": "user", "content": message})
135
  history.append({"role": "assistant", "content": response})
136
  return history, ""
137
 
138
  try:
139
+ # 2. Context Prompt
140
  context_prompt = f"""
141
  บทบาท: คุณคือผู้ช่วยทางการแพทย์อัจฉริยะ (AI Medical Assistant)
142
 
 
152
  - *สำคัญ*: ต้องลงท้ายเสมอว่า "ควรปรึกษาแพทย์ผู้เชี่ยวชาญเพื่อการวินิจฉัยที่แม่นยำที่สุด"
153
  """
154
 
155
+ # 3. Call Gemini
156
+ model = genai.GenerativeModel('gemini-2.5-flash')
157
  response = model.generate_content(context_prompt)
158
  bot_reply = response.text
159
 
 
161
  bot_reply = f"เกิดข้อผิดพลาด (System Error): {str(e)}"
162
  print(f"DEBUG ERROR: {e}")
163
 
164
+ # Append Dictionary format
165
  history.append({"role": "user", "content": message})
166
  history.append({"role": "assistant", "content": bot_reply})
167
 
 
168
  return history, ""
169
 
170
  # ============================================
 
345
  with gr.Tab("3. Gallery History"):
346
  gallery_ui = gr.Gallery(columns=4, height=600)
347
 
348
+ # --- Floating Chatbot ---
349
  with gr.Column(elem_id="floating_container"):
350
  with gr.Column(elem_id="chat_window"):
351
  gr.HTML(f"<div style='background:linear-gradient(90deg, #0072ff, #00c6ff); color:white; padding:15px; border-radius:15px 15px 0 0;'><b>💬 ปรึกษาน้องดูแล</b></div>")
352
 
353
+ # Chatbot: No type param needed here, but data passed will be dicts
354
+ chatbot = gr.Chatbot(height=400, show_label=False, avatar_images=(None, LOGO_RAMA_URL))
355
 
356
  msg = gr.Textbox(placeholder="พิมพ์คำถามที่นี่...", show_label=False)
357
  btn_send = gr.Button("ส่งข้อความ", variant="primary")
 
375
 
376
  btn_pdf.click(pdf_wrapper, [inp_pt_name, inp_pt_id, state_diag, state_conf], out_pdf)
377
 
378
+ # Chat interactions
379
  btn_send.click(chat_fn, [msg, chatbot, state_crop, state_info, state_diag], [chatbot, msg])
380
  msg.submit(chat_fn, [msg, chatbot, state_crop, state_info, state_diag], [chatbot, msg])
381