AIRider commited on
Commit
b4dff1d
·
verified ·
1 Parent(s): c174edf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -9
app.py CHANGED
@@ -1,9 +1,12 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import os
 
4
 
5
  hf_token = os.getenv("HF_TOKEN")
6
 
 
 
7
  def get_model_response(client, messages, max_tokens, temperature, top_p):
8
  try:
9
  response = client.chat_completion(
@@ -11,13 +14,22 @@ def get_model_response(client, messages, max_tokens, temperature, top_p):
11
  max_tokens=max_tokens,
12
  temperature=temperature,
13
  top_p=top_p,
14
- stream=False # 스트리밍을 비활성화하여 전체 응답을 한 번에 받습니다.
15
  )
16
- return response.choices[0].message.content
 
 
 
 
 
 
 
 
17
  except Exception as e:
18
- return f"모델 추론 실패: {str(e)}"
19
 
20
  def respond(message, history, system_message, max_tokens, temperature, top_p, selected_model):
 
21
  try:
22
  client = InferenceClient(model=selected_model, token=hf_token)
23
 
@@ -25,12 +37,17 @@ def respond(message, history, system_message, max_tokens, temperature, top_p, se
25
  messages.extend([{"role": "user" if i % 2 == 0 else "assistant", "content": m} for h in history for i, m in enumerate(h) if m])
26
  messages.append({"role": "user", "content": message})
27
 
28
- response = get_model_response(client, messages, max_tokens, temperature, top_p)
 
 
 
29
 
30
- history.append((message, response))
31
- return "", history
32
  except Exception as e:
33
- return "", history + [(message, f"오류 발생: {str(e)}")]
 
 
 
 
34
 
35
  models = {
36
  "deepseek-ai/DeepSeek-Coder-V2-Instruct": "DeepSeek-Coder-V2-Instruct",
@@ -47,6 +64,7 @@ with gr.Blocks() as demo:
47
 
48
  with gr.Row():
49
  regenerate = gr.Button("🔄 재생성")
 
50
  clear = gr.Button("🗑️ 대화 내역 지우기")
51
 
52
  with gr.Accordion("추가 설정", open=True):
@@ -62,10 +80,11 @@ with gr.Blocks() as demo:
62
 
63
  send.click(respond, inputs=[msg, chatbot, system_message, max_tokens, temperature, top_p, model], outputs=[msg, chatbot])
64
  msg.submit(respond, inputs=[msg, chatbot, system_message, max_tokens, temperature, top_p, model], outputs=[msg, chatbot])
65
- regenerate.click(lambda h: respond(h[-1][0] if h else "", h[:-1], *h.values()), inputs=[chatbot, system_message, max_tokens, temperature, top_p, model], outputs=[msg, chatbot])
 
66
  clear.click(lambda: (None, None), outputs=[msg, chatbot])
67
 
68
  if __name__ == "__main__":
69
  if not hf_token:
70
  print("경고: HF_TOKEN 환경 변수가 설정되지 않았습니다. 일부 모델에 접근할 수 없을 수 있습니다.")
71
- demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import os
4
+ from threading import Event
5
 
6
  hf_token = os.getenv("HF_TOKEN")
7
 
8
+ stop_event = Event()
9
+
10
  def get_model_response(client, messages, max_tokens, temperature, top_p):
11
  try:
12
  response = client.chat_completion(
 
14
  max_tokens=max_tokens,
15
  temperature=temperature,
16
  top_p=top_p,
17
+ stream=True
18
  )
19
+ full_response = ""
20
+ for message in response:
21
+ if stop_event.is_set():
22
+ break
23
+ token = message.choices[0].delta.content if hasattr(message.choices[0], 'delta') else message.choices[0].text
24
+ if token:
25
+ full_response += token
26
+ yield full_response
27
+ stop_event.clear()
28
  except Exception as e:
29
+ yield f"모델 추론 실패: {str(e)}"
30
 
31
  def respond(message, history, system_message, max_tokens, temperature, top_p, selected_model):
32
+ stop_event.clear()
33
  try:
34
  client = InferenceClient(model=selected_model, token=hf_token)
35
 
 
37
  messages.extend([{"role": "user" if i % 2 == 0 else "assistant", "content": m} for h in history for i, m in enumerate(h) if m])
38
  messages.append({"role": "user", "content": message})
39
 
40
+ response = ""
41
+ for partial_response in get_model_response(client, messages, max_tokens, temperature, top_p):
42
+ response = partial_response
43
+ yield "", history + [(message, response)]
44
 
 
 
45
  except Exception as e:
46
+ yield "", history + [(message, f"오류 발생: {str(e)}")]
47
+
48
+ def stop_generation():
49
+ stop_event.set()
50
+ return "생성이 중단되었습니다."
51
 
52
  models = {
53
  "deepseek-ai/DeepSeek-Coder-V2-Instruct": "DeepSeek-Coder-V2-Instruct",
 
64
 
65
  with gr.Row():
66
  regenerate = gr.Button("🔄 재생성")
67
+ stop = gr.Button("🛑 생성 중단")
68
  clear = gr.Button("🗑️ 대화 내역 지우기")
69
 
70
  with gr.Accordion("추가 설정", open=True):
 
80
 
81
  send.click(respond, inputs=[msg, chatbot, system_message, max_tokens, temperature, top_p, model], outputs=[msg, chatbot])
82
  msg.submit(respond, inputs=[msg, chatbot, system_message, max_tokens, temperature, top_p, model], outputs=[msg, chatbot])
83
+ regenerate.click(lambda h, s, m, t, p, mod: respond(h[-1][0] if h else "", h[:-1], s, m, t, p, mod), inputs=[chatbot, system_message, max_tokens, temperature, top_p, model], outputs=[msg, chatbot])
84
+ stop.click(stop_generation, inputs=[], outputs=[msg])
85
  clear.click(lambda: (None, None), outputs=[msg, chatbot])
86
 
87
  if __name__ == "__main__":
88
  if not hf_token:
89
  print("경고: HF_TOKEN 환경 변수가 설정되지 않았습니다. 일부 모델에 접근할 수 없을 수 있습니다.")
90
+ demo.launch(share=True)