Spaces:
Sleeping
Sleeping
import gradio as gr | |
import asyncio | |
import time | |
from g4f.client import Client | |
# Асинхронная обертка для синхронной функции с обработкой таймаута и повтором запроса | |
async def ask(question, retries=3, timeout=20): | |
client = Client() | |
for attempt in range(retries): | |
try: | |
# Время начала запроса | |
start_time = time.time() | |
# Пытаемся выполнить запрос | |
response = client.chat.completions.create( | |
model="gpt-4o-mini", | |
messages=[{ | |
"role": "user", | |
"content": question, | |
}], | |
) | |
# Если запрос был успешным, проверяем, не превышен ли таймаут | |
elapsed_time = time.time() - start_time | |
if elapsed_time < timeout: | |
return response.choices[0].message.content | |
else: | |
print("Timeout reached, retrying...") | |
except Exception as e: | |
print(f"Error on attempt {attempt + 1}: {e}") | |
# Ждем немного перед повторной попыткой | |
await asyncio.sleep(1) | |
return "Sorry, there was an error or timeout while processing your request." | |
# Список вопросов | |
questions = [ | |
"На каком языке вы хотите получить результат теста?/What language do you want the test result?", | |
"Какой вы школьный предмет?/What school subject are you?", | |
"Если бы вы были растением, то каким?/If you were a plant, what would you be?", | |
"Какой вы инструмент из коробки с инструментами?/What tool from the toolbox are you?", | |
"Что вкуснее: круг или квадрат?/What tastes better: a circle or a square?", | |
"Если бы вы были кнопкой, что бы вы включали?/If you were a button, what would you turn on?", | |
"Ваше любимое число?/What is your favorite number?", | |
"Чем вы хотите быть в следующей жизни?/What do you want to be in your next life?", | |
"Какой вы вид отдыха?/What type of relaxation are you?", | |
"Какой вы звук?/What sound are you?", | |
"Если бы вы были игрушкой, то какой?/If you were a toy, what would you be?", | |
] | |
# Асинхронная функция обработки данных | |
async def analyze_test(*args): | |
# Создаем словарь ответов | |
answers = {question: answer for question, answer in zip(questions, args)} | |
# Формируем запрос для анализа | |
prompt = ( | |
"You have completed a unique test that reveals your inner essence. " | |
"Generate your response in the user's language: " | |
"if the answers are mostly in English, respond in English; if they are in Russian, respond in Russian. " | |
"Do not propose new questions or answers; focus solely on analyzing the provided data. " | |
"Imagine that I am your guide in this exploration, and together we are trying to uncover who you truly are. " | |
"Analyze the test results, combining them into a cohesive narrative to create a portrait of the user's personality. " | |
"Describe the user's character as if unveiling their hidden archetype, avoiding simple or banal conclusions. " | |
"Do not mention specific answers but draw inspiration from them to craft a compelling narrative about the user. " | |
"The response should be short, engaging, and feel like a vivid character sketch in two to three sentences. " | |
f"Here are the test data: {str(answers)}" | |
) | |
result = await ask(prompt) # Асинхронный вызов функции ask с повтором в случае таймаута | |
return result.replace("```", "") | |
# Создаем интерфейс | |
def gradio_interface(*args): | |
return asyncio.run(analyze_test(*args)) # Теперь асинхронная функция вызывается внутри синхронной функции Gradio | |
inputs = [gr.Textbox(label=question, placeholder="Введите ваш ответ.../Enter your answer...") for question in questions] | |
interface = gr.Interface( | |
fn=gradio_interface, # Используем новый синхронный вызов для Gradio | |
inputs=inputs, | |
outputs="text", | |
title="Тест: Кто вы?/Test: Who are you?", | |
description=( | |
"Отвечайте на вопросы развернуто, чтобы получить более точный результат/Answer the questions in detail to get a more accurate result" | |
) | |
) | |
# Запуск интерфейса | |
if __name__ == "__main__": | |
interface.launch() | |