Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,37 +2,34 @@ import os
|
|
| 2 |
import subprocess
|
| 3 |
import shutil
|
| 4 |
import gradio as gr
|
| 5 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 6 |
import torch
|
| 7 |
from huggingface_hub import HfApi
|
| 8 |
|
|
|
|
|
|
|
|
|
|
| 9 |
def prepare_model():
|
| 10 |
model_path = "./ni_v1_model"
|
| 11 |
-
# Hugging Faceのキャッシュディレクトリ(ここがパンクの元)
|
| 12 |
-
cache_path = os.path.expanduser("~/.cache/huggingface/hub")
|
| 13 |
token = os.getenv("HF_TOKEN")
|
| 14 |
|
| 15 |
if not os.path.exists(model_path):
|
| 16 |
print("🧹 ストレージ確保のため、古い残骸を掃除するぜ...")
|
| 17 |
-
# 以前のマージ失敗作があれば削除
|
| 18 |
if os.path.exists(model_path):
|
| 19 |
shutil.rmtree(model_path)
|
| 20 |
-
|
| 21 |
-
# もし容量がギリギリならキャッシュも消す(再ダウンロードになるけど背に腹は代えられない)
|
| 22 |
-
# shutil.rmtree(cache_path, ignore_errors=True)
|
| 23 |
-
|
| 24 |
print("🚀 NI-v1 マージ開始...")
|
| 25 |
env = os.environ.copy()
|
| 26 |
if token:
|
| 27 |
env["HF_TOKEN"] = token
|
|
|
|
| 28 |
try:
|
| 29 |
subprocess.run(["hf", "auth", "login", "--token", token], check=True)
|
| 30 |
except:
|
| 31 |
-
print("⚠️
|
| 32 |
|
| 33 |
try:
|
| 34 |
-
#
|
| 35 |
-
# --low-cpu-mem: さらに負荷を減らす
|
| 36 |
subprocess.run(
|
| 37 |
["mergekit-yaml", "config.yaml", model_path,
|
| 38 |
"--allow-crimes",
|
|
@@ -41,42 +38,67 @@ def prepare_model():
|
|
| 41 |
check=True,
|
| 42 |
env=env
|
| 43 |
)
|
| 44 |
-
print("✨ マージ成功。のっぽ、
|
| 45 |
except:
|
| 46 |
-
raise RuntimeError("マージ失敗。
|
| 47 |
|
| 48 |
-
print("🧠 NI-v1 ロード中...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
|
| 50 |
model = AutoModelForCausalLM.from_pretrained(
|
| 51 |
model_path,
|
| 52 |
-
|
| 53 |
device_map="auto",
|
| 54 |
trust_remote_code=True
|
| 55 |
)
|
| 56 |
return pipeline("text-generation", model=model, tokenizer=tokenizer)
|
| 57 |
|
|
|
|
| 58 |
try:
|
| 59 |
pipe = prepare_model()
|
| 60 |
except Exception as e:
|
| 61 |
print(f"起動失敗: {e}")
|
| 62 |
pipe = None
|
| 63 |
|
|
|
|
|
|
|
|
|
|
| 64 |
def predict(message, history):
|
| 65 |
-
if pipe is None:
|
|
|
|
|
|
|
|
|
|
| 66 |
prompt = f"<|im_start|>user\n{message}<|im_end|>\n<|im_start|>assistant\n"
|
| 67 |
outputs = pipe(prompt, max_new_tokens=512, do_sample=True, temperature=0.7)
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
| 69 |
|
|
|
|
|
|
|
|
|
|
| 70 |
with gr.Blocks(title="NI-v1.0") as demo:
|
| 71 |
gr.Markdown("# 🤖 Noppo-Intelligence v1.0")
|
| 72 |
|
| 73 |
with gr.Tab("チャット"):
|
|
|
|
| 74 |
gr.ChatInterface(fn=predict)
|
| 75 |
|
| 76 |
with gr.Tab("公開"):
|
|
|
|
|
|
|
| 77 |
repo_id = gr.Textbox(label="Repo ID", value="noppodev/NoppoIntelligence")
|
| 78 |
-
user_token = gr.Textbox(label="Write Token", type="password")
|
| 79 |
-
pub_btn = gr.Button("アップロード")
|
| 80 |
status = gr.Textbox(label="Status")
|
| 81 |
|
| 82 |
def upload(r, t):
|
|
@@ -84,8 +106,9 @@ with gr.Blocks(title="NI-v1.0") as demo:
|
|
| 84 |
api = HfApi()
|
| 85 |
api.create_repo(repo_id=r, repo_type="model", exist_ok=True)
|
| 86 |
api.upload_folder(folder_path="./ni_v1_model", repo_id=r, token=t)
|
| 87 |
-
return "✅ 完了
|
| 88 |
-
except Exception as e:
|
|
|
|
| 89 |
|
| 90 |
pub_btn.click(upload, [repo_id, user_token], status)
|
| 91 |
|
|
|
|
| 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",
|
|
|
|
| 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):
|
|
|
|
| 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 |
|