Abobasnik commited on
Commit
6ed47a7
·
verified ·
1 Parent(s): 8cb4ea3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -24
app.py CHANGED
@@ -6,57 +6,49 @@ import os
6
  client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct", token=os.getenv("HF_TOKEN"))
7
 
8
  def process_text_simple(user_input, tone, task, language):
9
- # Базовая проверка ввода
10
  if not user_input or not user_input.strip():
11
  return "Пожалуйста, введите текст для обработки."
12
 
13
- # Формируем четкую инструкцию для модели
14
- prompt = f"Инструкция: {task}. Тон: {tone}. Язык: {language}.\nТекст для обработки: {user_input}"
15
 
16
  messages = [
17
- {"role": "system", "content": "Ты профессиональный AI-переводчик и редактор. Выполняй задачу точно и без лишних слов."},
18
  {"role": "user", "content": prompt}
19
  ]
20
 
21
  full_response = ""
22
  try:
23
- # Прямая генерация без сложной истории
24
  for chunk in client.chat_completion(messages=messages, max_tokens=1000, stream=True):
25
- token = chunk.choices[0].delta.content
26
- if token:
27
- full_response += token
28
- yield full_response
 
29
  except Exception as e:
30
- yield f"Произошла ошибка API: {str(e)}"
31
 
32
  # Создание интерфейса
33
  with gr.Blocks() as demo:
34
- gr.HTML("<div style='text-align:center;'><h1>🌈 AI Text Genius</h1><p>Версия 6.2 (Stable)</p></div>")
35
 
36
  with gr.Row():
37
  with gr.Column():
38
- # Отображение логотипа
39
  if os.path.exists("logo.png"):
40
  gr.Image("logo.png", show_label=False, container=False, height=120)
41
 
42
- text_input = gr.Textbox(label="Введите текст", lines=5, placeholder="Напишите что угодно...")
43
 
44
  with gr.Row():
45
  tone = gr.Dropdown(["Нейтральный", "Официальный", "Дерзкий", "Дружелюбный"], label="Настроение", value="Нейтральный")
46
- task = gr.Dropdown(["Перевести", "Суммировать", "Улучшить стиль", "Исправить ошибки"], label="Что сделать?", value="Перевести")
47
- lang = gr.Dropdown(["Русский", "English", "Deutsch", "Français", "Español"], label="Язык результата", value="Русский")
48
 
49
- btn = gr.Button("🚀 Обработать текст", variant="primary")
50
 
51
  with gr.Column():
52
- output = gr.Textbox(label="Результат от AI", lines=12, interactive=False)
53
 
54
- # Подключаем функцию напрямую к кнопке
55
- btn.click(
56
- fn=process_text_simple,
57
- inputs=[text_input, tone, task, lang],
58
- outputs=[output]
59
- )
60
 
61
- # Запуск
62
  demo.launch(theme="soft")
 
6
  client = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct", token=os.getenv("HF_TOKEN"))
7
 
8
  def process_text_simple(user_input, tone, task, language):
 
9
  if not user_input or not user_input.strip():
10
  return "Пожалуйста, введите текст для обработки."
11
 
12
+ prompt = f"Instruction: {task}. Tone: {tone}. Language: {language}.\nText: {user_input}"
 
13
 
14
  messages = [
15
+ {"role": "system", "content": "You are a helpful AI assistant. Respond only with the requested transformation."},
16
  {"role": "user", "content": prompt}
17
  ]
18
 
19
  full_response = ""
20
  try:
21
+ # Добавляем строгую проверку каждого чанка
22
  for chunk in client.chat_completion(messages=messages, max_tokens=1000, stream=True):
23
+ if chunk.choices and len(chunk.choices) > 0: # <-- Вот эта проверка уберет ошибку
24
+ token = chunk.choices[0].delta.content
25
+ if token:
26
+ full_response += token
27
+ yield full_response
28
  except Exception as e:
29
+ yield f"Ошибка API: {str(e)}"
30
 
31
  # Создание интерфейса
32
  with gr.Blocks() as demo:
33
+ gr.HTML("<div style='text-align:center;'><h1>🌈 AI Text Genius</h1><p>Версия 6.3 (Stable)</p></div>")
34
 
35
  with gr.Row():
36
  with gr.Column():
 
37
  if os.path.exists("logo.png"):
38
  gr.Image("logo.png", show_label=False, container=False, height=120)
39
 
40
+ text_input = gr.Textbox(label="Введите текст", lines=5)
41
 
42
  with gr.Row():
43
  tone = gr.Dropdown(["Нейтральный", "Официальный", "Дерзкий", "Дружелюбный"], label="Настроение", value="Нейтральный")
44
+ task = gr.Dropdown(["Перевести", "Суммировать", "Улучшить стиль"], label="Задача", value="Перевести")
45
+ lang = gr.Dropdown(["Русский", "English", "Deutsch"], label="Язык", value="Русский")
46
 
47
+ btn = gr.Button("🚀 Обработать", variant="primary")
48
 
49
  with gr.Column():
50
+ output = gr.Textbox(label="Результат", lines=12, interactive=False)
51
 
52
+ btn.click(fn=process_text_simple, inputs=[text_input, tone, task, lang], outputs=[output])
 
 
 
 
 
53
 
 
54
  demo.launch(theme="soft")