YSKang commited on
Commit
b8340a5
ยท
verified ยท
1 Parent(s): 824be21

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -52
app.py CHANGED
@@ -5,65 +5,106 @@ import uuid
5
  import os
6
  import tempfile
7
  import pymongo
 
8
  import certifi
9
  from bson.objectid import ObjectId
10
 
11
- # --- 1. DB ์„ค์ • ---
12
  MONGO_URI = os.environ.get("MONGO_URI")
 
13
 
14
- try:
15
- # ๐Ÿšจ ์ตœ์ข… ์ˆ˜์ •: ๊ฐ€์žฅ ๊ฐ•๋ ฅํ•œ ์šฐํšŒ ์„ค์ • ์กฐํ•ฉ
16
- client = pymongo.MongoClient(
17
- MONGO_URI,
18
- tls=True, # 1. ๋ณด์•ˆ ์—ฐ๊ฒฐ ํ•„์ˆ˜ (Atlas ์š”๊ตฌ์‚ฌํ•ญ)
19
- tlsAllowInvalidCertificates=True, # 2. ์ธ์ฆ์„œ ์˜ค๋ฅ˜ ๋ฌด์‹œ
20
- tlsAllowInvalidHostnames=True, # 3. ํ˜ธ์ŠคํŠธ ์ด๋ฆ„ ์˜ค๋ฅ˜ ๋ฌด์‹œ
21
- serverSelectionTimeoutMS=5000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  )
23
- # ์—ฐ๊ฒฐ ํ…Œ์ŠคํŠธ
24
- client.admin.command('ping')
25
- print("โœ… MongoDB ์—ฐ๊ฒฐ ์„ฑ๊ณต!")
26
- except Exception as e:
27
- print(f"โŒ MongoDB ์—ฐ๊ฒฐ ์‹คํŒจ: {e}")
28
- # ๋ฐฐํฌ ์‹œ ๋กœ๊ทธ ํ™•์ธ์„ ์œ„ํ•ด ์—๋Ÿฌ ์ถœ๋ ฅ
29
- import traceback
30
- traceback.print_exc()
31
-
32
- db = client.story_assistant_db
33
- interactions_col = db.interactions
34
- summaries_col = db.summaries
35
-
36
- # ... (๋‚˜๋จธ์ง€ ์ฝ”๋“œ๋Š” ๊ธฐ์กด๊ณผ ์™„๋ฒฝํžˆ ๋™์ผํ•ฉ๋‹ˆ๋‹ค) ...
37
- # ์•„๋ž˜๋Š” ๋ณต์‚ฌ ๋ถ™์—ฌ๋„ฃ๊ธฐ ํŽธ์˜๋ฅผ ์œ„ํ•ด ์ „์ฒด ์ฝ”๋“œ๋ฅผ ์œ ์ง€ํ•ฉ๋‹ˆ๋‹ค.
38
-
39
- # --- 2. DB ํ•จ์ˆ˜๋“ค ---
40
  def log_interaction(session_id, user_id, role, content):
41
- try:
42
- interaction = {
43
- "session_id": session_id, "user_id": user_id,
44
- "timestamp": datetime.datetime.now().isoformat(),
45
- "role": role, "content": content
46
- }
47
- interactions_col.insert_one(interaction)
48
- except Exception as e: print(f"DB Log Error: {e}")
 
 
 
 
 
 
49
 
50
  def log_summary(session_id, user_id, summary_text):
51
- try:
52
- summary = {
53
- "session_id": session_id, "user_id": user_id,
54
- "timestamp": datetime.datetime.now().isoformat(),
55
- "summary": summary_text
56
- }
57
- summaries_col.insert_one(summary)
58
- except Exception as e: print(f"DB Summary Error: {e}")
 
 
 
 
 
 
59
 
60
  def fetch_history(session_id):
61
- try:
62
- cursor = interactions_col.find({"session_id": session_id}).sort("timestamp", 1)
63
- return [(doc["role"], doc["content"], doc["timestamp"]) for doc in cursor]
64
- except Exception as e:
65
- print(f"DB Fetch Error: {e}")
66
- return []
 
 
 
 
 
 
 
 
67
 
68
  # --- 3. LLM API ์„ค์ • ---
69
  api_key = os.environ.get("GEMINI_API_KEY")
@@ -71,9 +112,7 @@ if not api_key:
71
  try:
72
  with open("api_key.txt", "r") as f: api_key = f.read().strip()
73
  except: pass
74
-
75
- if not api_key:
76
- print("โš ๏ธ GEMINI_API_KEY๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
77
 
78
  genai.configure(api_key=api_key)
79
 
@@ -81,7 +120,7 @@ try:
81
  with open("system_prompt.txt", "r", encoding="utf-8") as f: SYSTEM_PROMPT = f.read()
82
  except: SYSTEM_PROMPT = "๋‹น์‹ ์€ ์นœ์ ˆํ•œ ์ฑ—๋ด‡์ž…๋‹ˆ๋‹ค."
83
 
84
- # ๋ชจ๋ธ๋ช… ์žฌํ™•์ธ (gemini-1.5-flash ๊ถŒ์žฅ)
85
  model = genai.GenerativeModel(model_name='gemini-1.5-flash', system_instruction=SYSTEM_PROMPT)
86
 
87
  WELCOME_MESSAGE = (
@@ -184,6 +223,11 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
184
 
185
  with gr.Group(visible=False) as chat_view:
186
  gr.Markdown("# ๐Ÿ“ ์ด์•ผ๊ธฐ ๋น„์„œ (ํ”„๋กœํ† ํƒ€์ž…)")
 
 
 
 
 
187
  with gr.Row():
188
  with gr.Column(scale=3):
189
  chatbot = gr.Chatbot(
 
5
  import os
6
  import tempfile
7
  import pymongo
8
+ import sqlite3
9
  import certifi
10
  from bson.objectid import ObjectId
11
 
12
+ # --- 1. ํ•˜์ด๋ธŒ๋ฆฌ๋“œ DB ์„ค์ • ---
13
  MONGO_URI = os.environ.get("MONGO_URI")
14
+ USE_MONGO = False # ๊ธฐ๋ณธ๊ฐ’์€ False, ์—ฐ๊ฒฐ ์„ฑ๊ณต ์‹œ True๋กœ ๋ณ€๊ฒฝ
15
 
16
+ # 1-1. MongoDB ์—ฐ๊ฒฐ ์‹œ๋„
17
+ if MONGO_URI:
18
+ try:
19
+ print("๐Ÿ”Œ MongoDB ์—ฐ๊ฒฐ ์‹œ๋„ ์ค‘...")
20
+ client = pymongo.MongoClient(
21
+ MONGO_URI,
22
+ serverSelectionTimeoutMS=3000, # 3์ดˆ ๋‚ด ์‘๋‹ต ์—†์œผ๋ฉด ํฌ๊ธฐ
23
+ tls=True,
24
+ tlsAllowInvalidCertificates=True,
25
+ tlsAllowInvalidHostnames=True
26
+ )
27
+ client.admin.command('ping')
28
+ USE_MONGO = True
29
+ print("โœ… MongoDB ์—ฐ๊ฒฐ ์„ฑ๊ณต! (์›๊ฒฉ ์ €์žฅ์†Œ ์‚ฌ์šฉ)")
30
+ db = client.story_assistant_db
31
+ interactions_col = db.interactions
32
+ summaries_col = db.summaries
33
+ except Exception as e:
34
+ print(f"โš ๏ธ MongoDB ์—ฐ๊ฒฐ ์‹คํŒจ: {e}")
35
+ print("๐Ÿ”€ SQLite ๋กœ์ปฌ ์ €์žฅ์†Œ๋กœ ์ „ํ™˜ํ•ฉ๋‹ˆ๋‹ค.")
36
+ USE_MONGO = False
37
+ else:
38
+ print("โ„น๏ธ MONGO_URI๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. SQLite ๋กœ์ปฌ ์ €์žฅ์†Œ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.")
39
+
40
+ # 1-2. SQLite ์„ค์ • (MongoDB ์‹คํŒจ ์‹œ ๋ฐฑ์—…์šฉ)
41
+ if not USE_MONGO:
42
+ # Hugging Face Spaces์˜ ์˜๊ตฌ ์ €์žฅ์†Œ ๊ฒฝ๋กœ(/data)๊ฐ€ ์žˆ์œผ๋ฉด ๊ฑฐ๊ธฐ ์ €์žฅ, ์—†์œผ๋ฉด ์ผ๋ฐ˜ ํŒŒ์ผ
43
+ DB_PATH = os.path.join("/data", "logs.db") if os.path.exists("/data") else "logs.db"
44
+ print(f"๐Ÿ“‚ SQLite ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๊ฒฝ๋กœ: {DB_PATH}")
45
+
46
+ conn = sqlite3.connect(DB_PATH, check_same_thread=False)
47
+ cursor = conn.cursor()
48
+ cursor.execute('''
49
+ CREATE TABLE IF NOT EXISTS interactions (
50
+ session_id TEXT, user_id TEXT, timestamp TEXT, role TEXT, content TEXT
51
+ )
52
+ ''')
53
+ cursor.execute('''
54
+ CREATE TABLE IF NOT EXISTS summaries (
55
+ session_id TEXT, user_id TEXT, timestamp TEXT, summary TEXT
56
  )
57
+ ''')
58
+ conn.commit()
59
+
60
+ # --- 2. ํ†ตํ•ฉ DB ํ•จ์ˆ˜๋“ค (ํ•˜์ด๋ธŒ๋ฆฌ๋“œ) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  def log_interaction(session_id, user_id, role, content):
62
+ timestamp = datetime.datetime.now().isoformat()
63
+ if USE_MONGO:
64
+ try:
65
+ interactions_col.insert_one({
66
+ "session_id": session_id, "user_id": user_id,
67
+ "timestamp": timestamp, "role": role, "content": content
68
+ })
69
+ except Exception as e: print(f"DB Log Error (Mongo): {e}")
70
+ else:
71
+ try:
72
+ cursor.execute("INSERT INTO interactions VALUES (?, ?, ?, ?, ?)",
73
+ (session_id, user_id, timestamp, role, content))
74
+ conn.commit()
75
+ except Exception as e: print(f"DB Log Error (SQLite): {e}")
76
 
77
  def log_summary(session_id, user_id, summary_text):
78
+ timestamp = datetime.datetime.now().isoformat()
79
+ if USE_MONGO:
80
+ try:
81
+ summaries_col.insert_one({
82
+ "session_id": session_id, "user_id": user_id,
83
+ "timestamp": timestamp, "summary": summary_text
84
+ })
85
+ except Exception as e: print(f"DB Summary Error (Mongo): {e}")
86
+ else:
87
+ try:
88
+ cursor.execute("INSERT INTO summaries VALUES (?, ?, ?, ?)",
89
+ (session_id, user_id, timestamp, summary_text))
90
+ conn.commit()
91
+ except Exception as e: print(f"DB Summary Error (SQLite): {e}")
92
 
93
  def fetch_history(session_id):
94
+ if USE_MONGO:
95
+ try:
96
+ cursor_mongo = interactions_col.find({"session_id": session_id}).sort("timestamp", 1)
97
+ return [(doc["role"], doc["content"], doc["timestamp"]) for doc in cursor_mongo]
98
+ except Exception as e:
99
+ print(f"DB Fetch Error (Mongo): {e}")
100
+ return []
101
+ else:
102
+ try:
103
+ cursor.execute("SELECT role, content, timestamp FROM interactions WHERE session_id=? ORDER BY timestamp", (session_id,))
104
+ return cursor.fetchall()
105
+ except Exception as e:
106
+ print(f"DB Fetch Error (SQLite): {e}")
107
+ return []
108
 
109
  # --- 3. LLM API ์„ค์ • ---
110
  api_key = os.environ.get("GEMINI_API_KEY")
 
112
  try:
113
  with open("api_key.txt", "r") as f: api_key = f.read().strip()
114
  except: pass
115
+ if not api_key: print("โš ๏ธ GEMINI_API_KEY๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
 
 
116
 
117
  genai.configure(api_key=api_key)
118
 
 
120
  with open("system_prompt.txt", "r", encoding="utf-8") as f: SYSTEM_PROMPT = f.read()
121
  except: SYSTEM_PROMPT = "๋‹น์‹ ์€ ์นœ์ ˆํ•œ ์ฑ—๋ด‡์ž…๋‹ˆ๋‹ค."
122
 
123
+ # ๋ชจ๋ธ๋ช… ์žฌํ™•์ธ (gemini-1.5-flash)
124
  model = genai.GenerativeModel(model_name='gemini-1.5-flash', system_instruction=SYSTEM_PROMPT)
125
 
126
  WELCOME_MESSAGE = (
 
223
 
224
  with gr.Group(visible=False) as chat_view:
225
  gr.Markdown("# ๐Ÿ“ ์ด์•ผ๊ธฐ ๋น„์„œ (ํ”„๋กœํ† ํƒ€์ž…)")
226
+
227
+ # DB ์ƒํƒœ ํ‘œ์‹œ (๋””๋ฒ„๊น…์šฉ)
228
+ db_status = "๐ŸŸข MongoDB ์—ฐ๊ฒฐ๋จ" if USE_MONGO else "๐ŸŸ  SQLite ๋กœ์ปฌ ๋ชจ๋“œ (์ฃผ์˜: ์žฌ์‹œ์ž‘ ์‹œ ๋ฐ์ดํ„ฐ ์ดˆ๊ธฐํ™” ๊ฐ€๋Šฅ)"
229
+ gr.Markdown(f"โ„น๏ธ ์‹œ์Šคํ…œ ์ƒํƒœ: {db_status}")
230
+
231
  with gr.Row():
232
  with gr.Column(scale=3):
233
  chatbot = gr.Chatbot(