noppodev commited on
Commit
1c327ab
·
verified ·
1 Parent(s): 9beded6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -99
app.py CHANGED
@@ -2,115 +2,62 @@ import os
2
  import subprocess
3
  import shutil
4
  import gradio as gr
5
- from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, BitsAndBytesConfig
6
- import torch
7
  from huggingface_hub import HfApi
8
 
9
- # ---------------------------------------------------------
10
- # 1. モデル準備セクション (ストレージ清掃 + 認証 + マージ)
11
- # ---------------------------------------------------------
12
- def prepare_model():
13
- model_path = "./ni_v1_model"
14
- token = os.getenv("HF_TOKEN")
15
 
16
- if not os.path.exists(model_path):
17
- print("🧹 ストレージ確保のため、古い残骸を掃除するぜ...")
 
 
 
 
18
  if os.path.exists(model_path):
19
  shutil.rmtree(model_path)
20
-
21
- print("🚀 NI-v1 マージ開始...")
22
- env = os.environ.copy()
23
- if token:
24
- env["HF_TOKEN"] = token
25
- # 2026年最新の hf コマンドで認証
26
- try:
27
- subprocess.run(["hf", "auth", "login", "--token", token], check=True)
28
- except:
29
- print("⚠️ 認証コマンド失敗。環境変数のみで続行するぜ。")
30
 
31
- try:
32
- # ストレージとメモリを節約するオプション付きでマージ実行
33
- subprocess.run(
34
- ["mergekit-yaml", "config.yaml", model_path,
35
- "--allow-crimes",
36
- "--lazy-unpickle",
37
- "--low-cpu-mem"],
38
- check=True,
39
- env=env
40
- )
41
- print("✨ マージ成功。のっぽ、やったぜ!")
42
- except:
43
- raise RuntimeError("マジ失敗。config.yaml のレイヤー数を減らしてくれ。")
44
-
45
- print("🧠 NI-v1 ロード中 (4-bit 量子化でメモリ節約モード)...")
 
 
 
 
 
 
 
 
 
46
 
47
- # メモリ不足対策の量子化設定
48
- bnb_config = BitsAndBytesConfig(
49
- load_in_4bit=True,
50
- bnb_4bit_compute_dtype=torch.bfloat16,
51
- bnb_4bit_quant_type="nf4",
52
- bnb_4bit_use_double_quant=True,
53
- )
54
 
55
- tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
56
- model = AutoModelForCausalLM.from_pretrained(
57
- model_path,
58
- quantization_config=bnb_config, # ここメモリ大幅節約
59
- device_map="auto",
60
- trust_remote_code=True
61
- )
62
- return pipeline("text-generation", model=model, tokenizer=tokenizer)
63
-
64
- # ユニット起動
65
- try:
66
- pipe = prepare_model()
67
- except Exception as e:
68
- print(f"起動失敗: {e}")
69
- pipe = None
70
-
71
- # ---------------------------------------------------------
72
- # 2. 推論ロジック
73
- # ---------------------------------------------------------
74
- def predict(message, history):
75
- if pipe is None:
76
- return "知能ユニットが起動してないぜ。容量不足かロードエラーだ。"
77
 
78
- # ユーザー指定のプロンプト形式
79
- prompt = f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n"
80
- outputs = pipe(prompt, max_new_tokens=512, do_sample=True, temperature=0.7)
81
-
82
- # 応答部分を抽出
83
- response = outputs[0]['generated_text'].split("assistant\n")[-1].replace("<|im_end|>", "")
84
- return response
85
 
86
- # ---------------------------------------------------------
87
- # 3. UIセクション (ChatInterfaceで送信エラーを物理的に防ぐ)
88
- # ---------------------------------------------------------
89
- with gr.Blocks(title="NI-v1.0") as demo:
90
- gr.Markdown("# 🤖 Noppo-Intelligence v1.0")
91
-
92
- with gr.Tab("チャット"):
93
- # 履歴管理をGradioに任せるのが、送信エラーを回避する一番の近道だ
94
- gr.ChatInterface(fn=predict)
95
-
96
- with gr.Tab("公開"):
97
- gr.Markdown("### 完成した NI-v1 を Hugging Face にアップロード")
98
- # リポジトリ名はのっぽ指定のもの
99
- repo_id = gr.Textbox(label="Repo ID", value="noppodev/NoppoIntelligence")
100
- user_token = gr.Textbox(label="Write Token (HF_TOKEN)", type="password")
101
- pub_btn = gr.Button("アップロード開始")
102
- status = gr.Textbox(label="Status")
103
-
104
- def upload(r, t):
105
- try:
106
- api = HfApi()
107
- api.create_repo(repo_id=r, repo_type="model", exist_ok=True)
108
- api.upload_folder(folder_path="./ni_v1_model", repo_id=r, token=t)
109
- return "✅ アップロード完了!BeyondIntelligenceへの第一歩だ。"
110
- except Exception as e:
111
- return f"❌ エラー発生: {e}"
112
-
113
- pub_btn.click(upload, [repo_id, user_token], status)
114
 
115
  if __name__ == "__main__":
116
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
2
  import subprocess
3
  import shutil
4
  import gradio as gr
 
 
5
  from huggingface_hub import HfApi
6
 
7
+ # 1. 処理ロジック
8
+ def run_factory(repo_id, token):
9
+ if not repo_id or not token:
10
+ return "❌ Repo IDとTokenを入れてくれ!"
 
 
11
 
12
+ model_path = "./ni_v1_model"
13
+ env = os.environ.copy()
14
+ env["HF_TOKEN"] = token
15
+
16
+ try:
17
+ # 古い残骸を掃除
18
  if os.path.exists(model_path):
19
  shutil.rmtree(model_path)
 
 
 
 
 
 
 
 
 
 
20
 
21
+ # 認証
22
+ print("🚀 認証中...")
23
+ subprocess.run(["hf", "auth", "login", "--token", token], check=True)
24
+
25
+ # マージ実行 (lazy-unpickleでメモリ節約)
26
+ print("🚀 マージ開始...")
27
+ subprocess.run(
28
+ ["mergekit-yaml", "config.yaml", model_path,
29
+ "--allow-crimes", "--lazy-unpickle", "--low-cpu-mem"],
30
+ check=True, env=env
31
+ )
32
+
33
+ # アップロド実行
34
+ print("🚀 アップロード開始...")
35
+ api = HfApi()
36
+ api.create_repo(repo_id=repo_id, repo_type="model", exist_ok=True)
37
+ api.upload_folder(
38
+ folder_path=model_path,
39
+ repo_id=repo_id,
40
+ token=token,
41
+ commit_message="NI-v1.0 generated by NoppoStudio Factory"
42
+ )
43
+
44
+ return f"✅ 成功だぜ!\nリポジトリ: https://huggingface.co/{repo_id}\n今すぐColabで動かそうぜ!"
45
 
46
+ except Exception as e:
47
+ return f"❌ エラー発生: {str(e)}"
 
 
 
 
 
48
 
49
+ # 2. UI
50
+ with gr.Blocks(title="NI-v1 Factory") as demo:
51
+ gr.Markdown("# 🏭 Noppo-Intelligence v1.0 Factory")
52
+ gr.Markdown("Spaces(CPU)マージだけ行い、完成品リポジトリへ自動転送するぜ。")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ with gr.Column():
55
+ repo = gr.Textbox(label="転送先 Repo ID", value="noppodev/NoppoIntelligence")
56
+ token = gr.Textbox(label="Hugging Face Write Token", type="password")
57
+ start_btn = gr.Button("マージ&アップロード��始", variant="primary")
58
+ output = gr.Textbox(label="ログ / 結果", interactive=False)
 
 
59
 
60
+ start_btn.click(run_factory, [repo, token], output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  if __name__ == "__main__":
63
  demo.launch(server_name="0.0.0.0", server_port=7860)