eclipse2 commited on
Commit
a2e1bfa
Β·
verified Β·
1 Parent(s): 1b36bf1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -16
app.py CHANGED
@@ -1,5 +1,4 @@
1
- # app.py β€” Streamlit + InferenceClient (fixed model, env token)
2
-
3
  import os
4
  import traceback
5
  import streamlit as st
@@ -14,40 +13,95 @@ except Exception:
14
  pass
15
 
16
  st.set_page_config(page_title="κ°„λ‹¨ν•œ 챗봇")
17
- st.title("뭐든지 λ¬Όμ–΄λ³΄μ„Έμš”")
18
 
19
- # ── 토큰은 ν™˜κ²½λ³€μˆ˜λ§Œ μ‚¬μš© (Spaces Secrets 포함)
20
  token = os.environ.get("HUGGINGFACEHUB_API_TOKEN") or os.environ.get("HF_TOKEN")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  if not token:
22
- st.error("Hugging Face 토큰이 μ—†μŠ΅λ‹ˆλ‹€. ν™˜κ²½λ³€μˆ˜(HUGGINGFACEHUB_API_TOKEN)λ₯Ό μ„€μ •ν•˜μ„Έμš”.")
23
  st.stop()
24
 
25
- # ── text-generation μ§€μ›λ˜λŠ” causal LM으둜 'κ³ μ •'
26
- MODEL_ID = "HuggingFaceH4/zephyr-7b-beta"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- client = InferenceClient(token=token) # λͺ¨λΈ λ―Έμ§€μ •μœΌλ‘œ 생성
 
29
 
30
- def generate_response(text: str) -> str:
31
  try:
32
- return client.text_generation(
33
- text,
34
- model=MODEL_ID, # ← 호좜 μ‹œ λͺ¨λΈ μ§€μ • (κ³ μ •)
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  max_new_tokens=200,
36
  temperature=0.7,
37
  top_p=0.9,
38
  )
39
- except HfHubHTTPError as e:
40
- raise RuntimeError(f"Hugging Face API 였λ₯˜: {e}") from e
41
  except Exception as e:
42
- raise RuntimeError(f"μ˜ˆμ™Έ λ°œμƒ: {e}") from e
 
 
43
 
44
  with st.form("Question"):
45
  user_input = st.text_area("μ§ˆλ¬Έμ„ μž…λ ₯ν•˜μ„Έμš”:")
46
  submitted = st.form_submit_button("전솑")
47
  if submitted and user_input.strip():
48
  try:
49
- out = generate_response(user_input.strip())
50
  st.success(out)
 
 
 
51
  except Exception:
52
  st.error("μš”μ²­ 처리 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.")
53
  st.code(traceback.format_exc())
 
1
+ # app.py β€” Streamlit + Hugging Face InferenceClient (chat μš°μ„ , text_generation 폴백)
 
2
  import os
3
  import traceback
4
  import streamlit as st
 
13
  pass
14
 
15
  st.set_page_config(page_title="κ°„λ‹¨ν•œ 챗봇")
16
+ st.title("무엇이든 λ¬Όμ–΄λ³΄μ„Έμš”")
17
 
18
+ # ── Token/Model ────────────────────────────────────────────────────────────
19
  token = os.environ.get("HUGGINGFACEHUB_API_TOKEN") or os.environ.get("HF_TOKEN")
20
+ # λŒ€λ‹€μˆ˜ ν”„λ‘œλ°”μ΄λ”μ—μ„œ chat(conversational)둜 잘 λ™μž‘ν•˜λŠ” λͺ¨λΈλ“€
21
+ DEFAULT_MODELS = [
22
+ "HuggingFaceH4/zephyr-7b-beta",
23
+ "google/gemma-2-2b-it",
24
+ "microsoft/Phi-3-mini-4k-instruct",
25
+ ]
26
+ default_model = os.environ.get("HF_MODEL", DEFAULT_MODELS[0])
27
+
28
+ with st.sidebar:
29
+ st.subheader("Settings")
30
+ model_id = st.selectbox("Model", DEFAULT_MODELS, index=DEFAULT_MODELS.index(default_model) if default_model in DEFAULT_MODELS else 0)
31
+ tok_in = st.text_input("Hugging Face Token (hf_…)", type="password", value=token or "", help="Spaces Secrets에 λ„£μœΌλ©΄ μžλ™μœΌλ‘œ ν™˜κ²½λ³€μˆ˜λ‘œ μ£Όμž…λ©λ‹ˆλ‹€.")
32
+ if tok_in.strip():
33
+ token = tok_in.strip()
34
+
35
  if not token:
36
+ st.error("Hugging Face 토큰이 μ—†μŠ΅λ‹ˆλ‹€. ν™˜κ²½λ³€μˆ˜(HUGGINGFACEHUB_API_TOKEN) μ§€μ •ν•˜κ±°λ‚˜ μ‚¬μ΄λ“œλ°”μ— μž…λ ₯ν•˜μ„Έμš”.")
37
  st.stop()
38
 
39
+ # λͺ¨λΈ λ―Έμ§€μ • ν΄λΌμ΄μ–ΈνŠΈ (호좜 μ‹œ model=... 전달)
40
+ client = InferenceClient(token=token)
41
+
42
+ def _extract_chat_content(result) -> str:
43
+ """
44
+ HF chat-completions의 λ‹€μ–‘ν•œ 리턴 ν˜•μ‹μ„ μ•ˆμ „ν•˜κ²Œ νŒŒμ‹±
45
+ """
46
+ # dict μŠ€νƒ€μΌ
47
+ if isinstance(result, dict):
48
+ try:
49
+ return result["choices"][0]["message"]["content"]
50
+ except Exception:
51
+ pass
52
+ # 객체 μŠ€νƒ€μΌ(점 ν‘œκΈ°)
53
+ try:
54
+ # pydantic-like
55
+ return result.choices[0].message["content"]
56
+ except Exception:
57
+ try:
58
+ return result.choices[0].message.content
59
+ except Exception:
60
+ pass
61
+ # λ§ˆμ§€λ§‰ 폴백
62
+ return str(result)
63
 
64
+ def chat_then_generate(prompt: str) -> str:
65
+ errors = []
66
 
67
+ # 1) chat-completions (conversational) μ‹œλ„
68
  try:
69
+ chat_res = client.chat.completions.create( # huggingface_hub >= 0.24 방식
70
+ model=model_id,
71
+ messages=[{"role": "user", "content": prompt}],
72
+ max_tokens=200,
73
+ temperature=0.7,
74
+ top_p=0.9,
75
+ )
76
+ return _extract_chat_content(chat_res)
77
+ except Exception as e:
78
+ errors.append(f"chat({model_id}): {e}")
79
+
80
+ # 2) μœ„κ°€ μ‹€νŒ¨ν•˜λ©΄ text_generation 폴백 (일뢀 ν”„λ‘œλ°”μ΄λ”/λͺ¨λΈμ€ λ‘˜ λ‹€ 됨)
81
+ try:
82
+ gen_res = client.text_generation(
83
+ prompt,
84
+ model=model_id,
85
  max_new_tokens=200,
86
  temperature=0.7,
87
  top_p=0.9,
88
  )
89
+ return gen_res
 
90
  except Exception as e:
91
+ errors.append(f"text_generation({model_id}): {e}")
92
+
93
+ raise RuntimeError("λͺ¨λ“  μ‹œλ„κ°€ μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€:\n" + "\n".join(errors))
94
 
95
  with st.form("Question"):
96
  user_input = st.text_area("μ§ˆλ¬Έμ„ μž…λ ₯ν•˜μ„Έμš”:")
97
  submitted = st.form_submit_button("전솑")
98
  if submitted and user_input.strip():
99
  try:
100
+ out = chat_then_generate(user_input.strip())
101
  st.success(out)
102
+ except HfHubHTTPError as e:
103
+ st.error(f"Hugging Face API 였λ₯˜: {e}")
104
+ st.code(traceback.format_exc())
105
  except Exception:
106
  st.error("μš”μ²­ 처리 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.")
107
  st.code(traceback.format_exc())