flan-t5-chatbot / app.py
eclipse2's picture
Update app.py
9b574ca verified
Raw History Blame Contribute Delete
2.55 kB
# app.py โ€” Streamlit + Hugging Face InferenceClient (chat API, ์•ˆ์ „ ๋ชจ๋ธ ํด๋ฐฑ)
import os
import traceback
import streamlit as st
from huggingface_hub import InferenceClient
from huggingface_hub.errors import HfHubHTTPError
st.set_page_config(page_title="๊ฐ„๋‹จํ•œ ์ฑ—๋ด‡")
st.title("๋ญ๋“ ์ง€ ๋ฌผ์–ด๋ณด์„ธ์š”~")
# 1) ํ† ํฐ: ํ™˜๊ฒฝ๋ณ€์ˆ˜๋งŒ ์‚ฌ์šฉ (Spaces Secrets โ†’ ์ž๋™ ์ฃผ์ž…)
HF_TOKEN = os.environ.get("HUGGINGFACEHUB_API_TOKEN") or os.environ.get("HF_TOKEN")
if not HF_TOKEN:
st.error("Hugging Face ํ† ํฐ์ด ์—†์Šต๋‹ˆ๋‹ค. HUGGINGFACEHUB_API_TOKEN=hf_xxx ๋ฅผ ์„ค์ •ํ•˜์„ธ์š”.")
st.stop()
# 2) ์ฑ„ํŒ…์ด ์ž˜ ๋ถ™๋Š” ๊ฒฝ๋Ÿ‰ ๋ชจ๋ธ ํ›„๋ณด (ํ”„๋กœ๋ฐ”์ด๋” ํ˜ธํ™˜์„ฑโ†‘ ์ˆœ์œผ๋กœ ๋‚˜์—ด)
# ํ•„์š”์‹œ HF_MODEL ํ™˜๊ฒฝ๋ณ€์ˆ˜๋กœ ์ฒซ ํ›„๋ณด๋ฅผ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
DEFAULT_CANDIDATES = [
os.environ.get("HF_MODEL", "Qwen/Qwen2.5-0.5B-Instruct"),
"TinyLlama/TinyLlama-1.1B-Chat-v1.0",
"Qwen/Qwen2.5-1.5B-Instruct",
"google/gemma-2-2b-it",
]
# 3) ํด๋ผ์ด์–ธํŠธ (๋ชจ๋ธ ๋ฏธ์ง€์ •) โ€” ํ˜ธ์ถœ ์‹œ model=... ์ „๋‹ฌ
client = InferenceClient(token=HF_TOKEN)
def chat_once(model_id: str, prompt: str) -> str:
"""chat-completions ์šฐ์„ . ์‹คํŒจ ์‹œ ์˜ˆ์™ธ."""
res = client.chat.completions.create(
model=model_id,
messages=[{"role": "user", "content": prompt}],
max_tokens=200,
temperature=0.7,
top_p=0.9,
)
try:
return res.choices[0].message.content
except Exception:
return str(res)
def generate_response(prompt: str) -> str:
errors = []
for mid in DEFAULT_CANDIDATES:
try:
out = chat_once(mid, prompt)
if mid != DEFAULT_CANDIDATES[0]:
st.info(f"(์ž๋™ ํด๋ฐฑ ๋ชจ๋ธ ์‚ฌ์šฉ: {mid})")
return out
except Exception as e:
errors.append(f"{mid}: {e}")
continue
# ๋ชจ๋“  ํ›„๋ณด ์‹คํŒจ ์‹œ ์ƒ์„ธ ๋กœ๊ทธ ๋…ธ์ถœ
raise RuntimeError("๋ชจ๋“  ๋ชจ๋ธ ์‹œ๋„๊ฐ€ ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค:\n" + "\n".join(errors))
with st.form("Question"):
text = st.text_area("์งˆ๋ฌธ์„ ์ž…๋ ฅํ•˜์„ธ์š”:")
submitted = st.form_submit_button("์ „์†ก")
if submitted and text.strip():
try:
answer = generate_response(text.strip())
st.success(answer)
except HfHubHTTPError as e:
st.error(f"Hugging Face API ์˜ค๋ฅ˜: {e}")
st.code(traceback.format_exc())
except Exception:
st.error("์š”์ฒญ ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.")
st.code(traceback.format_exc())