JUNGU commited on
Commit
cb245e5
Β·
verified Β·
1 Parent(s): 8c4c037

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +125 -50
app.py CHANGED
@@ -1,64 +1,139 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
- response = ""
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
 
 
 
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
+ # ν•„μš”ν•œ 라이브러리λ₯Ό κ°€μ Έμ˜΅λ‹ˆλ‹€.
2
  import gradio as gr
3
+ import google.generativeai as genai
4
+ import os
5
 
6
+ # --- Hugging Face Spaces의 Secrets λ˜λŠ” 둜컬 ν™˜κ²½λ³€μˆ˜μ—μ„œ API ν‚€λ₯Ό κ°€μ Έμ˜΅λ‹ˆλ‹€. ---
7
+ # 이 앱을 Spaces에 배포할 λ•ŒλŠ” 'Settings' -> 'Repository secrets'에
8
+ # 'GEMINI_API_KEY'λΌλŠ” μ΄λ¦„μœΌλ‘œ ν‚€λ₯Ό μ €μž₯ν•΄μ•Ό ν•©λ‹ˆλ‹€.
9
+ GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
10
 
11
+ # --- UI 및 챗봇 μ„€λͺ… ---
12
+ # Gradio Blocksλ₯Ό μ‚¬μš©ν•˜μ—¬ μ’€ 더 μœ μ—°ν•œ UIλ₯Ό κ΅¬μ„±ν•©λ‹ˆλ‹€.
13
+ with gr.Blocks(theme=gr.themes.Default(primary_hue="blue")) as demo:
14
+ gr.Markdown(
15
+ """
16
+ # β™ŠοΈ Gemini API 챗봇 (Secrets μ‚¬μš©)
17
+ Google Gemini APIλ₯Ό μ‚¬μš©ν•˜λŠ” μ±—λ΄‡μž…λ‹ˆλ‹€.
18
+ Hugging Face Spaces의 'Settings' 탭에 μžˆλŠ” 'Repository secrets'에 `GEMINI_API_KEY`κ°€ μ„€μ •λ˜μ–΄ μžˆμ–΄μ•Ό ν•©λ‹ˆλ‹€.
19
+ [API ν‚€ λ°œκΈ‰λ°›κΈ°](https://aistudio.google.com/app/apikey)
20
+ """
21
+ )
22
+
23
+ # API ν‚€κ°€ μ„€μ •λ˜μ—ˆλŠ”μ§€ ν™•μΈν•˜κ³  μ•ˆλ‚΄ λ©”μ‹œμ§€λ₯Ό ν‘œμ‹œν•©λ‹ˆλ‹€.
24
+ if not GEMINI_API_KEY:
25
+ gr.Warning("⚠️ Gemini API ν‚€κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€. Hugging Face Spaces의 'Repository secrets'에 GEMINI_API_KEYλ₯Ό μΆ”κ°€ν•΄μ£Όμ„Έμš”.")
26
 
27
+ # Gradio 챗봇 UI μ»΄ν¬λ„ŒνŠΈ
28
+ chatbot = gr.Chatbot(label="Gemini 챗봇", height=600)
 
 
 
 
 
 
 
29
 
30
+ with gr.Row():
31
+ # μ‚¬μš©μž λ©”μ‹œμ§€ μž…λ ₯λž€
32
+ msg = gr.Textbox(
33
+ label="λ©”μ‹œμ§€ μž…λ ₯",
34
+ placeholder="무엇이든 λ¬Όμ–΄λ³΄μ„Έμš”...",
35
+ container=False,
36
+ scale=7,
37
+ )
38
+ # 전솑 λ²„νŠΌ
39
+ submit_button = gr.Button("전솑", variant="primary", scale=1)
40
 
41
+ with gr.Accordion("κ³ κΈ‰ μ„€μ •", open=False):
42
+ # LLM의 역할을 μ •μ˜ν•˜λŠ” μ‹œμŠ€ν…œ λ©”μ‹œμ§€
43
+ system_message = gr.Textbox(
44
+ value="You are a helpful and friendly chatbot.", label="μ‹œμŠ€ν…œ λ©”μ‹œμ§€"
45
+ )
46
+ # λͺ¨λΈμ˜ μ°½μ˜μ„±μ„ μ‘°μ ˆν•˜λŠ” μŠ¬λΌμ΄λ”
47
+ temperature = gr.Slider(
48
+ minimum=0.0, maximum=1.0, value=0.7, step=0.1, label="Temperature"
49
+ )
50
+ # 생성할 μ΅œλŒ€ 토큰 수λ₯Ό μ‘°μ ˆν•˜λŠ” μŠ¬λΌμ΄λ”
51
+ max_tokens = gr.Slider(
52
+ minimum=1, maximum=4096, value=1024, step=1, label="Max new tokens"
53
+ )
54
 
55
+ # --- Gemini API 호좜 ν•¨μˆ˜ ---
56
+ def respond(message, chat_history, system_prompt, temp, max_output_tokens):
57
+ # ν™˜κ²½λ³€μˆ˜μ—μ„œ κ°€μ Έμ˜¨ API ν‚€κ°€ μ—†μœΌλ©΄ μ•ˆλ‚΄ λ©”μ‹œμ§€λ₯Ό λ„μ›λ‹ˆλ‹€.
58
+ if not GEMINI_API_KEY:
59
+ yield "Google API ν‚€κ°€ μ„€μ •λ˜μ§€ μ•Šμ•˜μŠ΅λ‹ˆλ‹€. κ΄€λ¦¬μžμ—κ²Œ λ¬Έμ˜ν•˜μ„Έμš”."
60
+ return
61
 
62
+ try:
63
+ # API ν‚€λ₯Ό μ„€μ •ν•©λ‹ˆλ‹€.
64
+ genai.configure(api_key=GEMINI_API_KEY)
65
+ except Exception as e:
66
+ yield f"API ν‚€ 섀정에 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {e}"
67
+ return
68
+
69
+ # μ‚¬μš©ν•  λͺ¨λΈκ³Ό μ‹œμŠ€ν…œ ν”„λ‘¬ν”„νŠΈλ₯Ό μ„€μ •ν•©λ‹ˆλ‹€.
70
+ model = genai.GenerativeModel(
71
+ model_name='gemini-2.0-flash', # μ΅œμ‹  Flash λͺ¨λΈ μ‚¬μš©
72
+ system_instruction=system_prompt
73
+ )
74
 
75
+ # Gradio의 λŒ€ν™” 기둝을 Gemini APIκ°€ 이해할 수 μžˆλŠ” ν˜•μ‹μœΌλ‘œ λ³€ν™˜ν•©λ‹ˆλ‹€.
76
+ gemini_history = []
77
+ for user_msg, model_msg in chat_history:
78
+ if user_msg:
79
+ gemini_history.append({"role": "user", "parts": [user_msg]})
80
+ if model_msg:
81
+ gemini_history.append({"role": "model", "parts": [model_msg]})
82
+
83
+ # 이전 λŒ€ν™” 기둝을 λ°”νƒ•μœΌλ‘œ μ±„νŒ… μ„Έμ…˜μ„ μ‹œμž‘ν•©λ‹ˆλ‹€.
84
+ chat = model.start_chat(history=gemini_history)
85
 
86
+ # λͺ¨λΈ 생성 κ΄€λ ¨ 섀정을 κ΅¬μ„±ν•©λ‹ˆλ‹€.
87
+ generation_config = genai.types.GenerationConfig(
88
+ temperature=temp,
89
+ max_output_tokens=int(max_output_tokens),
90
+ )
91
 
92
+ try:
93
+ # 슀트리밍 λ°©μ‹μœΌλ‘œ λ©”μ‹œμ§€λ₯Ό 보내고 응닡을 λ°›μŠ΅λ‹ˆλ‹€.
94
+ response = chat.send_message(
95
+ message,
96
+ stream=True,
97
+ generation_config=generation_config
98
+ )
 
 
 
 
 
 
 
 
 
 
 
99
 
100
+ # 슀트리밍 응닡을 μ‹€μ‹œκ°„μœΌλ‘œ UI에 ν‘œμ‹œν•©λ‹ˆλ‹€.
101
+ full_response = ""
102
+ for chunk in response:
103
+ if hasattr(chunk, 'text'):
104
+ full_response += chunk.text
105
+ yield full_response
106
 
107
+ except Exception as e:
108
+ # API 호좜 쀑 μ—λŸ¬κ°€ λ°œμƒν•˜λ©΄ UI에 ν‘œμ‹œν•©λ‹ˆλ‹€.
109
+ yield f"응닡 생성 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€: {e}"
110
+
111
+ # --- Gradio 이벀트 λ¦¬μŠ€λ„ˆ ---
112
+ # μ‚¬μš©μžκ°€ λ©”μ‹œμ§€λ₯Ό μž…λ ₯ν•˜κ³  '전솑' λ²„νŠΌμ„ λˆ„λ₯΄κ±°λ‚˜ μ—”ν„°λ₯Ό 쳀을 λ•Œ 싀행될 둜직
113
+ def on_submit(message, chat_history, system_prompt, temp, max_output_tokens):
114
+ # λŒ€ν™” 기둝에 μ‚¬μš©μž λ©”μ‹œμ§€λ₯Ό μΆ”κ°€ν•©λ‹ˆλ‹€.
115
+ chat_history.append((message, None))
116
+ # 슀트리밍 응닡을 μœ„ν•΄ 빈 λ¬Έμžμ—΄λ‘œ 응닡을 μ‹œμž‘ν•©λ‹ˆλ‹€.
117
+ bot_response_stream = respond(message, chat_history, system_prompt, temp, max_output_tokens)
118
+
119
+ # 슀트리밍 응닡을 UI에 μ—…λ°μ΄νŠΈν•©λ‹ˆλ‹€.
120
+ for partial_response in bot_response_stream:
121
+ chat_history[-1] = (message, partial_response)
122
+ yield "", chat_history
123
+
124
+ # λ©”μ‹œμ§€ 전솑(λ²„νŠΌ 클릭 λ˜λŠ” μ—”ν„°) μ‹œ on_submit ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•©λ‹ˆλ‹€.
125
+ # UIμ—μ„œ API ν‚€ μž…λ ₯λž€μ΄ μ œκ±°λ˜μ—ˆμœΌλ―€λ‘œ, μž…λ ₯(inputs) λ¦¬μŠ€νŠΈμ—μ„œλ„ μ œμ™Έν•©λ‹ˆλ‹€.
126
+ msg.submit(
127
+ on_submit,
128
+ [msg, chatbot, system_message, temperature, max_tokens],
129
+ [msg, chatbot]
130
+ )
131
+ submit_button.click(
132
+ on_submit,
133
+ [msg, chatbot, system_message, temperature, max_tokens],
134
+ [msg, chatbot]
135
+ )
136
+
137
+ # μŠ€ν¬λ¦½νŠΈκ°€ 직접 싀행될 λ•Œ Gradio 앱을 μ‹€ν–‰ν•©λ‹ˆλ‹€.
138
  if __name__ == "__main__":
139
+ demo.launch(debug=True)