peterpeter8585 commited on
Commit
cc8a692
Β·
verified Β·
1 Parent(s): f4d296a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -63
app.py CHANGED
@@ -388,52 +388,47 @@ def summarize_title(history):
388
  except Exception:
389
  return "μš”μ•½ μ‹€νŒ¨"
390
 
391
- def save_conversation(username, history):
392
- os.makedirs("user_logs", exist_ok=True)
393
- if not history: return
 
 
 
 
 
 
 
 
394
  title = summarize_title(history)
395
- fname = f"user_logs/{username}_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
396
- with open(fname, "w", encoding="utf-8") as f:
397
- json.dump({"title": title, "history": history}, f, ensure_ascii=False, indent=2)
 
 
 
 
 
 
 
 
398
 
399
  def list_conversations(username):
400
- os.makedirs("user_logs", exist_ok=True)
401
- files = [f for f in os.listdir("user_logs") if f.startswith(username)]
402
- data = []
403
  for f in files:
404
- with open(os.path.join("user_logs", f), encoding="utf-8") as jf:
405
- info = json.load(jf)
406
- data.append((info.get("title", f), f))
407
- return data
408
-
409
- def load_conversation(file):
410
- with open(os.path.join("user_logs", file), encoding="utf-8") as jf:
411
- return json.load(jf)["history"]
412
 
413
- # ──────────────────────────────
414
- # βœ… 둜그인 ν›„ μ‚¬μš©μž 정보 κ°€μ Έμ˜€κΈ°
415
- # ──────────────────────────────
416
- def get_hf_user(token):
417
- """HF OAuth ν† ν°μœΌλ‘œ μ‚¬μš©μž 정보 쑰회"""
418
  try:
419
- r = requests.get("https://huggingface.co/api/whoami-v2", headers={"Authorization": f"Bearer {token}"})
420
- if r.status_code == 200:
421
- data = r.json()
422
- return data.get("name") or data.get("email") or "unknown_user"
423
- except Exception:
424
- pass
425
- return "guest"
426
- import re, json
427
-
428
- def chat(message, history,username="default_user"):
429
- try:
430
- # μ‹œμŠ€ν…œ λ©”μ‹œμ§€ 포함 ν”„λ‘¬ν”„νŠΈ ꡬ성
431
- prompt=message
432
-
433
- raw_response = agent.run(prompt)
434
  text = str(raw_response)
435
 
436
- # βœ… JSON ν˜•νƒœλ‘œ 응닡 μ‹œ νŒŒμ‹±
437
  output = text
438
  match = re.search(r"\{.*\}", text, re.DOTALL)
439
  if match:
@@ -448,17 +443,38 @@ def chat(message, history,username="default_user"):
448
  )
449
  except Exception:
450
  output = text
451
-
452
  except Exception as e:
453
  output = f"⚠️ 였λ₯˜: {e}"
454
 
455
- # βœ… Gradio용 μ±„νŒ… ν˜•μ‹ μ—…λ°μ΄νŠΈ
456
  history = history + [(message, output)]
457
- os.makedirs("user_logs", exist_ok=True)
458
- file_path = os.path.join("user_logs", f"{username}_current.json")
459
- with open(file_path, "w", encoding="utf-8") as f:
460
- json.dump({"history": history}, f, ensure_ascii=False, indent=2)
461
  return history, history, ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
462
  '''
463
  def chat(message, history, hf_token):
464
  username = get_hf_user(hf_token) if hf_token else "guest"
@@ -496,25 +512,32 @@ def chat(message, history, hf_token):
496
  return history, history, "" # μž…λ ₯ μ΄ˆκΈ°ν™”
497
  '''
498
  # 예: hf_token (ν˜Ήμ€ username) 을 μž…λ ₯으둜 받도둝 λ³€κ²½
499
- def refresh_conversation_list(*_):
500
- """λŒ€ν™” λͺ©λ‘μ„ μƒˆλ‘œκ³ μΉ¨ (Gradio 호좜 λŒ€μ‘)"""
501
- if not os.path.exists("user_logs"):
502
- return gr.Dropdown.update(choices=[], value=None)
503
- files = sorted(os.listdir("user_logs"), reverse=True)
504
- titles = [f.replace(".json", "") for f in files]
505
- return gr.Dropdown.update(choices=titles, value=titles[0] if titles else None)
506
- def load_selected(file):
507
- """μ„ νƒλœ λŒ€ν™”λ₯Ό λΆˆλŸ¬μ™€ μ΄μ–΄μ„œ λŒ€ν™”"""
508
- path = os.path.join("user_logs", file)
509
- if not os.path.exists(path):
510
- return []
511
- with open(path, "r", encoding="utf-8") as f:
512
- data = json.load(f)
513
- return data.get("history", [])
514
-
515
-
516
-
517
-
 
 
 
 
 
 
 
518
 
519
 
520
 
 
388
  except Exception:
389
  return "μš”μ•½ μ‹€νŒ¨"
390
 
391
+ import pickle
392
+ import os, datetime
393
+
394
+ # ν˜„μž¬ λ””λ ‰ν„°λ¦¬λ‘œ κ³ μ •
395
+ os.chdir(os.path.dirname(os.path.abspath(__file__)))
396
+ os.makedirs("user_logs", exist_ok=True)
397
+
398
+ # --- λŒ€ν™” 기둝 μ €μž₯/뢈러였기 ---
399
+ def save_conversation(username, history, conv_name="current"):
400
+ """κ³„μ •λ³„λ‘œ λŒ€ν™”κΈ°λ‘μ„ pickle둜 μ‹€μ‹œκ°„ μ €μž₯"""
401
+ os.makedirs(f"user_logs/{username}", exist_ok=True)
402
  title = summarize_title(history)
403
+ fname = f"user_logs/{username}/{conv_name}.pkl"
404
+ with open(fname, "wb") as f:
405
+ pickle.dump({"title": title, "history": history}, f)
406
+
407
+ def load_conversation(username, conv_name="current"):
408
+ path = f"user_logs/{username}/{conv_name}.pkl"
409
+ if not os.path.exists(path):
410
+ return []
411
+ with open(path, "rb") as f:
412
+ data = pickle.load(f)
413
+ return data.get("history", [])
414
 
415
  def list_conversations(username):
416
+ os.makedirs(f"user_logs/{username}", exist_ok=True)
417
+ files = [f for f in os.listdir(f"user_logs/{username}") if f.endswith(".pkl")]
418
+ titles = []
419
  for f in files:
420
+ with open(f"user_logs/{username}/" + f, "rb") as fp:
421
+ data = pickle.load(fp)
422
+ titles.append((data.get("title", f), f))
423
+ return titles
 
 
 
 
424
 
425
+ # --- chat ν•¨μˆ˜ μˆ˜μ • ---
426
+ def chat(message, history, username="guest", conv_name="current"):
 
 
 
427
  try:
428
+ raw_response = agent.run(message)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  text = str(raw_response)
430
 
431
+ # JSON ν˜•μ‹ 응닡 νŒŒμ‹±
432
  output = text
433
  match = re.search(r"\{.*\}", text, re.DOTALL)
434
  if match:
 
443
  )
444
  except Exception:
445
  output = text
 
446
  except Exception as e:
447
  output = f"⚠️ 였λ₯˜: {e}"
448
 
449
+ # 기둝 μΆ”κ°€ 및 μ¦‰μ‹œ μ €μž₯
450
  history = history + [(message, output)]
451
+ save_conversation(username, history, conv_name)
 
 
 
452
  return history, history, ""
453
+
454
+ # --- 뢈러였기 λ²„νŠΌ ν•¨μˆ˜ ---
455
+ def load_selected(username, file):
456
+ path = f"user_logs/{username}/{file}"
457
+ if not os.path.exists(path):
458
+ return []
459
+ with open(path, "rb") as f:
460
+ data = pickle.load(f)
461
+ return data.get("history", [])
462
+ # ──────────────────────────────
463
+ # βœ… 둜그인 ν›„ μ‚¬μš©μž 정보 κ°€μ Έμ˜€κΈ°
464
+ # ──────────────────────────────
465
+ def get_hf_user(token):
466
+ """HF OAuth ν† ν°μœΌλ‘œ μ‚¬μš©μž 정보 쑰회"""
467
+ try:
468
+ r = requests.get("https://huggingface.co/api/whoami-v2", headers={"Authorization": f"Bearer {token}"})
469
+ if r.status_code == 200:
470
+ data = r.json()
471
+ return data.get("name") or data.get("email") or "unknown_user"
472
+ except Exception:
473
+ pass
474
+ return "guest"
475
+ import re, json
476
+
477
+
478
  '''
479
  def chat(message, history, hf_token):
480
  username = get_hf_user(hf_token) if hf_token else "guest"
 
512
  return history, history, "" # μž…λ ₯ μ΄ˆκΈ°ν™”
513
  '''
514
  # 예: hf_token (ν˜Ήμ€ username) 을 μž…λ ₯으둜 받도둝 λ³€κ²½
515
+ def refresh_conversation_list(username="guest"):
516
+ """계정별 λŒ€ν™” λͺ©λ‘μ„ μƒˆλ‘œκ³ μΉ¨ (Gradio Dropdown μ—…λ°μ΄νŠΈμš©)"""
517
+ base_dir = os.path.join("user_logs", username)
518
+ os.makedirs(base_dir, exist_ok=True)
519
+
520
+ files = sorted(
521
+ [f for f in os.listdir(base_dir) if f.endswith(".pkl")],
522
+ reverse=True
523
+ )
524
+
525
+ # 제λͺ© λͺ©λ‘ λ§Œλ“€κΈ°
526
+ titles = []
527
+ for f in files:
528
+ try:
529
+ with open(os.path.join(base_dir, f), "rb") as fp:
530
+ data = pickle.load(fp)
531
+ title = data.get("title", f.replace(".pkl", ""))
532
+ except Exception:
533
+ title = f.replace(".pkl", "")
534
+ titles.append(title)
535
+
536
+ # Dropdown μ—…λ°μ΄νŠΈ
537
+ if titles:
538
+ return gr.update(choices=titles, value=titles[0])
539
+ else:
540
+ return gr.update(choices=[], value=None)
541
 
542
 
543