noppodev commited on
Commit
bfdb1d6
·
verified ·
1 Parent(s): b88341c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -42
app.py CHANGED
@@ -5,29 +5,27 @@ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
5
  import torch
6
  from huggingface_hub import HfApi
7
 
8
- # 1. モデルマージ & ロード
9
  def prepare_model():
10
  model_path = "./ni_v1_model"
11
  token = os.getenv("HF_TOKEN")
12
 
13
  if not os.path.exists(model_path):
14
- print("🚀 マージ開始...")
15
  env = os.environ.copy()
16
  if token:
17
  env["HF_TOKEN"] = token
18
  subprocess.run(["huggingface-cli", "login", "--token", token], check=True)
19
 
20
  try:
21
- # config.yamlを使用してマージ
22
  subprocess.run(
23
  ["mergekit-yaml", "config.yaml", model_path, "--allow-crimes"],
24
  check=True,
25
  env=env
26
  )
27
  print("✨ マージ成功。")
28
- except Exception as e:
29
- print(f"❌ マージエラー: {e}")
30
- raise e
31
 
32
  print("🧠 NI-v1 ロード中...")
33
  tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
@@ -39,56 +37,42 @@ def prepare_model():
39
  )
40
  return pipeline("text-generation", model=model, tokenizer=tokenizer)
41
 
42
- # 起動
43
  try:
44
  pipe = prepare_model()
45
  except Exception as e:
46
- print(f"起動エラー: {e}")
47
  pipe = None
48
 
49
- # 2. 推論
50
- def chat_fn(message):
51
- if pipe is None: return "知能ユニット未起動だぜ。"
 
 
 
52
  prompt = f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n"
53
  outputs = pipe(prompt, max_new_tokens=512, do_sample=True, temperature=0.7)
54
- return outputs[0]['generated_text'].split("assistant\n")[-1].replace("<|im_end|>", "")
 
 
 
55
 
56
- # 3. UI (Gradio 5.x 仕様に完全準拠)
57
  with gr.Blocks(title="NI-v1.0") as demo:
58
  gr.Markdown("# 🤖 Noppo-Intelligence v1.0")
59
 
60
  with gr.Tab("チャット"):
61
- # ログで要求されている通り、辞書型(messages)を明示的に指定
62
- chatbot = gr.Chatbot(type="messages")
63
- msg = gr.Textbox(placeholder="最新モデルの力を見せてくれ。")
64
- with gr.Row():
65
- send = gr.Button("送信", variant="primary")
66
- clear = gr.Button("クリア")
67
-
68
- def respond(message, chat_history):
69
- if not message:
70
- return "", chat_history
71
-
72
- # ユーザーの入力を「辞書形式」で追加
73
- chat_history.append({"role": "user", "content": message})
74
-
75
- # 応答生成
76
- bot_res = chat_fn(message)
77
-
78
- # AIの回答を「辞書形式」で追加
79
- chat_history.append({"role": "assistant", "content": bot_res})
80
-
81
- return "", chat_history
82
-
83
- msg.submit(respond, [msg, chatbot], [msg, chatbot])
84
- send.click(respond, [msg, chatbot], [msg, chatbot])
85
- clear.click(lambda: [], None, chatbot, queue=False)
86
 
87
  with gr.Tab("公開"):
88
- # のっぽの指定通り noppodev/NoppoIntelligence に修正
89
  repo_id = gr.Textbox(label="Repo ID", value="noppodev/NoppoIntelligence")
90
- user_token = gr.Textbox(label="Write Token", type="password")
91
- pub_btn = gr.Button("アップロード")
92
  status = gr.Textbox(label="Status")
93
 
94
  def upload(r, t):
@@ -97,7 +81,8 @@ with gr.Blocks(title="NI-v1.0") as demo:
97
  api.create_repo(repo_id=r, repo_type="model", exist_ok=True)
98
  api.upload_folder(folder_path="./ni_v1_model", repo_id=r, token=t)
99
  return "✅ 完了したぜ。"
100
- except Exception as e: return f"❌ エラー: {e}"
 
101
 
102
  pub_btn.click(upload, [repo_id, user_token], status)
103
 
 
5
  import torch
6
  from huggingface_hub import HfApi
7
 
8
+ # 1. モデル準備 (Merge & Load)
9
  def prepare_model():
10
  model_path = "./ni_v1_model"
11
  token = os.getenv("HF_TOKEN")
12
 
13
  if not os.path.exists(model_path):
14
+ print("🚀 NI-v1 マージ開始...")
15
  env = os.environ.copy()
16
  if token:
17
  env["HF_TOKEN"] = token
18
  subprocess.run(["huggingface-cli", "login", "--token", token], check=True)
19
 
20
  try:
 
21
  subprocess.run(
22
  ["mergekit-yaml", "config.yaml", model_path, "--allow-crimes"],
23
  check=True,
24
  env=env
25
  )
26
  print("✨ マージ成功。")
27
+ except:
28
+ raise RuntimeError("マージ失敗。")
 
29
 
30
  print("🧠 NI-v1 ロード中...")
31
  tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
 
37
  )
38
  return pipeline("text-generation", model=model, tokenizer=tokenizer)
39
 
40
+ # グローバルでモデルをロード
41
  try:
42
  pipe = prepare_model()
43
  except Exception as e:
44
+ print(f"起動失敗: {e}")
45
  pipe = None
46
 
47
+ # 推論ロジック
48
+ def predict(message, history):
49
+ if pipe is None:
50
+ return "知能ユニットが起動してないぜ。"
51
+
52
+ # モデル向けのプロンプト構築
53
  prompt = f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n"
54
  outputs = pipe(prompt, max_new_tokens=512, do_sample=True, temperature=0.7)
55
+
56
+ # 応答を抽出
57
+ response = outputs[0]['generated_text'].split("assistant\n")[-1].replace("<|im_end|>", "")
58
+ return response
59
 
60
+ # 2. UI (ChatInterface を使用して送信エラーを物理的に防ぐ)
61
  with gr.Blocks(title="NI-v1.0") as demo:
62
  gr.Markdown("# 🤖 Noppo-Intelligence v1.0")
63
 
64
  with gr.Tab("チャット"):
65
+ # 履歴管理をGradioに任せることで「送信エラー」を回避するぜ
66
+ gr.ChatInterface(
67
+ fn=predict,
68
+ type="messages" # 最新の辞書型(role/content)に固定
69
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  with gr.Tab("公開"):
72
+ gr.Markdown("### 完成した NI-v1 を Hugging Face にアップロード")
73
  repo_id = gr.Textbox(label="Repo ID", value="noppodev/NoppoIntelligence")
74
+ user_token = gr.Textbox(label="Write Token (HF_TOKEN)", type="password")
75
+ pub_btn = gr.Button("アップロード開始")
76
  status = gr.Textbox(label="Status")
77
 
78
  def upload(r, t):
 
81
  api.create_repo(repo_id=r, repo_type="model", exist_ok=True)
82
  api.upload_folder(folder_path="./ni_v1_model", repo_id=r, token=t)
83
  return "✅ 完了したぜ。"
84
+ except Exception as e:
85
+ return f"❌ エラー: {e}"
86
 
87
  pub_btn.click(upload, [repo_id, user_token], status)
88