Studio commited on
Commit
828a989
·
verified ·
1 Parent(s): 2eb1c4b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -54
app.py CHANGED
@@ -1,64 +1,83 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
8
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  if __name__ == "__main__":
64
  demo.launch()
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForQuestionAnswering
3
+ import torch
4
 
5
+ # -------------------------------
6
+ # Модель суммаризации
7
+ # -------------------------------
8
+ sum_tokenizer = AutoTokenizer.from_pretrained("LaciaStudio/Lacia_sum_small_v1")
9
+ sum_model = AutoModelForSeq2SeqLM.from_pretrained("LaciaStudio/Lacia_sum_small_v1")
10
 
11
+ def summarize_document(file):
12
+ if file is None:
13
+ return "Файл не загружен."
14
+ # Открываем файл и читаем его содержимое
15
+ with open(file, "r", encoding="utf-8") as f:
16
+ text = f.read()
17
+ input_text = "summarize: " + text
18
+ inputs = sum_tokenizer(input_text, return_tensors="pt", max_length=512, truncation=True)
19
+ summary_ids = sum_model.generate(inputs["input_ids"], max_length=150, num_beams=4, early_stopping=True)
20
+ summary = sum_tokenizer.decode(summary_ids[0], skip_special_tokens=True)
21
+ return summary
22
 
23
+ # -------------------------------
24
+ # Модель вопросов-ответов (Q&A)
25
+ # -------------------------------
26
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
27
+ qa_tokenizer = AutoTokenizer.from_pretrained("LaciaStudio/Kaleidoscope_large_v1")
28
+ qa_model = AutoModelForQuestionAnswering.from_pretrained("LaciaStudio/Kaleidoscope_large_v1")
29
+ qa_model.to(device)
 
 
30
 
31
+ def answer_question(context, question):
32
+ inputs = qa_tokenizer(question, context, return_tensors="pt", truncation=True, max_length=384)
33
+ inputs = {k: v.to(device) for k, v in inputs.items()}
34
+ outputs = qa_model(**inputs)
35
+ start_index = torch.argmax(outputs.start_logits)
36
+ end_index = torch.argmax(outputs.end_logits)
37
+ answer_tokens = inputs["input_ids"][0][start_index:end_index + 1]
38
+ answer = qa_tokenizer.decode(answer_tokens, skip_special_tokens=True)
39
+ return answer
40
 
41
+ def answer_question_file(file, question):
42
+ if file is None:
43
+ return "Файл не загружен."
44
+ with open(file, "r", encoding="utf-8") as f:
45
+ context = f.read()
46
+ return answer_question(context, question)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ def answer_question_text(context, question):
49
+ return answer_question(context, question)
50
 
51
+ # -------------------------------
52
+ # Интерфейс Gradio
53
+ # -------------------------------
54
+ with gr.Blocks() as demo:
55
+ gr.Markdown("# Интерфейс для суммаризации и вопросов-ответов")
56
+ with gr.Row():
57
+ # Левая колонка – суммаризация
58
+ with gr.Column():
59
+ gr.Markdown("## Суммаризация документа")
60
+ file_input_sum = gr.File(label="Прикрепить файл для суммаризации", file_count="single", type="file")
61
+ summarize_button = gr.Button("Суммаризировать")
62
+ summary_output = gr.Textbox(label="Суммаризация", lines=10)
63
+ summarize_button.click(fn=summarize_document, inputs=file_input_sum, outputs=summary_output)
64
+
65
+ # Правая колонка – Q&A с двумя вкладками
66
+ with gr.Column():
67
+ gr.Markdown("## Вопрос-ответ по документу")
68
+ with gr.Tabs():
69
+ with gr.Tab("Загрузить файл"):
70
+ file_input_qa = gr.File(label="Прикрепить файл с документом", file_count="single", type="file")
71
+ question_input_file = gr.Textbox(label="Введите вопрос", placeholder="Ваш вопрос здесь")
72
+ answer_button_file = gr.Button("Получить ответ")
73
+ answer_output_file = gr.Textbox(label="Ответ", lines=5)
74
+ answer_button_file.click(fn=answer_question_file, inputs=[file_input_qa, question_input_file], outputs=answer_output_file)
75
+ with gr.Tab("Ввести текст"):
76
+ context_input = gr.Textbox(label="Введите текст документа", lines=10, placeholder="Текст документа здесь")
77
+ question_input_text = gr.Textbox(label="Введите вопрос", placeholder="Ваш вопрос здесь")
78
+ answer_button_text = gr.Button("Получить ответ")
79
+ answer_output_text = gr.Textbox(label="Ответ", lines=5)
80
+ answer_button_text.click(fn=answer_question_text, inputs=[context_input, question_input_text], outputs=answer_output_text)
81
+
82
  if __name__ == "__main__":
83
  demo.launch()