Spaces:
Sleeping
Sleeping
from transformers import AutoTokenizer, T5ForConditionalGeneration | |
import torch | |
import gradio as gr | |
import re | |
import json | |
# Инициализация модели | |
def load_model(): | |
tokenizer = AutoTokenizer.from_pretrained( | |
"cointegrated/rut5-base-multitask", | |
legacy=False | |
) | |
model = T5ForConditionalGeneration.from_pretrained( | |
"cointegrated/rut5-base-multitask", | |
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32 | |
) | |
return tokenizer, model | |
tokenizer, model = load_model() | |
# Функция генерации мета-тегов | |
def generate_meta_tags(description): | |
try: | |
# Формируем четкий промт | |
prompt = f""" | |
Сгенерируй SEO-метатеги для товара на основе описания. | |
Требования: | |
- Title: до 60 символов, ключевые слова | |
- Description: до 160 символов, преимущества | |
Описание товара: | |
{description.strip()} | |
Выведи только JSON-объект: | |
{{"title": "...", "description": "..."}} | |
""" | |
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512) | |
with torch.no_grad(): | |
outputs = model.generate( | |
**inputs, | |
max_new_tokens=200, | |
num_beams=3, | |
do_sample=True, | |
temperature=0.5, | |
early_stopping=True | |
) | |
# Обработка результата | |
result = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
json_match = re.search(r'\{.*\}', result, re.DOTALL) | |
if json_match: | |
tags = json.loads(json_match.group()) | |
# Проверяем и обрезаем длину | |
return { | |
"title": tags.get("title", "")[:60], | |
"description": tags.get("description", "")[:160] | |
} | |
except Exception as e: | |
print(f"Error: {e}") | |
# Fallback вариант | |
clean_text = re.sub(r'[^\w\s]', '', description) | |
return { | |
"title": clean_text[:60], | |
"description": clean_text[:160] | |
} | |
# Интерфейс Gradio | |
with gr.Blocks(title="SEO Генератор") as app: | |
gr.Markdown("## Генератор мета-тегов для товаров") | |
with gr.Row(): | |
with gr.Column(): | |
input_desc = gr.Textbox( | |
label="Введите описание товара", | |
placeholder="Например: Смартфон Samsung Galaxy S23...", | |
lines=5 | |
) | |
btn = gr.Button("Сгенерировать", variant="primary") | |
with gr.Column(): | |
output_tags = gr.JSON(label="Результат") | |
btn.click( | |
fn=generate_meta_tags, | |
inputs=input_desc, | |
outputs=output_tags | |
) | |
if __name__ == "__main__": | |
app.launch(server_name="0.0.0.0", server_port=7860) |