DeepLearning101 commited on
Commit
834bad5
·
verified ·
1 Parent(s): 7c1e48e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +170 -151
app.py CHANGED
@@ -8,7 +8,7 @@ from huggingface_hub import HfApi, hf_hub_download
8
 
9
  # Load Env
10
  load_dotenv()
11
- SAVE_FILE = os.getenv("SAVE_FILE_NAME", "saved_professors.json")
12
  HF_TOKEN = os.getenv("HF_TOKEN")
13
  DATASET_REPO_ID = os.getenv("DATASET_REPO_ID")
14
 
@@ -21,8 +21,9 @@ except Exception as e:
21
 
22
  # --- Helper Functions ---
23
 
24
- def get_key(p):
25
- return f"{p['name']}-{p['university']}"
 
26
 
27
  def load_data():
28
  data = []
@@ -68,76 +69,75 @@ def save_data(data):
68
  path_in_repo=SAVE_FILE,
69
  repo_id=DATASET_REPO_ID,
70
  repo_type="dataset",
71
- commit_message="Sync data from Space"
72
  )
73
  except Exception as e:
74
  print(f"Upload Error: {e}")
75
 
76
  def format_df(source_list, saved_list):
77
  if not source_list:
78
- return pd.DataFrame(columns=["狀態", "姓名", "大學", "系所", "標籤"])
79
 
80
  if saved_list is None:
81
  saved_list = []
82
 
83
- saved_map = {get_key(p): p for p in saved_list}
84
 
85
  data = []
86
- for p in source_list:
87
- display_p = saved_map.get(get_key(p), p)
88
 
89
- status_map = {'match': '✅', 'mismatch': '', 'pending': '❓'}
90
- status_icon = status_map.get(display_p.get('status'), '')
91
- has_detail = "📄" if display_p.get('details') else ""
92
 
93
- tags = ", ".join(display_p.get('tags', []))
94
 
95
  data.append([
96
  f"{status_icon} {has_detail}",
97
- display_p['name'],
98
- display_p['university'],
99
- display_p['department'],
100
  tags
101
  ])
102
- return pd.DataFrame(data, columns=["狀態", "姓名", "大學", "系所", "標籤"])
103
 
104
- def get_tags_text(prof):
105
- if not prof or not prof.get('tags'):
106
  return "目前標籤: (無)"
107
- return "🏷️ " + ", ".join([f"`{t}`" for t in prof['tags']])
108
 
109
- def get_tags_choices(prof):
110
- if not prof: return []
111
- return prof.get('tags', [])
112
 
113
  # --- Event Handlers ---
114
 
115
- def search_professors(query, current_saved):
116
  if not query: return gr.update(), current_saved, gr.update()
117
 
118
  try:
119
- results = gemini_service.search_professors(query)
120
  return format_df(results, current_saved), results, gr.update(visible=True)
121
  except Exception as e:
122
  raise gr.Error(f"搜尋失敗: {e}")
123
 
124
- def load_more(query, current_search_results, current_saved):
125
- if not query: return gr.update(), current_search_results
126
 
127
- current_names = [p['name'] for p in current_search_results]
128
  try:
129
- new_results = gemini_service.search_professors(query, exclude_names=current_names)
130
 
131
- existing_keys = set(get_key(p) for p in current_search_results)
132
- for p in new_results:
133
- if get_key(p) not in existing_keys:
134
- current_search_results.append(p)
135
 
136
- return format_df(current_search_results, current_saved), current_search_results
137
  except Exception as e:
138
  raise gr.Error(f"載入失敗: {e}")
139
 
140
- def select_professor_from_df(evt: gr.SelectData, search_results, saved_data, view_mode):
141
  if not evt: return [gr.update()] * 8
142
  index = evt.index[0]
143
 
@@ -145,69 +145,71 @@ def select_professor_from_df(evt: gr.SelectData, search_results, saved_data, vie
145
  if not target_list or index >= len(target_list):
146
  return gr.update(), gr.update(), gr.update(), None, None, gr.update(), gr.update(), gr.update()
147
 
148
- prof = target_list[index]
149
 
150
- key = get_key(prof)
151
- saved_prof = next((p for p in saved_data if get_key(p) == key), None)
152
- current_prof = saved_prof if saved_prof else prof
153
 
154
  details_md = ""
155
 
156
- if current_prof.get('details') and len(current_prof.get('details')) > 10:
157
- details_md = current_prof['details']
158
- if not saved_prof:
159
- saved_data.insert(0, current_prof)
 
160
  save_data(saved_data)
161
  else:
162
- gr.Info(f"正在調查 {current_prof['name']}...")
 
163
  try:
164
- res = gemini_service.get_professor_details(current_prof)
165
- current_prof['details'] = res['text']
166
- current_prof['sources'] = res['sources']
167
  details_md = res['text']
168
 
169
- if saved_prof:
170
- saved_prof.update(current_prof)
171
  else:
172
- saved_data.insert(0, current_prof)
173
  save_data(saved_data)
174
  except Exception as e:
175
  raise gr.Error(f"調查失敗: {e}")
176
 
177
- if current_prof.get('sources'):
178
- details_md += "\n\n### 📚 參考來源\n"
179
- for s in current_prof['sources']:
180
  details_md += f"- [{s['title']}]({s['uri']})\n"
181
 
182
  return (
183
  gr.update(visible=True),
184
  details_md,
185
  [],
186
- current_prof,
187
  saved_data,
188
- get_tags_text(current_prof),
189
- gr.update(choices=get_tags_choices(current_prof), value=None),
190
  gr.update(visible=True)
191
  )
192
 
193
- def add_tag(new_tag, selected_prof, saved_data, view_mode, search_results):
194
- if not selected_prof or not new_tag:
195
  return gr.update(), gr.update(), gr.update(), saved_data, gr.update()
196
 
197
- if 'tags' not in selected_prof: selected_prof['tags'] = []
198
 
199
- if new_tag not in selected_prof['tags']:
200
- selected_prof['tags'].append(new_tag)
201
 
202
- key = get_key(selected_prof)
203
  found = False
204
- for i, p in enumerate(saved_data):
205
- if get_key(p) == key:
206
- saved_data[i] = selected_prof
207
  found = True
208
  break
209
  if not found:
210
- saved_data.insert(0, selected_prof)
211
 
212
  save_data(saved_data)
213
  gr.Info(f"已新增標籤: {new_tag}")
@@ -217,23 +219,23 @@ def add_tag(new_tag, selected_prof, saved_data, view_mode, search_results):
217
 
218
  return (
219
  gr.update(value=""),
220
- get_tags_text(selected_prof),
221
- gr.update(choices=selected_prof['tags']),
222
  saved_data,
223
  new_df
224
  )
225
 
226
- def remove_tag(tag_to_remove, selected_prof, saved_data, view_mode, search_results):
227
- if not selected_prof or not tag_to_remove:
228
  return gr.update(), gr.update(), saved_data, gr.update()
229
 
230
- if 'tags' in selected_prof and tag_to_remove in selected_prof['tags']:
231
- selected_prof['tags'].remove(tag_to_remove)
232
 
233
- key = get_key(selected_prof)
234
- for i, p in enumerate(saved_data):
235
- if get_key(p) == key:
236
- saved_data[i] = selected_prof
237
  break
238
  save_data(saved_data)
239
  gr.Info(f"已移除標籤: {tag_to_remove}")
@@ -242,15 +244,15 @@ def remove_tag(tag_to_remove, selected_prof, saved_data, view_mode, search_resul
242
  new_df = format_df(target_list, saved_data)
243
 
244
  return (
245
- get_tags_text(selected_prof),
246
- gr.update(choices=selected_prof['tags'], value=None),
247
  saved_data,
248
  new_df
249
  )
250
 
251
- def chat_response(history, message, selected_prof):
252
- if not selected_prof: return history, ""
253
- context = selected_prof.get('details', '')
254
  if not context: return history, ""
255
 
256
  service_history = []
@@ -265,26 +267,26 @@ def chat_response(history, message, selected_prof):
265
  history.append((message, f"Error: {e}"))
266
  return history, ""
267
 
268
- def update_status(status, selected_prof, saved_data, view_mode, search_results):
269
- if not selected_prof: return gr.update(), saved_data
270
 
271
- selected_prof['status'] = status if selected_prof.get('status') != status else None
272
 
273
- key = get_key(selected_prof)
274
- for i, p in enumerate(saved_data):
275
- if get_key(p) == key:
276
- saved_data[i] = selected_prof
277
  break
278
  save_data(saved_data)
279
 
280
  target_list = saved_data if view_mode == "追蹤清單" else search_results
281
  return format_df(target_list, saved_data), saved_data
282
 
283
- def remove_prof(selected_prof, saved_data, view_mode, search_results):
284
- if not selected_prof: return gr.update(), gr.update(value=None), saved_data, gr.update(visible=False)
285
 
286
- key = get_key(selected_prof)
287
- new_saved = [p for p in saved_data if get_key(p) != key]
288
  save_data(new_saved)
289
 
290
  target_list = new_saved if view_mode == "追蹤清單" else search_results
@@ -308,21 +310,33 @@ def init_on_load():
308
 
309
  # --- UI Layout ---
310
 
311
- with gr.Blocks(title="Prof.404 開箱教授去哪兒?", theme=gr.themes.Soft()) as demo:
312
 
313
  saved_state = gr.State([])
314
  search_res_state = gr.State([])
315
- selected_prof_state = gr.State(None)
316
 
317
- # 🌟 這裡插入了您要求的徽章與文字,使用 HTML 置中
318
  gr.Markdown("""
319
  <div align="center">
320
 
321
- # 🎓 Prof.404 - 開箱教授去哪兒?
322
- **學術研究啟程的導航系統,拒絕當科研路上的無頭蒼蠅** | **API Rate limits 是 RPD 20,故建議自行 Fork使用**</span>
 
 
 
 
 
 
 
323
  👉 歡迎 Star [GitHub](https://github.com/Deep-Learning-101/prof-404) ⭐ 覺得不錯 👈
324
-
 
 
 
 
325
  <h3>🧠 補腦專區:<a href="https://deep-learning-101.github.io/" target="_blank">Deep Learning 101</a></h3>
 
326
 
327
  | 🔥 技術傳送門 (Tech Stack) | 📚 必讀心法 (Must Read) |
328
  | :--- | :--- |
@@ -330,11 +344,10 @@ with gr.Blocks(title="Prof.404 開箱教授去哪兒?", theme=gr.themes.Soft()
330
  | 📝 [**自然語言處理 (NLP)**](https://deep-learning-101.github.io/Natural-Language-Processing) | 📊 [**評測篇:臺灣 LLM 分析**](https://deep-learning-101.github.io/Blog/TW-LLM-Benchmark) |
331
  | 👁️ [**電腦視覺 (CV)**](https://deep-learning-101.github.io//Computer-Vision) | 🛠️ [**實戰篇:打造高精準 RAG**](https://deep-learning-101.github.io/RAG) |
332
  | 🎤 [**語音處理 (Speech)**](https://deep-learning-101.github.io/Speech-Processing) | 🕳️ [**避坑篇:AI Agent 開發陷阱**](https://deep-learning-101.github.io/agent) |
333
- </div>
334
  """)
335
 
336
  with gr.Row():
337
- search_input = gr.Textbox(label="搜尋研究領域", placeholder="例如: 大型語言模型, 後量子密碼遷移...", scale=4)
338
  search_btn = gr.Button("🔍 搜尋", variant="primary", scale=1)
339
 
340
  with gr.Row():
@@ -343,11 +356,11 @@ with gr.Blocks(title="Prof.404 開箱教授去哪兒?", theme=gr.themes.Soft()
343
  with gr.Row():
344
  # Left: List
345
  with gr.Column(scale=1):
346
- prof_df = gr.Dataframe(
347
- headers=["狀態", "姓名", "大學", "系所", "標籤"],
348
- datatype=["str", "str", "str", "str", "str"],
349
  interactive=False,
350
- label="教授列表 (點擊查看詳情)"
351
  )
352
  load_more_btn = gr.Button("載入更多", visible=False)
353
 
@@ -355,92 +368,98 @@ with gr.Blocks(title="Prof.404 開箱教授去哪兒?", theme=gr.themes.Soft()
355
  with gr.Column(scale=2, visible=False) as details_col:
356
  detail_md = gr.Markdown("詳細資料...")
357
 
358
- # Status Buttons
359
- with gr.Row():
360
- btn_match = gr.Button(" 符合")
361
- btn_mismatch = gr.Button("❌ 不符")
362
- btn_pending = gr.Button("❓ 待觀察")
363
- btn_remove = gr.Button("🗑️ 移除", variant="stop")
364
-
 
365
  gr.Markdown("---")
366
-
367
- # Tags Management
368
  with gr.Column(visible=False) as tags_row:
369
  tags_display = gr.Markdown("目前標籤: (無)")
370
  with gr.Row():
371
- tag_input = gr.Textbox(label="新增標籤", placeholder="輸入後按新增...", scale=3)
372
  tag_add_btn = gr.Button("➕ 新增", scale=1)
373
 
374
  with gr.Accordion("刪除標籤", open=False):
375
  with gr.Row():
376
  tag_dropdown = gr.Dropdown(label="選擇標籤", choices=[], scale=3)
377
  tag_del_btn = gr.Button("🗑️ 刪除", scale=1, variant="secondary")
378
-
379
- gr.Markdown("---")
380
- gr.Markdown("### 💬 AI 助手")
381
- chatbot = gr.Chatbot(height=300)
382
- msg = gr.Textbox(label="提問")
383
- send_btn = gr.Button("送出")
384
 
385
  # --- Wiring ---
386
 
387
- demo.load(init_on_load, inputs=None, outputs=[saved_state, prof_df])
 
388
 
 
389
  search_btn.click(
390
- search_professors,
391
- inputs=[search_input, saved_state],
392
- outputs=[prof_df, search_res_state, load_more_btn]
393
  ).then(
394
  lambda: gr.update(value="搜尋結果"), outputs=[view_radio]
395
  )
396
 
397
  load_more_btn.click(
398
- load_more,
399
- inputs=[search_input, search_res_state, saved_state],
400
- outputs=[prof_df, search_res_state]
401
  )
402
 
403
  view_radio.change(
404
- toggle_view,
405
- inputs=[view_radio, search_res_state, saved_state],
406
- outputs=[prof_df, load_more_btn]
407
  )
408
 
409
- prof_df.select(
410
- select_professor_from_df,
411
- inputs=[search_res_state, saved_state, view_radio],
 
412
  outputs=[
413
- details_col, detail_md, chatbot, selected_prof_state, saved_state,
414
  tags_display, tag_dropdown, tags_row
415
  ]
416
  )
417
 
418
- send_btn.click(chat_response, inputs=[chatbot, msg, selected_prof_state], outputs=[chatbot, msg])
419
- msg.submit(chat_response, inputs=[chatbot, msg, selected_prof_state], outputs=[chatbot, msg])
 
420
 
 
421
  tag_add_btn.click(
422
- add_tag,
423
- inputs=[tag_input, selected_prof_state, saved_state, view_radio, search_res_state],
424
- outputs=[tag_input, tags_display, tag_dropdown, saved_state, prof_df]
425
  )
426
-
427
  tag_del_btn.click(
428
- remove_tag,
429
- inputs=[tag_dropdown, selected_prof_state, saved_state, view_radio, search_res_state],
430
- outputs=[tags_display, tag_dropdown, saved_state, prof_df]
431
  )
432
-
433
- for btn, status in [(btn_match, 'match'), (btn_mismatch, 'mismatch'), (btn_pending, 'pending')]:
 
434
  btn.click(
435
- update_status,
436
- inputs=[gr.State(status), selected_prof_state, saved_state, view_radio, search_res_state],
437
- outputs=[prof_df, saved_state]
438
  )
439
-
440
  btn_remove.click(
441
- remove_prof,
442
- inputs=[selected_prof_state, saved_state, view_radio, search_res_state],
443
- outputs=[gr.State(None), prof_df, saved_state, details_col]
444
  )
445
 
446
  if __name__ == "__main__":
 
8
 
9
  # Load Env
10
  load_dotenv()
11
+ SAVE_FILE = os.getenv("SAVE_FILE_NAME", "saved_companies.json")
12
  HF_TOKEN = os.getenv("HF_TOKEN")
13
  DATASET_REPO_ID = os.getenv("DATASET_REPO_ID")
14
 
 
21
 
22
  # --- Helper Functions ---
23
 
24
+ def get_key(c):
25
+ # 使用公司名稱當作 Key
26
+ return f"{c['name']}"
27
 
28
  def load_data():
29
  data = []
 
69
  path_in_repo=SAVE_FILE,
70
  repo_id=DATASET_REPO_ID,
71
  repo_type="dataset",
72
+ commit_message="Sync company data"
73
  )
74
  except Exception as e:
75
  print(f"Upload Error: {e}")
76
 
77
  def format_df(source_list, saved_list):
78
  if not source_list:
79
+ return pd.DataFrame(columns=["狀態", "公司名稱", "產業類別", "標籤"])
80
 
81
  if saved_list is None:
82
  saved_list = []
83
 
84
+ saved_map = {get_key(c): c for c in saved_list}
85
 
86
  data = []
87
+ for c in source_list:
88
+ display_c = saved_map.get(get_key(c), c)
89
 
90
+ status_map = {'good': '✅ 優質', 'risk': '⚠️ 風險', 'pending': '❓ 未定'}
91
+ status_icon = status_map.get(display_c.get('status'), '')
92
+ has_detail = "📄" if display_c.get('details') else ""
93
 
94
+ tags = ", ".join(display_c.get('tags', []))
95
 
96
  data.append([
97
  f"{status_icon} {has_detail}",
98
+ display_c['name'],
99
+ display_c.get('industry', '未知'),
 
100
  tags
101
  ])
102
+ return pd.DataFrame(data, columns=["狀態", "公司名稱", "產業類別", "標籤"])
103
 
104
+ def get_tags_text(comp):
105
+ if not comp or not comp.get('tags'):
106
  return "目前標籤: (無)"
107
+ return "🏷️ " + ", ".join([f"`{t}`" for t in comp['tags']])
108
 
109
+ def get_tags_choices(comp):
110
+ if not comp: return []
111
+ return comp.get('tags', [])
112
 
113
  # --- Event Handlers ---
114
 
115
+ def search_companies(query, current_saved):
116
  if not query: return gr.update(), current_saved, gr.update()
117
 
118
  try:
119
+ results = gemini_service.search_companies(query)
120
  return format_df(results, current_saved), results, gr.update(visible=True)
121
  except Exception as e:
122
  raise gr.Error(f"搜尋失敗: {e}")
123
 
124
+ def load_more(query, current_results, current_saved):
125
+ if not query: return gr.update(), current_results
126
 
127
+ current_names = [c['name'] for c in current_results]
128
  try:
129
+ new_results = gemini_service.search_companies(query, exclude_names=current_names)
130
 
131
+ existing_keys = set(get_key(c) for c in current_results)
132
+ for c in new_results:
133
+ if get_key(c) not in existing_keys:
134
+ current_results.append(c)
135
 
136
+ return format_df(current_results, current_saved), current_results
137
  except Exception as e:
138
  raise gr.Error(f"載入失敗: {e}")
139
 
140
+ def select_company(evt: gr.SelectData, search_results, saved_data, view_mode):
141
  if not evt: return [gr.update()] * 8
142
  index = evt.index[0]
143
 
 
145
  if not target_list or index >= len(target_list):
146
  return gr.update(), gr.update(), gr.update(), None, None, gr.update(), gr.update(), gr.update()
147
 
148
+ comp = target_list[index]
149
 
150
+ key = get_key(comp)
151
+ saved_comp = next((c for c in saved_data if get_key(c) == key), None)
152
+ current_comp = saved_comp if saved_comp else comp
153
 
154
  details_md = ""
155
 
156
+ # Check Cache
157
+ if current_comp.get('details') and len(current_comp.get('details')) > 10:
158
+ details_md = current_comp['details']
159
+ if not saved_comp:
160
+ saved_data.insert(0, current_comp)
161
  save_data(saved_data)
162
  else:
163
+ # Call API
164
+ gr.Info(f"正在調查 {current_comp['name']} (查詢統編、PTT評價)...")
165
  try:
166
+ res = gemini_service.get_company_details(current_comp)
167
+ current_comp['details'] = res['text']
168
+ current_comp['sources'] = res['sources']
169
  details_md = res['text']
170
 
171
+ if saved_comp:
172
+ saved_comp.update(current_comp)
173
  else:
174
+ saved_data.insert(0, current_comp)
175
  save_data(saved_data)
176
  except Exception as e:
177
  raise gr.Error(f"調查失敗: {e}")
178
 
179
+ if current_comp.get('sources'):
180
+ details_md += "\n\n### 📚 資料來源\n"
181
+ for s in current_comp['sources']:
182
  details_md += f"- [{s['title']}]({s['uri']})\n"
183
 
184
  return (
185
  gr.update(visible=True),
186
  details_md,
187
  [],
188
+ current_comp,
189
  saved_data,
190
+ get_tags_text(current_comp),
191
+ gr.update(choices=get_tags_choices(current_comp), value=None),
192
  gr.update(visible=True)
193
  )
194
 
195
+ def add_tag(new_tag, selected_comp, saved_data, view_mode, search_results):
196
+ if not selected_comp or not new_tag:
197
  return gr.update(), gr.update(), gr.update(), saved_data, gr.update()
198
 
199
+ if 'tags' not in selected_comp: selected_comp['tags'] = []
200
 
201
+ if new_tag not in selected_comp['tags']:
202
+ selected_comp['tags'].append(new_tag)
203
 
204
+ key = get_key(selected_comp)
205
  found = False
206
+ for i, c in enumerate(saved_data):
207
+ if get_key(c) == key:
208
+ saved_data[i] = selected_comp
209
  found = True
210
  break
211
  if not found:
212
+ saved_data.insert(0, selected_comp)
213
 
214
  save_data(saved_data)
215
  gr.Info(f"已新增標籤: {new_tag}")
 
219
 
220
  return (
221
  gr.update(value=""),
222
+ get_tags_text(selected_comp),
223
+ gr.update(choices=selected_comp['tags']),
224
  saved_data,
225
  new_df
226
  )
227
 
228
+ def remove_tag(tag_to_remove, selected_comp, saved_data, view_mode, search_results):
229
+ if not selected_comp or not tag_to_remove:
230
  return gr.update(), gr.update(), saved_data, gr.update()
231
 
232
+ if 'tags' in selected_comp and tag_to_remove in selected_comp['tags']:
233
+ selected_comp['tags'].remove(tag_to_remove)
234
 
235
+ key = get_key(selected_comp)
236
+ for i, c in enumerate(saved_data):
237
+ if get_key(c) == key:
238
+ saved_data[i] = selected_comp
239
  break
240
  save_data(saved_data)
241
  gr.Info(f"已移除標籤: {tag_to_remove}")
 
244
  new_df = format_df(target_list, saved_data)
245
 
246
  return (
247
+ get_tags_text(selected_comp),
248
+ gr.update(choices=selected_comp['tags'], value=None),
249
  saved_data,
250
  new_df
251
  )
252
 
253
+ def chat_response(history, message, selected_comp):
254
+ if not selected_comp: return history, ""
255
+ context = selected_comp.get('details', '')
256
  if not context: return history, ""
257
 
258
  service_history = []
 
267
  history.append((message, f"Error: {e}"))
268
  return history, ""
269
 
270
+ def update_status(status, selected_comp, saved_data, view_mode, search_results):
271
+ if not selected_comp: return gr.update(), saved_data
272
 
273
+ selected_comp['status'] = status if selected_comp.get('status') != status else None
274
 
275
+ key = get_key(selected_comp)
276
+ for i, c in enumerate(saved_data):
277
+ if get_key(c) == key:
278
+ saved_data[i] = selected_comp
279
  break
280
  save_data(saved_data)
281
 
282
  target_list = saved_data if view_mode == "追蹤清單" else search_results
283
  return format_df(target_list, saved_data), saved_data
284
 
285
+ def remove_comp(selected_comp, saved_data, view_mode, search_results):
286
+ if not selected_comp: return gr.update(), gr.update(value=None), saved_data, gr.update(visible=False)
287
 
288
+ key = get_key(selected_comp)
289
+ new_saved = [c for c in saved_data if get_key(c) != key]
290
  save_data(new_saved)
291
 
292
  target_list = new_saved if view_mode == "追蹤清單" else search_results
 
310
 
311
  # --- UI Layout ---
312
 
313
+ with gr.Blocks(title="Com.404 台企天眼通", theme=gr.themes.Soft()) as demo:
314
 
315
  saved_state = gr.State([])
316
  search_res_state = gr.State([])
317
+ selected_comp_state = gr.State(None)
318
 
319
+ # 🌟 Com.404 專屬 Header
320
  gr.Markdown("""
321
  <div align="center">
322
 
323
+ # 🏢 Com.404 - 台企天眼通 (Company Scout)
324
+
325
+ [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/DeepLearning101/Com.404) &nbsp;
326
+ [![GitHub](https://img.shields.io/badge/GitHub-Repo-black)](https://github.com/Deep-Learning-101/prof-404) &nbsp;
327
+ [![Powered by](https://img.shields.io/badge/Powered%20by-Gemini%202.0%20Flash-4285F4?logo=google)](https://deepmind.google/technologies/gemini/)
328
+
329
+ **查統編、看資本額、搜 PTT/Dcard 評價、掃描勞資糾紛,一鍵完成。**
330
+ <span style="font-size: 0.9em; color: gray;">(支援雲端同步!Space 重啟資料不遺失 🔄 | API KEY RPD,建議自行 Fork)</span>
331
+
332
  👉 歡迎 Star [GitHub](https://github.com/Deep-Learning-101/prof-404) ⭐ 覺得不錯 👈
333
+ </div>
334
+
335
+ ---
336
+
337
+ <div align="center">
338
  <h3>🧠 補腦專區:<a href="https://deep-learning-101.github.io/" target="_blank">Deep Learning 101</a></h3>
339
+ </div>
340
 
341
  | 🔥 技術傳送門 (Tech Stack) | 📚 必讀心法 (Must Read) |
342
  | :--- | :--- |
 
344
  | 📝 [**自然語言處理 (NLP)**](https://deep-learning-101.github.io/Natural-Language-Processing) | 📊 [**評測篇:臺灣 LLM 分析**](https://deep-learning-101.github.io/Blog/TW-LLM-Benchmark) |
345
  | 👁️ [**電腦視覺 (CV)**](https://deep-learning-101.github.io//Computer-Vision) | 🛠️ [**實戰篇:打造高精準 RAG**](https://deep-learning-101.github.io/RAG) |
346
  | 🎤 [**語音處理 (Speech)**](https://deep-learning-101.github.io/Speech-Processing) | 🕳️ [**避坑篇:AI Agent 開發陷阱**](https://deep-learning-101.github.io/agent) |
 
347
  """)
348
 
349
  with gr.Row():
350
+ search_input = gr.Textbox(label="輸入公司名稱或統編", placeholder="例如: 台積電, 2330, 八方雲集...", scale=4)
351
  search_btn = gr.Button("🔍 搜尋", variant="primary", scale=1)
352
 
353
  with gr.Row():
 
356
  with gr.Row():
357
  # Left: List
358
  with gr.Column(scale=1):
359
+ comp_df = gr.Dataframe(
360
+ headers=["狀態", "公司名稱", "產業類別", "標籤"],
361
+ datatype=["str", "str", "str", "str"],
362
  interactive=False,
363
+ label="公司列表 (點擊查看詳情)"
364
  )
365
  load_more_btn = gr.Button("載入更多", visible=False)
366
 
 
368
  with gr.Column(scale=2, visible=False) as details_col:
369
  detail_md = gr.Markdown("詳細資料...")
370
 
371
+ # 🌟 Chat Section (位於中間)
372
+ with gr.Column(elem_classes="chat-section"):
373
+ gr.Markdown("### 🤖 商業分析師 (已閱讀下方報告)")
374
+ chatbot = gr.Chatbot(height=250, type="messages")
375
+ with gr.Row():
376
+ msg = gr.Textbox(label="提問", placeholder="例如:這間公司有勞資糾紛嗎?薪資結構如何?", scale=4)
377
+ send_btn = gr.Button("送出", scale=1)
378
+
379
  gr.Markdown("---")
380
+
381
+ # Tags & Status
382
  with gr.Column(visible=False) as tags_row:
383
  tags_display = gr.Markdown("目前標籤: (無)")
384
  with gr.Row():
385
+ tag_input = gr.Textbox(label="新增標籤", placeholder="例如: 面試過, 薪水高...", scale=3)
386
  tag_add_btn = gr.Button("➕ 新增", scale=1)
387
 
388
  with gr.Accordion("刪除標籤", open=False):
389
  with gr.Row():
390
  tag_dropdown = gr.Dropdown(label="選擇標籤", choices=[], scale=3)
391
  tag_del_btn = gr.Button("🗑️ 刪除", scale=1, variant="secondary")
392
+
393
+ with gr.Row():
394
+ btn_good = gr.Button(" 優質")
395
+ btn_risk = gr.Button("⚠️ 風險")
396
+ btn_pending = gr.Button("❓ 未定")
397
+ btn_remove = gr.Button("🗑️ 移除", variant="stop")
398
 
399
  # --- Wiring ---
400
 
401
+ # Init
402
+ demo.load(init_on_load, inputs=None, outputs=[saved_state, comp_df])
403
 
404
+ # Search & Load More
405
  search_btn.click(
406
+ search_companies,
407
+ inputs=[search_input, saved_state],
408
+ outputs=[comp_df, search_res_state, load_more_btn]
409
  ).then(
410
  lambda: gr.update(value="搜尋結果"), outputs=[view_radio]
411
  )
412
 
413
  load_more_btn.click(
414
+ load_more,
415
+ inputs=[search_input, search_res_state, saved_state],
416
+ outputs=[comp_df, search_res_state]
417
  )
418
 
419
  view_radio.change(
420
+ toggle_view,
421
+ inputs=[view_radio, search_res_state, saved_state],
422
+ outputs=[comp_df, load_more_btn]
423
  )
424
 
425
+ # Selection
426
+ comp_df.select(
427
+ select_company,
428
+ inputs=[search_res_state, saved_state, view_radio],
429
  outputs=[
430
+ details_col, detail_md, chatbot, selected_comp_state, saved_state,
431
  tags_display, tag_dropdown, tags_row
432
  ]
433
  )
434
 
435
+ # Chat
436
+ send_btn.click(chat_response, inputs=[chatbot, msg, selected_comp_state], outputs=[chatbot, msg])
437
+ msg.submit(chat_response, inputs=[chatbot, msg, selected_comp_state], outputs=[chatbot, msg])
438
 
439
+ # Tags
440
  tag_add_btn.click(
441
+ add_tag,
442
+ inputs=[tag_input, selected_comp_state, saved_state, view_radio, search_res_state],
443
+ outputs=[tag_input, tags_display, tag_dropdown, saved_state, comp_df]
444
  )
 
445
  tag_del_btn.click(
446
+ remove_tag,
447
+ inputs=[tag_dropdown, selected_comp_state, saved_state, view_radio, search_res_state],
448
+ outputs=[tags_display, tag_dropdown, saved_state, comp_df]
449
  )
450
+
451
+ # Status & Remove
452
+ for btn, status in [(btn_good, 'good'), (btn_risk, 'risk'), (btn_pending, 'pending')]:
453
  btn.click(
454
+ update_status,
455
+ inputs=[gr.State(status), selected_comp_state, saved_state, view_radio, search_res_state],
456
+ outputs=[comp_df, saved_state]
457
  )
458
+
459
  btn_remove.click(
460
+ remove_comp,
461
+ inputs=[selected_comp_state, saved_state, view_radio, search_res_state],
462
+ outputs=[gr.State(None), comp_df, saved_state, details_col]
463
  )
464
 
465
  if __name__ == "__main__":