AnswerMate / app.py
Brasd99's picture
Lost char
fd14ab3
raw
history blame
3.58 kB
from typing import List, Tuple, Dict, Any
import time
import json
import requests
import gradio as gr
MAX_QUESTIONS_COUNT = 25
MAX_TAGS_COUNT = 5
MAX_ATTEMPS = 3
WAIT_TIME = 3
CHATGPT_URL = 'https://free.churchless.tech/v1/chat/completions'
def get_answer(question: str) -> Dict[str, Any]:
headers = {
'Content-Type': 'application/json; charset=utf-8'
}
payload = {
'model': 'gpt-3.5-turbo',
'messages': [{
'role': 'user',
'content': question
}]
}
try:
response = requests.post(CHATGPT_URL, headers=headers, data=json.dumps(payload))
response.raise_for_status()
content = response.json()['choices'][0]['message']['content']
return {
'status': True,
'content': content
}
except:
return {
'status': False
}
def format_results(results: List[Tuple[str, str]]) -> str:
output = ''
for i, (question, answer) in enumerate(results):
output += f'Question №{i+1}: {question}\n'
output += f'Answer: {answer}\n'
if i < len(results) - 1:
output += '--------------------------------------\n\n'
output = output.strip()
return output
def validate_tags(tags: str) -> None:
if not tags:
raise gr.Error('Validation error. It is necessary to set at least one tag')
if len(tags) > MAX_TAGS_COUNT:
raise gr.Error(f'Validation error. The maximum allowed number of tags is {MAX_TAGS_COUNT}.')
def validate_questions(questions: str) -> None:
if not questions:
raise gr.Error('Validation error. It is necessary to ask at least one question')
if len(questions) > MAX_QUESTIONS_COUNT:
raise gr.Error(f'Validation error. The maximum allowed number of questions is {MAX_QUESTIONS_COUNT}.')
def find_answers(tags: str, questions: str, progress=gr.Progress()) -> str:
tags = tags.split('\n')
questions = questions.split('\n')
validate_tags(tags)
validate_questions(questions)
tags_str = ''.join([f'[{tag}]' for tag in tags])
results = []
for question in progress.tqdm(questions):
tagged_question = f'{tags_str} {question}'
for attempt in range(MAX_ATTEMPS):
answer = get_answer(tagged_question)
if answer['status']:
results.append((question, answer['content']))
break
elif attempt == MAX_ATTEMPS - 1:
results.append((question, 'An error occurred while receiving data.'))
else:
time.sleep(WAIT_TIME)
return format_results(results)
title = '<h1 style="text-align:center">AnswerMate</h1>'
with gr.Blocks(theme='soft', title='AnswerMate') as blocks:
gr.HTML(title)
gr.Markdown('The service allows you to get answers to all questions on the specified topic.')
with gr.Row():
tags_input = gr.Textbox(
label='Enter tags (each line is a separate tag). Maximum: 5.',
placeholder='.Net\nC#',
lines=5)
questions_input = gr.Textbox(
label='Enter questions (each line is a separate question). Maximum: 25.',
placeholder='What is inheritance, encapsulation, abstraction, polymorphism?\nWhat is CLR?',
lines=25)
process_button = gr.Button('Find answers')
outputs = gr.Textbox(label='Output', placeholder='Output will appear here')
process_button.click(fn=find_answers, inputs=[tags_input, questions_input], outputs=outputs)
blocks.queue(concurrency_count=1).launch()