Yokky009 commited on
Commit
205a913
·
verified ·
1 Parent(s): d685e30

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -34
app.py CHANGED
@@ -1,11 +1,26 @@
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,
@@ -15,50 +30,117 @@ def respond(
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
  import gradio as gr
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+ import warnings
5
+ warnings.filterwarnings("ignore")
6
 
7
  """
8
+ Sarashinaモデルを使用したGradioチャットボット
9
+ Hugging Face Transformersライブラリを使用してローカルでモデルを実行
10
  """
 
11
 
12
+ # モデルとトークナイザーの初期化
13
+ MODEL_NAME = "sbintuitions/sarashina2.2-3b-instruct-v0.1"
14
+
15
+ print("モデルを読み込み中...")
16
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
17
+ model = AutoModelForCausalLM.from_pretrained(
18
+ MODEL_NAME,
19
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
20
+ device_map="auto" if torch.cuda.is_available() else None,
21
+ trust_remote_code=True
22
+ )
23
+ print("モデルの読み込みが完了しました。")
24
 
25
  def respond(
26
  message,
 
30
  temperature,
31
  top_p,
32
  ):
33
+ """
34
+ チャットボットの応答を生成する関数
35
+ Gradio ChatInterfaceの標準形式に対応
36
+ """
37
+ try:
38
+ # システムメッセージと会話履歴を含むプロンプトを構築
39
+ conversation = ""
40
+ if system_message.strip():
41
+ conversation += f"システム: {system_message}\n"
42
+
43
+ # 会話履歴を追加
44
+ for user_msg, bot_msg in history:
45
+ if user_msg:
46
+ conversation += f"ユーザー: {user_msg}\n"
47
+ if bot_msg:
48
+ conversation += f"アシスタント: {bot_msg}\n"
49
+
50
+ # 現在のメッセージを追加
51
+ conversation += f"ユーザー: {message}\nアシスタント: "
52
+
53
+ # トークン化
54
+ inputs = tokenizer.encode(conversation, return_tensors="pt")
55
+
56
+ # GPU使用時はCUDAに移動
57
+ if torch.cuda.is_available():
58
+ inputs = inputs.cuda()
59
+
60
+ # 応答生成(ストリーミング対応)
61
+ response = ""
62
+ with torch.no_grad():
63
+ # 一度に生成してからストリーミング風に出力
64
+ outputs = model.generate(
65
+ inputs,
66
+ max_new_tokens=max_tokens,
67
+ temperature=temperature,
68
+ top_p=top_p,
69
+ do_sample=True,
70
+ pad_token_id=tokenizer.eos_token_id,
71
+ eos_token_id=tokenizer.eos_token_id,
72
+ repetition_penalty=1.1
73
+ )
74
+
75
+ # 生成されたテキストをデコード
76
+ generated = tokenizer.decode(outputs[0], skip_special_tokens=True)
77
+
78
+ # 応答部分のみを抽出
79
+ full_response = generated[len(conversation):].strip()
80
+
81
+ # 不要な部分を除去
82
+ if "ユーザー:" in full_response:
83
+ full_response = full_response.split("ユーザー:")[0].strip()
84
+
85
+ # ストリーミング風の出力
86
+ for i in range(len(full_response)):
87
+ response = full_response[:i+1]
88
+ yield response
89
+
90
+ except Exception as e:
91
+ yield f"エラーが発生しました: {str(e)}"
92
 
93
  """
94
+ Gradio ChatInterfaceを使用したシンプルなチャットボット
95
+ カスタマイズ可能なパラメータを含む
96
  """
97
  demo = gr.ChatInterface(
98
  respond,
99
+ title="🤖 Sarashina Chatbot",
100
+ description="Sarashina2.2-3b-instruct モデルを使用した日本語チャットボットです。",
101
  additional_inputs=[
102
+ gr.Textbox(
103
+ value="あなたは親切で知識豊富な日本語アシスタントです。ユーザーの質問に丁寧に答えてください。",
104
+ label="システムメッセージ",
105
+ lines=3
106
+ ),
107
+ gr.Slider(
108
+ minimum=1,
109
+ maximum=1024,
110
+ value=512,
111
+ step=1,
112
+ label="最大新規トークン数"
113
+ ),
114
+ gr.Slider(
115
+ minimum=0.1,
116
+ maximum=2.0,
117
+ value=0.7,
118
+ step=0.1,
119
+ label="Temperature (創造性)"
120
+ ),
121
  gr.Slider(
122
  minimum=0.1,
123
  maximum=1.0,
124
  value=0.95,
125
  step=0.05,
126
+ label="Top-p (多様性制御)",
127
  ),
128
  ],
129
+ theme=gr.themes.Soft(),
130
+ examples=[
131
+ ["こんにちは!今日はどんなことを話しましょうか?"],
132
+ ["日本の文化について教えてください。"],
133
+ ["簡単なレシピを教えてもらえますか?"],
134
+ ["プログラミングについて質問があります。"],
135
+ ],
136
+ cache_examples=False,
137
  )
138
 
 
139
  if __name__ == "__main__":
140
+ demo.launch(
141
+ server_name="0.0.0.0",
142
+ server_port=7860,
143
+ share=False,
144
+ show_api=True, # API documentation を表示
145
+ debug=True
146
+ )