Spaces:
Runtime error
Runtime error
File size: 2,553 Bytes
9b574ca b4102fb 9b574ca b4102fb 9b574ca 11ece3a b4102fb 9b574ca a2e1bfa 9b574ca 2f49c14 9b574ca b4102fb 9b574ca 2f49c14 9b574ca 2f49c14 9b574ca 2f49c14 9b574ca 2f49c14 9b574ca 2f49c14 a2e1bfa 9b574ca a2e1bfa 9b574ca b4102fb 2f49c14 b4102fb 2f49c14 9b574ca | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | # 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())
|