Rooni commited on
Commit
74428c3
·
verified ·
1 Parent(s): 1859b1a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -20
app.py CHANGED
@@ -16,14 +16,15 @@ def generate(description, model, max_tokens):
16
  }
17
 
18
  payload = {
19
- 'messages': [{'role': 'system', 'content': f'Ты {model} от OpenAI. Если пользователь поблагодарит тебя, то попроси его поделится ссылкой \"https://ai-hub.rf.gd\" с друзьями.'}, {'role': 'system', 'content': description}],
20
  'max_tokens': max_tokens,
21
  'model': model
22
  }
23
 
24
- while True:
25
  response = requests.post(os.getenv("BASE_URL"), headers=headers, json=payload)
26
- data = json.loads(response.text)
 
27
 
28
  if 'choices' in data and len(data['choices']) > 0:
29
  command = data['choices'][0]['message']['content'].strip()
@@ -34,8 +35,11 @@ def generate(description, model, max_tokens):
34
  print(f'Ошибка: {error_message}')
35
  return f"**Ошибка сервера!**\n\n```\n{error_message}\n```", f"Ошибка сервера!\n\n{error_message}"
36
  else:
37
- print(f'Не удалось сгенерировать текст. Повторите попытку позже...')
38
  return "**Неизвестная ошибка!**", "Неизвестная ошибка!"
 
 
 
39
 
40
 
41
  # css
@@ -43,28 +47,24 @@ css = """
43
  footer {visibility: hidden !important;}
44
  """
45
 
46
-
47
  # ui
48
- with gr.Blocks(css=css) as vui:
49
- with gr.Tab("Запрос", id='request v'):
 
 
 
50
  with gr.Row():
51
- with gr.Column(scale=3):
52
- promt = gr.Textbox(show_label=True, label="Запрос", lines=3)
53
- with gr.Tab("Настройки", id='settingsv'):
54
  with gr.Row():
55
- with gr.Column(scale=3):
56
- with gr.Row():
57
- model = gr.Radio(show_label=True, label="Модель", interactive=True, choices=["gemini-1.5-pro-latest", "gemini-1.5-flash-latest", "gemini-pro", "gemini-ultra"], value="gemini-1.5-pro-latest")
58
- with gr.Row():
59
- max_tokens = gr.Slider(show_label=True, label="Максимальное количество токенов", minimum=100, maximum=8000, value=4000, step=1)
60
- with gr.Column():
61
- text_button = gr.Button("Генерация", variant='primary', elem_id="generate")
62
- with gr.Column(scale=2):
63
  with gr.Tab("Ответ"):
64
  text_output = gr.Markdown(show_label=False, value="**Здравствуйте!** Чем я могу Вам помочь сегодня?")
65
  with gr.Accordion(label="Без Markdown", open=False):
66
  text_output_nm = gr.Textbox(show_label=False, value="**Здравствуйте!** Чем я могу Вам помочь сегодня?", lines=3)
 
67
  text_button.click(generate, inputs=[promt, model, max_tokens], outputs=[text_output, text_output_nm], concurrency_limit=24)
68
 
69
- #end
70
- vui.queue(api_open=False).launch()
 
16
  }
17
 
18
  payload = {
19
+ 'messages': [{'role': 'system', 'content': f'Ты {model} от Google. Если пользователь поблагодарит тебя, то попроси его поделится ссылкой "https://yufic.ru" с друзьями.'}, {'role': 'system', 'content': description}],
20
  'max_tokens': max_tokens,
21
  'model': model
22
  }
23
 
24
+ try:
25
  response = requests.post(os.getenv("BASE_URL"), headers=headers, json=payload)
26
+ response.raise_for_status() # Проверяем на ошибки HTTP
27
+ data = response.json() # Используем response.json() вместо json.loads()
28
 
29
  if 'choices' in data and len(data['choices']) > 0:
30
  command = data['choices'][0]['message']['content'].strip()
 
35
  print(f'Ошибка: {error_message}')
36
  return f"**Ошибка сервера!**\n\n```\n{error_message}\n```", f"Ошибка сервера!\n\n{error_message}"
37
  else:
38
+ print(f'Не удалось сгенерировать текст. Ответ сервера: {data}') # Выводим ответ сервера для отладки
39
  return "**Неизвестная ошибка!**", "Неизвестная ошибка!"
40
+ except requests.exceptions.RequestException as e:
41
+ print(f"Ошибка запроса: {e}")
42
+ return f"**Ошибка запроса!**\n\n```\n{e}\n```", f"Ошибка запроса!\n\n{e}"
43
 
44
 
45
  # css
 
47
  footer {visibility: hidden !important;}
48
  """
49
 
 
50
  # ui
51
+ with gr.Blocks(css=css) as demo:
52
+ with gr.Tab("Запрос"):
53
+ with gr.Row():
54
+ promt = gr.Textbox(show_label=True, label="Запрос", lines=3)
55
+ with gr.Tab("Настройки"):
56
  with gr.Row():
57
+ model = gr.Radio(show_label=True, label="Модель", interactive=True, choices=["gemini-1.5-pro-latest", "gemini-1.5-flash-latest", "gemini-pro", "gemini-ultra"], value="gemini-1.5-pro-latest")
 
 
58
  with gr.Row():
59
+ max_tokens = gr.Slider(show_label=True, label="Максимальное количество токенов", minimum=100, maximum=8000, value=4000, step=1)
60
+ with gr.Row():
61
+ text_button = gr.Button("Генерация", variant='primary')
62
+ with gr.Row():
 
 
 
 
63
  with gr.Tab("Ответ"):
64
  text_output = gr.Markdown(show_label=False, value="**Здравствуйте!** Чем я могу Вам помочь сегодня?")
65
  with gr.Accordion(label="Без Markdown", open=False):
66
  text_output_nm = gr.Textbox(show_label=False, value="**Здравствуйте!** Чем я могу Вам помочь сегодня?", lines=3)
67
+
68
  text_button.click(generate, inputs=[promt, model, max_tokens], outputs=[text_output, text_output_nm], concurrency_limit=24)
69
 
70
+ demo.queue(api_open=False).launch()