Spaces:
Runtime error
Runtime error
File size: 2,113 Bytes
6275495 e6961b0 6275495 7e8d01b 6275495 db606bb 9113cb8 b10ba12 80ceb8c 6275495 9c601ea 9d9c29a db606bb af5c917 7e8d01b 6275495 db606bb c263659 db606bb d334b30 db606bb 5e09a54 24fb973 c263659 9d9c29a 6275495 5e09a54 6275495 e6961b0 7e8d01b 6275495 e6961b0 6275495 e6961b0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
import os
os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "0"
import torch
import gradio as gr
from transformers import AutoTokenizer, AutoModelForCausalLM
model_id = "sberbank-ai/rugpt3medium_based_on_gpt2"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device)
context = (
"Университет Иннополис был основан в 2012 году. "
"Это современный вуз в России, специализирующийся на IT и робототехнике, "
"расположенный в городе Иннополис, Татарстан.\n"
)
def respond(message, history=None):
prompt = f"Прочитай текст и ответь на вопрос:\n\n{context}\n\nВопрос: {message}\nОтвет:"
input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
with torch.no_grad():
output_ids = model.generate(
input_ids,
max_new_tokens=100,
temperature=0.8,
top_p=0.9,
do_sample=True,
pad_token_id=tokenizer.eos_token_id
)
full_output = tokenizer.decode(output_ids[0], skip_special_tokens=True)
if "Ответ:" in full_output:
answer = full_output.split("Ответ:")[-1].strip()
else:
answer = full_output[len(prompt):].strip()
return answer
# основной Gradio чат
chat = gr.ChatInterface(
fn=respond,
title="Бот об Университете Иннополис (на русском)",
chatbot=gr.Chatbot(label="Диалог"),
textbox=gr.Textbox(placeholder="Задай вопрос на русском...", label="Твой вопрос")
)
# добавим простой API endpoint
demo = gr.Blocks()
with demo:
gr.Markdown("### Иннополис Бот + API")
chat.render()
# API endpoint
@gr.api()
def ask_api(question: str):
return {"answer": respond(question)}
if __name__ == "__main__":
demo.launch()
|