FridayMaster commited on
Commit
a36f63d
·
verified ·
1 Parent(s): b3abbf4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -37
app.py CHANGED
@@ -1,49 +1,60 @@
 
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
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
  demo = gr.ChatInterface(
46
- respond,
47
  additional_inputs=[
48
  gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
@@ -56,8 +67,9 @@ demo = gr.ChatInterface(
56
  label="Top-p (nucleus sampling)",
57
  ),
58
  ],
 
 
59
  )
60
 
61
-
62
  if __name__ == "__main__":
63
  demo.launch()
 
1
+ import os
2
  import gradio as gr
3
+ from transformers import AutoModelForCausalLM, AutoTokenizer
4
+ import torch
5
 
6
+ # Load your model and tokenizer from Hugging Face
7
+ model_name = 'redael/model_udc'
8
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
9
+ model = AutoModelForCausalLM.from_pretrained(model_name)
10
 
11
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
12
+ model.to(device)
13
 
14
+ # Function to generate response
15
+ def generate_response(message, history, system_message, max_tokens, temperature, top_p):
16
+ # Prepare the conversation history
 
 
 
 
 
17
  messages = [{"role": "system", "content": system_message}]
18
+
19
+ for user_msg, bot_msg in history:
20
+ if user_msg:
21
+ messages.append({"role": "user", "content": user_msg})
22
+ if bot_msg:
23
+ messages.append({"role": "assistant", "content": bot_msg})
24
+
25
  messages.append({"role": "user", "content": message})
26
+
27
+ # Tokenize and prepare the input
28
+ prompt = "\n".join([f"{msg['role'].capitalize()}: {msg['content']}" for msg in messages])
29
+ inputs = tokenizer(prompt, return_tensors='pt', padding=True, truncation=True, max_length=512).to(device)
30
+
31
+ # Generate the response
32
+ outputs = model.generate(
33
+ inputs['input_ids'],
34
+ max_length=max_tokens,
35
+ num_return_sequences=1,
36
+ pad_token_id=tokenizer.eos_token_id,
37
  temperature=temperature,
38
  top_p=top_p,
39
+ early_stopping=True,
40
+ do_sample=True # Enable sampling
41
+ )
42
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
43
+
44
+ # Clean up the response
45
+ response = response.split("Assistant:")[-1].strip()
46
+ response_lines = response.split('\n')
47
+ clean_response = []
48
+ for line in response_lines:
49
+ if "User:" not in line and "Assistant:" not in line:
50
+ clean_response.append(line)
51
+ response = ' '.join(clean_response)
52
+
53
+ return [(message, response)]
54
 
55
+ # Create the Gradio chat interface
 
 
56
  demo = gr.ChatInterface(
57
+ fn=generate_response,
58
  additional_inputs=[
59
  gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
60
  gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
 
67
  label="Top-p (nucleus sampling)",
68
  ),
69
  ],
70
+ title="Chatbot",
71
+ description="Ask anything to the chatbot."
72
  )
73
 
 
74
  if __name__ == "__main__":
75
  demo.launch()