Spaces:
Runtime error
Runtime error
old
Browse files
app.py
CHANGED
@@ -8,110 +8,35 @@ hf_token = os.getenv("HF_TOKEN", None)
|
|
8 |
model_path = "./capybara-finetuned" # или HF-репозиторий, например: "NousResearch/Nous-Capybara-3B-V1.9"
|
9 |
|
10 |
# Загружаем модель и токенизатор
|
11 |
-
|
12 |
tokenizer = AutoTokenizer.from_pretrained(
|
13 |
model_path,
|
14 |
token=hf_token,
|
15 |
trust_remote_code=True,
|
16 |
use_fast=True,
|
17 |
)
|
18 |
-
# Ensure essential special tokens exist; add if missing and remember to resize embeddings
|
19 |
-
_added_specials = False
|
20 |
-
if tokenizer.eos_token is None:
|
21 |
-
tokenizer.add_special_tokens({"eos_token": "</s>"})
|
22 |
-
_added_specials = True
|
23 |
-
if tokenizer.pad_token is None:
|
24 |
-
# Prefer a distinct PAD token; do not alias to eos to avoid None ids
|
25 |
-
tokenizer.add_special_tokens({"pad_token": "<pad>"})
|
26 |
-
_added_specials = True
|
27 |
-
|
28 |
-
# Choose safe dtype depending on device
|
29 |
-
if torch.cuda.is_available():
|
30 |
-
try:
|
31 |
-
bf16_ok = torch.cuda.is_bf16_supported()
|
32 |
-
except Exception:
|
33 |
-
bf16_ok = False
|
34 |
-
_dtype = torch.bfloat16 if bf16_ok else torch.float16
|
35 |
-
else:
|
36 |
-
_dtype = torch.float32
|
37 |
|
38 |
model = AutoModelForCausalLM.from_pretrained(
|
39 |
model_path,
|
40 |
token=hf_token,
|
41 |
-
torch_dtype=
|
42 |
-
device_map="
|
43 |
trust_remote_code=True,
|
44 |
-
low_cpu_mem_usage=False, # avoid meta tensors and lazy init on CPU
|
45 |
)
|
46 |
|
47 |
-
# Make generation config consistent with tokenizer and resize embeddings if we added tokens
|
48 |
-
model.config.pad_token_id = tokenizer.pad_token_id
|
49 |
-
model.config.eos_token_id = tokenizer.eos_token_id
|
50 |
-
if '_added_specials' in globals() and _added_specials:
|
51 |
-
try:
|
52 |
-
model.resize_token_embeddings(len(tokenizer))
|
53 |
-
except Exception as _resize_err:
|
54 |
-
print("[warn] resize_token_embeddings failed:", _resize_err)
|
55 |
-
|
56 |
-
# Set model to eval mode
|
57 |
-
model.eval()
|
58 |
-
|
59 |
-
|
60 |
os.makedirs("offload", exist_ok=True)
|
61 |
|
62 |
-
# Optional warm-up to catch config/runtime issues early
|
63 |
-
try:
|
64 |
-
_ = AutoTokenizer
|
65 |
-
# Minimal no-op generation; will use defaults
|
66 |
-
# We keep it extremely small to avoid heavy compute
|
67 |
-
# and we swallow errors to not crash the app
|
68 |
-
pass
|
69 |
-
except Exception as _warm_err:
|
70 |
-
print("[warmup] warning:", _warm_err)
|
71 |
-
|
72 |
# Создаём пайплайн
|
73 |
-
pipe = pipeline(
|
74 |
-
"text-generation",
|
75 |
-
model=model,
|
76 |
-
tokenizer=tokenizer,
|
77 |
-
)
|
78 |
|
79 |
-
# Функция классификации
|
80 |
def classify(text):
|
81 |
-
if not text or not str(text).strip():
|
82 |
-
return "⚠️ Пустой ввод. Введите сообщение."
|
83 |
-
|
84 |
prompt = f"### Вопрос:\n{text}\n\n### Класс:"
|
85 |
try:
|
86 |
-
|
87 |
-
|
88 |
-
return_tensors="pt",
|
89 |
-
padding=True,
|
90 |
-
truncation=True,
|
91 |
-
max_length=min(2048, getattr(tokenizer, "model_max_length", 2048) or 2048),
|
92 |
-
)
|
93 |
-
input_ids = enc["input_ids"]
|
94 |
-
attention_mask = enc.get("attention_mask")
|
95 |
-
if attention_mask is None:
|
96 |
-
attention_mask = torch.ones_like(input_ids)
|
97 |
-
|
98 |
-
gen_kwargs = dict(
|
99 |
-
max_new_tokens=16,
|
100 |
-
do_sample=False,
|
101 |
-
pad_token_id=tokenizer.pad_token_id,
|
102 |
-
eos_token_id=tokenizer.eos_token_id,
|
103 |
-
use_cache=True,
|
104 |
-
)
|
105 |
-
with torch.no_grad():
|
106 |
-
out = model.generate(input_ids=input_ids, attention_mask=attention_mask, **gen_kwargs)
|
107 |
-
gen_only = out[:, input_ids.shape[1]:]
|
108 |
-
generated = tokenizer.decode(gen_only[0], skip_special_tokens=True)
|
109 |
-
label = (generated.strip().split()[0].lower() if generated.strip() else "unknown")
|
110 |
return f"🔍 Класс: **{label}**"
|
111 |
except Exception as e:
|
112 |
-
|
113 |
-
tb = traceback.format_exc(limit=5)
|
114 |
-
return f"❌ Ошибка: {str(e)}\n\n<details><summary>trace</summary>\n\n{tb}\n\n</details>"
|
115 |
|
116 |
# Интерфейс Gradio
|
117 |
iface = gr.Interface(
|
@@ -120,6 +45,8 @@ iface = gr.Interface(
|
|
120 |
outputs="markdown",
|
121 |
title="Capybara Text Classifier 🦫",
|
122 |
description="Классификация текста как 'запрос' или 'реклама' с помощью Capybara-3B",
|
|
|
|
|
123 |
)
|
124 |
|
125 |
app, local_url, share_url = iface.launch(share=True, ssr_mode=False)
|
|
|
8 |
model_path = "./capybara-finetuned" # или HF-репозиторий, например: "NousResearch/Nous-Capybara-3B-V1.9"
|
9 |
|
10 |
# Загружаем модель и токенизатор
|
|
|
11 |
tokenizer = AutoTokenizer.from_pretrained(
|
12 |
model_path,
|
13 |
token=hf_token,
|
14 |
trust_remote_code=True,
|
15 |
use_fast=True,
|
16 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
|
18 |
model = AutoModelForCausalLM.from_pretrained(
|
19 |
model_path,
|
20 |
token=hf_token,
|
21 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
22 |
+
device_map="auto",
|
23 |
trust_remote_code=True,
|
|
|
24 |
)
|
25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
os.makedirs("offload", exist_ok=True)
|
27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
# Создаём пайплайн
|
29 |
+
pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
|
|
|
|
|
|
|
|
30 |
|
31 |
+
# Функция классификации
|
32 |
def classify(text):
|
|
|
|
|
|
|
33 |
prompt = f"### Вопрос:\n{text}\n\n### Класс:"
|
34 |
try:
|
35 |
+
result = pipe(prompt, max_new_tokens=10, do_sample=False)[0]["generated_text"]
|
36 |
+
label = result.split("### Класс:")[-1].strip().split()[0].lower()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
return f"🔍 Класс: **{label}**"
|
38 |
except Exception as e:
|
39 |
+
return f"❌ Ошибка: {str(e)}"
|
|
|
|
|
40 |
|
41 |
# Интерфейс Gradio
|
42 |
iface = gr.Interface(
|
|
|
45 |
outputs="markdown",
|
46 |
title="Capybara Text Classifier 🦫",
|
47 |
description="Классификация текста как 'запрос' или 'реклама' с помощью Capybara-3B",
|
48 |
+
# enable_api=True, # Разрешаем вызывать данный Interface извне
|
49 |
+
# api_name="/classify" # Название эндпоинта (путь для client.predict)
|
50 |
)
|
51 |
|
52 |
app, local_url, share_url = iface.launch(share=True, ssr_mode=False)
|