Triok1 commited on
Commit
05c8c2e
·
verified ·
1 Parent(s): 82152ba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -67
app.py CHANGED
@@ -1,73 +1,39 @@
1
- from transformers import AutoTokenizer, T5ForConditionalGeneration
2
- import torch
3
  import gradio as gr
4
- import re
5
 
6
- tokenizer = AutoTokenizer.from_pretrained("cointegrated/rut5-base-multitask", legacy=False)
7
- model = T5ForConditionalGeneration.from_pretrained("cointegrated/rut5-base-multitask")
 
 
8
 
9
- def smart_truncate(text, max_len):
10
- if len(text) <= max_len:
11
- return text
12
- return text[:text[:max_len+1].rfind(' ')].strip()
13
-
14
- def generate_meta(description):
15
- # Очищаем входное описание
16
- description = description.strip()
17
-
18
- # Теперь безопасный f-string без .strip() внутри
19
- prompt = """
20
- Create a title and description for product page.
21
- Product name: Fenix ARB-L18-4000U
22
- Description: {description}
23
-
24
- Output format:
25
- {{"title": "SEO заголовок до 60 символов", "description": "SEO описание до 160 символов"}}
26
- """.format(description=description)
27
 
28
  inputs = tokenizer(prompt, return_tensors="pt", max_length=512, truncation=True)
29
-
30
- with torch.no_grad():
31
- outputs = model.generate(
32
- **inputs,
33
- max_new_tokens=200,
34
- num_beams=5,
35
- early_stopping=True,
36
- no_repeat_ngram_size=2
37
- )
38
-
39
- try:
40
- result = tokenizer.decode(outputs[0], skip_special_tokens=True)
41
- json_match = re.search(r'\{.*\}', result, re.DOTALL)
42
-
43
- if json_match:
44
- json_data = json.loads(json_match.group())
45
- title = smart_truncate(json_data.get("title", ""), 60)
46
- desc = smart_truncate(json_data.get("description", ""), 160)
47
- else:
48
- clean_text = re.sub(r'\s+', ' ', description)
49
- title = smart_truncate(f"Аккумулятор Fenix {clean_text}", 60)
50
- desc = smart_truncate(clean_text, 160)
51
-
52
- except Exception as e:
53
- clean_text = re.sub(r'\s+', ' ', description)
54
- title = smart_truncate(f"Аккумулятор Fenix {clean_text}", 60)
55
- desc = smart_truncate(clean_text, 160)
56
-
57
- return title, desc
58
-
59
-
60
- # Интерфейс
61
- with gr.Blocks() as app:
62
- gr.Markdown("## Генератор метатегов (контроль длины)")
63
 
64
- inp = gr.Textbox(label="Описание товара", lines=7)
65
- btn = gr.Button("Сгенерировать")
66
-
67
- with gr.Row():
68
- out_title = gr.Textbox(label="Title (до 60)", interactive=False)
69
- out_desc = gr.Textbox(label="Description (до 160)", lines=3, interactive=False)
70
-
71
- btn.click(fn=generate_meta, inputs=inp, outputs=[out_title, out_desc])
72
-
73
- app.launch()
 
 
 
 
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
3
 
4
+ # Загружаем модель и токенайзер
5
+ model_name = "cointegrated/rut5-base-summarization"
6
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
7
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
8
 
9
+ def generate_meta_description(product_description):
10
+ prompt = f"Сгенерируй meta description (до 160 символов) по следующему описанию товара: {product_description}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  inputs = tokenizer(prompt, return_tensors="pt", max_length=512, truncation=True)
13
+ summary_ids = model.generate(
14
+ inputs["input_ids"],
15
+ max_length=60, # приблизительно ~160 символов на русском
16
+ num_beams=4,
17
+ no_repeat_ngram_size=2,
18
+ early_stopping=True
19
+ )
20
+ summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
21
+
22
+ # обрезаем аккуратно, чтобы не обрывать слова
23
+ if len(summary) > 160:
24
+ truncated = summary[:160]
25
+ last_space = truncated.rfind(' ')
26
+ summary = truncated[:last_space]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ return summary.strip()
29
+
30
+ iface = gr.Interface(
31
+ fn=generate_meta_description,
32
+ inputs=gr.Textbox(label="Описание товара", lines=5, placeholder="Например: Красивое мужское пальто из шерсти..."),
33
+ outputs=gr.Textbox(label="Meta Description (до 160 символов)"),
34
+ title="Meta Description генератор (русский)",
35
+ description="Генерирует логичный и краткий meta description по описанию товара (до 160 символов, без обрезания слов)."
36
+ )
37
+
38
+ if __name__ == "__main__":
39
+ iface.launch()