YSKang's picture
Upload app.py
c6de08d verified
import gradio as gr
import google.generativeai as genai
import datetime
import uuid
import os
import tempfile
import pymongo
import sqlite3
import certifi
from bson.objectid import ObjectId
# --- 1. ํ•˜์ด๋ธŒ๋ฆฌ๋“œ DB ์„ค์ • ---
MONGO_URI = os.environ.get("MONGO_URI")
USE_MONGO = False # ๊ธฐ๋ณธ๊ฐ’์€ False, ์—ฐ๊ฒฐ ์„ฑ๊ณต ์‹œ True๋กœ ๋ณ€๊ฒฝ
# 1-1. MongoDB ์—ฐ๊ฒฐ ์‹œ๋„
if MONGO_URI:
try:
print("๐Ÿ”Œ MongoDB ์—ฐ๊ฒฐ ์‹œ๋„ ์ค‘...")
client = pymongo.MongoClient(
MONGO_URI,
serverSelectionTimeoutMS=3000, # 3์ดˆ ๋‚ด ์‘๋‹ต ์—†์œผ๋ฉด ํฌ๊ธฐ
tls=True,
tlsAllowInvalidCertificates=True,
tlsAllowInvalidHostnames=True
)
client.admin.command('ping')
USE_MONGO = True
print("โœ… MongoDB ์—ฐ๊ฒฐ ์„ฑ๊ณต! (์›๊ฒฉ ์ €์žฅ์†Œ ์‚ฌ์šฉ)")
db = client.story_assistant_db
interactions_col = db.interactions
summaries_col = db.summaries
except Exception as e:
print(f"โš ๏ธ MongoDB ์—ฐ๊ฒฐ ์‹คํŒจ: {e}")
print("๐Ÿ”€ SQLite ๋กœ์ปฌ ์ €์žฅ์†Œ๋กœ ์ „ํ™˜ํ•ฉ๋‹ˆ๋‹ค.")
USE_MONGO = False
else:
print("โ„น๏ธ MONGO_URI๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค. SQLite ๋กœ์ปฌ ์ €์žฅ์†Œ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.")
# 1-2. SQLite ์„ค์ • (MongoDB ์‹คํŒจ ์‹œ ๋ฐฑ์—…์šฉ)
if not USE_MONGO:
# Hugging Face Spaces์˜ ์˜๊ตฌ ์ €์žฅ์†Œ ๊ฒฝ๋กœ(/data)๊ฐ€ ์žˆ์œผ๋ฉด ๊ฑฐ๊ธฐ ์ €์žฅ, ์—†์œผ๋ฉด ์ผ๋ฐ˜ ํŒŒ์ผ
DB_PATH = os.path.join("/data", "logs.db") if os.path.exists("/data") else "logs.db"
print(f"๐Ÿ“‚ SQLite ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๊ฒฝ๋กœ: {DB_PATH}")
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS interactions (
session_id TEXT, user_id TEXT, timestamp TEXT, role TEXT, content TEXT
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS summaries (
session_id TEXT, user_id TEXT, timestamp TEXT, summary TEXT
)
''')
conn.commit()
# --- 2. ํ†ตํ•ฉ DB ํ•จ์ˆ˜๋“ค (ํ•˜์ด๋ธŒ๋ฆฌ๋“œ) ---
def log_interaction(session_id, user_id, role, content):
timestamp = datetime.datetime.now().isoformat()
if USE_MONGO:
try:
interactions_col.insert_one({
"session_id": session_id, "user_id": user_id,
"timestamp": timestamp, "role": role, "content": content
})
except Exception as e: print(f"DB Log Error (Mongo): {e}")
else:
try:
cursor.execute("INSERT INTO interactions VALUES (?, ?, ?, ?, ?)",
(session_id, user_id, timestamp, role, content))
conn.commit()
except Exception as e: print(f"DB Log Error (SQLite): {e}")
def log_summary(session_id, user_id, summary_text):
timestamp = datetime.datetime.now().isoformat()
if USE_MONGO:
try:
summaries_col.insert_one({
"session_id": session_id, "user_id": user_id,
"timestamp": timestamp, "summary": summary_text
})
except Exception as e: print(f"DB Summary Error (Mongo): {e}")
else:
try:
cursor.execute("INSERT INTO summaries VALUES (?, ?, ?, ?)",
(session_id, user_id, timestamp, summary_text))
conn.commit()
except Exception as e: print(f"DB Summary Error (SQLite): {e}")
def fetch_history(session_id):
if USE_MONGO:
try:
cursor_mongo = interactions_col.find({"session_id": session_id}).sort("timestamp", 1)
return [(doc["role"], doc["content"], doc["timestamp"]) for doc in cursor_mongo]
except Exception as e:
print(f"DB Fetch Error (Mongo): {e}")
return []
else:
try:
cursor.execute("SELECT role, content, timestamp FROM interactions WHERE session_id=? ORDER BY timestamp", (session_id,))
return cursor.fetchall()
except Exception as e:
print(f"DB Fetch Error (SQLite): {e}")
return []
# --- 3. LLM API ์„ค์ • ---
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
try:
with open("api_key.txt", "r") as f: api_key = f.read().strip()
except: pass
if not api_key: print("โš ๏ธ GEMINI_API_KEY๊ฐ€ ์„ค์ •๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค.")
genai.configure(api_key=api_key)
try:
with open("system_prompt.txt", "r", encoding="utf-8") as f: SYSTEM_PROMPT = f.read()
except: SYSTEM_PROMPT = "๋‹น์‹ ์€ ์นœ์ ˆํ•œ ์ฑ—๋ด‡์ž…๋‹ˆ๋‹ค."
# ๋ชจ๋ธ๋ช… ์žฌํ™•์ธ (gemini-1.5-flash)
model = genai.GenerativeModel(model_name='gemini-2.5-flash', system_instruction=SYSTEM_PROMPT)
WELCOME_MESSAGE = (
"์•ˆ๋…•ํ•˜์„ธ์š”, ์„ ์ƒ๋‹˜. '์ด์•ผ๊ธฐ ๋น„์„œ'์ž…๋‹ˆ๋‹ค.\n"
"์˜ค๋Š˜ ์ž์„œ์ „์˜ ์ฒซ ์ฑ•ํ„ฐ๋ฅผ ์œ„ํ•ด, **๊ฐ€์žฅ ๋จผ์ € ๋– ์˜ค๋ฅด๋Š” ์ด์•ผ๊ธฐ**๋ฅผ ๋“ค๋ ค์ฃผ์‹œ๊ฒ ์–ด์š”?\n\n"
"1. **์œ ๋…„ ์‹œ์ ˆ**์˜ ์ถ”์–ต\n2. ์ธ์ƒ **์ตœ๊ณ ์˜ ์Œ์‹**\n3. **์ฒซ ์ง์žฅ**์˜ ๊ธฐ์–ต\n4. **๋ฐฐ์šฐ์ž**์™€์˜ ์ฒซ ๋งŒ๋‚จ\n\n"
"์œ„ ์ฃผ์ œ ์ค‘ ํ•˜๋‚˜๋ฅผ ๊ณจ๋ผ์ฃผ์‹œ๊ฑฐ๋‚˜, ํŽธํ•˜๊ฒŒ ๋‹ค๋ฅธ ๋ง์”€์„ ํ•ด์ฃผ์…”๋„ ์ข‹์Šต๋‹ˆ๋‹ค."
)
# --- 4. ํ•ต์‹ฌ ๋กœ์ง ---
def format_history_for_llm(history):
llm_history = []
for msg in history:
if msg['role'] == 'user':
llm_history.append({"role": "user", "parts": [{"text": msg['content']}]})
elif msg['role'] == 'assistant':
llm_history.append({"role": "model", "parts": [{"text": msg['content']}]})
return llm_history
def chat(user_input, history, session_id, user_id):
if not user_input.strip(): return "", history
history.append({"role": "user", "content": user_input})
log_interaction(session_id, user_id, 'user', user_input)
yield "", history
llm_history = format_history_for_llm(history[:-1])
chat_session = model.start_chat(history=llm_history)
try:
response = chat_session.send_message(user_input, stream=True)
full_response = ""
history.append({"role": "assistant", "content": ""})
for chunk in response:
full_response += chunk.text
history[-1]['content'] = full_response
yield "", history
log_interaction(session_id, user_id, 'model', full_response)
except Exception as e:
history.append({"role": "assistant", "content": f"โš ๏ธ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"})
yield "", history
def change_topic(history, session_id, user_id):
if not history: return history
llm_history = format_history_for_llm(history)
chat_session = model.start_chat(history=llm_history)
summary_prompt = (
"์ง€๊ธˆ๊นŒ์ง€ ๋‚˜๋ˆˆ ๋Œ€ํ™” ๋‚ด์šฉ์„ '์„ ์ƒ๋‹˜์€ ~ ๊ฒฝํ—˜์„ ํ•˜์…จ์Šต๋‹ˆ๋‹ค'์™€ ๊ฐ™์€ ๋ฌธ์ฒด๋กœ "
"3๋ฌธ์žฅ ์ด๋‚ด๋กœ ๊ฐ„๋žตํ•˜๊ฒŒ ์š”์•ฝํ•ด์ค˜. ์ด ์š”์•ฝ์€ ๊ธฐ๋ก์„ ์œ„ํ•œ ๊ฒƒ์ด์•ผ."
)
try:
response = chat_session.send_message(summary_prompt)
summary_text = response.text
log_summary(session_id, user_id, summary_text)
end_message = f"\n\n[๊ธฐ๋ก ์™„๋ฃŒ] ์ง€๊ธˆ๊นŒ์ง€์˜ ์ด์•ผ๊ธฐ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ž˜ ๊ธฐ๋กํ•ด ๋‘์—ˆ์Šต๋‹ˆ๋‹ค.\n\n๐Ÿ“ **์š”์•ฝ:** {summary_text}\n\n์ž, ๊ทธ๋Ÿผ ์ด์ œ ๋‹ค๋ฅธ ์ฃผ์ œ๋กœ ๋„˜์–ด๊ฐ€ ๋ณผ๊นŒ์š”? ์–ด๋–ค ์ด์•ผ๊ธฐ๋ฅผ ๋” ๋“ค๋ ค์ฃผ์‹œ๊ฒ ์–ด์š”?"
history.append({"role": "assistant", "content": end_message})
return history
except Exception as e:
history.append({"role": "assistant", "content": f"โš ๏ธ ์š”์•ฝ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"})
return history
def export_chat_txt(session_id):
data = fetch_history(session_id)
if not data: return None
text_content = f"์ž์„œ์ „ ์ธํ„ฐ๋ทฐ ๊ธฐ๋ก (Session: {session_id})\n์ €์žฅ ์ผ์‹œ: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n" + "=" * 50 + "\n\n"
for role, content, timestamp in data:
speaker = "์„ ์ƒ๋‹˜" if role == 'user' else "์ด์•ผ๊ธฐ ๋น„์„œ"
text_content += f"[{timestamp.split('T')[1][:5]}] {speaker}:\n{content}\n\n" + "-" * 20 + "\n\n"
fd, path = tempfile.mkstemp(suffix=".txt", prefix=f"interview_{session_id[:8]}_")
with os.fdopen(fd, 'w', encoding='utf-8') as f: f.write(text_content)
return path
def export_chat_md(session_id):
data = fetch_history(session_id)
if not data: return None
md_content = f"# ๐Ÿ“œ ์ž์„œ์ „ ์ธํ„ฐ๋ทฐ ๊ธฐ๋ก\n\n> **์„ธ์…˜ ID:** `{session_id}`<br>**์ €์žฅ ์ผ์‹œ:** {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n---\n\n"
for role, content, timestamp in data:
speaker = "๐Ÿง‘โ€๐Ÿซ ์„ ์ƒ๋‹˜" if role == 'user' else "๐Ÿค– ์ด์•ผ๊ธฐ ๋น„์„œ"
md_content += f"### {speaker} <span style='color:gray;font-size:0.8em'>({timestamp.split('T')[1][:5]})</span>\n\n{content}\n\n"
fd, path = tempfile.mkstemp(suffix=".md", prefix=f"interview_{session_id[:8]}_")
with os.fdopen(fd, 'w', encoding='utf-8') as f: f.write(md_content)
return path
# --- 5. UI ๊ตฌ์„ฑ ---
def start_chat(user_id_val):
if not user_id_val.strip():
return gr.update(visible=True), gr.update(visible=False), "โš ๏ธ ํ…Œ์Šคํ„ฐ ID๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”!"
return gr.update(visible=False), gr.update(visible=True), ""
with gr.Blocks(theme=gr.themes.Soft()) as demo:
session_id = gr.State(lambda: str(uuid.uuid4()))
user_id = gr.State("")
with gr.Group(visible=True) as login_view:
gr.Markdown("# ๐Ÿ‘‹ ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค! ์ด์•ผ๊ธฐ ๋น„์„œ ํ…Œ์ŠคํŠธ๋ฅผ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.")
gr.Markdown("์›ํ™œํ•œ ๊ธฐ๋ก์„ ์œ„ํ•ด ํ…Œ์Šคํ„ฐ ID(๋‹‰๋„ค์ž„)๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”.")
with gr.Row():
login_id_input = gr.Textbox(label="ํ…Œ์Šคํ„ฐ ID", placeholder="์˜ˆ: tester_hong, ํ–‰๋ณตํ•œํ•˜๋ฃจ", scale=3, autofocus=True)
login_btn = gr.Button("๐Ÿš€ ์‹œ์ž‘ํ•˜๊ธฐ", variant="primary", scale=1)
login_msg = gr.Markdown("", visible=True)
with gr.Group(visible=False) as chat_view:
gr.Markdown("# ๐Ÿ“ ์ด์•ผ๊ธฐ ๋น„์„œ (ํ”„๋กœํ† ํƒ€์ž…)")
# DB ์ƒํƒœ ํ‘œ์‹œ (๋””๋ฒ„๊น…์šฉ)
db_status = "๐ŸŸข MongoDB ์—ฐ๊ฒฐ๋จ" if USE_MONGO else "๐ŸŸ  SQLite ๋กœ์ปฌ ๋ชจ๋“œ (์ฃผ์˜: ์žฌ์‹œ์ž‘ ์‹œ ๋ฐ์ดํ„ฐ ์ดˆ๊ธฐํ™” ๊ฐ€๋Šฅ)"
gr.Markdown(f"โ„น๏ธ ์‹œ์Šคํ…œ ์ƒํƒœ: {db_status}")
with gr.Row():
with gr.Column(scale=3):
chatbot = gr.Chatbot(
value=[{"role": "assistant", "content": WELCOME_MESSAGE}],
height=650,
label="๋Œ€ํ™”์ฐฝ",
type="messages",
avatar_images=(None, "https://i.ibb.co/ZHrkBPm/ai-assistant.png")
)
with gr.Row():
msg_input = gr.Textbox(scale=4, show_label=False, placeholder="์—ฌ๊ธฐ์— ์ด์•ผ๊ธฐ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”...", container=False)
submit_btn = gr.Button("์ „์†ก", scale=1, variant="primary")
with gr.Row():
topic_change_btn = gr.Button("๐Ÿ”„ ์ด ์ฃผ์ œ ๋งˆ๋ฌด๋ฆฌํ•˜๊ณ  ๋‹ค๋ฅธ ์ด์•ผ๊ธฐ ํ•˜๊ธฐ", variant="secondary", scale=1)
with gr.Column(scale=1):
gr.Markdown("### ๐Ÿ› ๏ธ ํ…Œ์Šคํ„ฐ ์ •๋ณด")
user_id_display = gr.Textbox(label="ํ˜„์žฌ ์ ‘์† ID", interactive=False)
gr.Markdown("### ๐Ÿ’ก ์‚ฌ์šฉ ๊ฐ€์ด๋“œ")
gr.Markdown("- **์ด์•ผ๊ธฐ ์‹œ์ž‘:** ๋ด‡์˜ ์งˆ๋ฌธ์— ํŽธํ•˜๊ฒŒ ๋‹ตํ•ด์ฃผ์„ธ์š”.\n- **์ฃผ์ œ ๋ณ€๊ฒฝ:** ์ฑ„ํŒ…์ฐฝ ์•„๋ž˜ **'๐Ÿ”„ ์ด ์ฃผ์ œ ๋งˆ๋ฌด๋ฆฌ...'** ๋ฒ„ํŠผ์„ ๋ˆŒ๋Ÿฌ์ฃผ์„ธ์š”.")
gr.Markdown("### ๐Ÿ’พ ๋Œ€ํ™” ๋‚ด์šฉ ๋‚ด๋ณด๋‚ด๊ธฐ")
with gr.Row():
export_txt_btn = gr.Button("๐Ÿ“„ TXT")
export_md_btn = gr.Button("๐Ÿ“ MD")
download_file = gr.File(label="๋‹ค์šด๋กœ๋“œ", interactive=False, height=100)
login_btn.click(start_chat, inputs=[login_id_input], outputs=[login_view, chat_view, login_msg]).then(
lambda id_val: (id_val, id_val), inputs=[login_id_input], outputs=[user_id, user_id_display]
)
login_id_input.submit(start_chat, inputs=[login_id_input], outputs=[login_view, chat_view, login_msg]).then(
lambda id_val: (id_val, id_val), inputs=[login_id_input], outputs=[user_id, user_id_display]
)
msg_input.submit(chat, [msg_input, chatbot, session_id, user_id], [msg_input, chatbot])
submit_btn.click(chat, [msg_input, chatbot, session_id, user_id], [msg_input, chatbot])
topic_change_btn.click(change_topic, [chatbot, session_id, user_id], [chatbot])
export_txt_btn.click(export_chat_txt, inputs=[session_id], outputs=[download_file])
export_md_btn.click(export_chat_md, inputs=[session_id], outputs=[download_file])
# --- 6. ์•ฑ ์‹คํ–‰ ---
app_password = os.environ.get("APP_PASSWORD")
if __name__ == "__main__":
launch_kwargs = {
"server_name": "0.0.0.0",
"server_port": 7860,
"ssr_mode": False
}
if app_password:
launch_kwargs["auth"] = ("team", app_password)
print(f"๐Ÿš€ Launching Gradio with settings: {launch_kwargs}")
demo.launch(**launch_kwargs)