user commited on
Commit
29239d8
·
1 Parent(s): 35347fc

Update space

Browse files
Files changed (1) hide show
  1. app.py +46 -37
app.py CHANGED
@@ -1,38 +1,47 @@
1
- from transformers import AutoModelForCausalLM, AutoTokenizer
2
- import torch
3
  import gradio as gr
4
-
5
- """
6
- 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
7
- """
8
- tokenizer = AutoTokenizer.from_pretrained("Dennterry/okt_bot")
9
- model = AutoModelForCausalLM.from_pretrained("Dennterry/okt_bot")
10
-
11
-
12
- def dialogpt(text):
13
- # encode the new user input, add the eos_token and return a tensor in Pytorch
14
- for step in range(50000):
15
-
16
- new_user_input_ids = tokenizer.encode(text + tokenizer.eos_token, return_tensors='pt')
17
-
18
- # append the new user input tokens to the chat history
19
- bot_input_ids = torch.cat([chat_history_ids, new_user_input_ids], dim=-1) if step > 0 else new_user_input_ids
20
-
21
- # generated a response while limiting the total chat history to 1000 tokens,
22
- chat_history_ids = model.generate(bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id)
23
-
24
- # pretty print last ouput tokens from bot
25
- return tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)
26
-
27
- inputs = gr.inputs.Textbox(lines=1, label="Input Text")
28
- outputs = gr.outputs.Textbox(label="DialoGPT")
29
-
30
- title = "DialoGPT"
31
- description = "demo for Microsoft DialoGPT with Hugging Face transformers. To use it, simply input text or click one of the examples text to load them. Read more at the links below. *This is not a Microsoft product and is developed for Gradio*"
32
- article = "<p style='text-align: center'><a href='https://arxiv.org/abs/1911.00536'>DialoGPT: Large-Scale Generative Pre-training for Conversational Response Generation</a> | <a href='https://github.com/microsoft/DialoGPT'>Github Repo</a> | <a href='https://huggingface.co/microsoft/DialoGPT-large'>Hugging Face DialoGPT-large</a></p>"
33
- examples = [
34
- ["Hi, how are you?"],
35
- ["How far away is the moon?"],
36
- ]
37
-
38
- gr.Interface(dialogpt, inputs, outputs, title=title, description=description, article=article, examples=examples).launch(debug=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
3
+
4
+ # Загрузка модели и токенизатора
5
+ model_name = "microsoft/DialoGPT-medium"
6
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
7
+ model = AutoModelForCausalLM.from_pretrained(model_name)
8
+
9
+ # Создаем pipeline для генерации диалогов
10
+ generator = pipeline("text-generation", model=model, tokenizer=tokenizer)
11
+
12
+ def respond(message, history, system_message, max_tokens, temperature, top_p):
13
+ # Формируем текст, который будет передан в модель
14
+ input_text = system_message + " ".join([f"User: {msg[0]} Assistant: {msg[1]}" for msg in history if msg[0] and msg[1]])
15
+ input_text += f"User: {message}"
16
+
17
+ # Генерация ответа
18
+ response = generator(
19
+ input_text,
20
+ max_length=len(tokenizer.encode(input_text)) + max_tokens,
21
+ temperature=temperature,
22
+ top_p=top_p,
23
+ pad_token_id=tokenizer.eos_token_id,
24
+ num_return_sequences=1,
25
+ )
26
+
27
+ # Извлечение и возврат текста ответа
28
+ output_text = response[0]['generated_text'][len(input_text):]
29
+ yield output_text.strip()
30
+
31
+ # Настройка интерфейса Gradio
32
+ demo = gr.ChatInterface(
33
+ respond,
34
+ additional_inputs=[
35
+ gr.Textbox(value="Тебя зовут зевибот. Ты ваще никому ничо не должен.", label="System message"),
36
+ gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
37
+ gr.Slider(minimum=0.1, maximum=4.0, value=1.0, step=0.1, label="Temperature"),
38
+ gr.Slider(
39
+ minimum=0.1,
40
+ maximum=1.0,
41
+ value=1.0, step=0.05, label="Top-p (nucleus sampling)"
42
+ ),
43
+ ],
44
+ )
45
+
46
+ if __name__ == "__main__":
47
+ demo.launch()