redael commited on
Commit
d17fd79
·
verified ·
1 Parent(s): 3959fe9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -56
app.py CHANGED
@@ -1,68 +1,64 @@
1
  import os
2
  os.system('sh setup.sh')
3
  import gradio as gr
4
- from huggingface_hub import InferenceClient
5
-
6
- """
7
- 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
8
- """
9
- import os
10
- os.system('sh setup.sh')
11
-
12
- client = InferenceClient("redael/model_udc")
13
 
 
 
 
 
14
 
15
- def respond(
16
- message,
17
- history: list[tuple[str, str]],
18
- system_message,
19
- max_tokens,
20
- temperature,
21
- top_p,
22
- ):
23
- messages = [{"role": "system", "content": system_message}]
24
 
25
- for val in history:
26
- if val[0]:
27
- messages.append({"role": "user", "content": val[0]})
28
- if val[1]:
29
- messages.append({"role": "assistant", "content": val[1]})
30
-
31
- messages.append({"role": "user", "content": message})
32
-
33
- response = ""
34
-
35
- for message in client.chat_completion(
36
- messages,
37
- max_tokens=max_tokens,
38
- stream=True,
39
  temperature=temperature,
40
  top_p=top_p,
41
- ):
42
- token = message.choices[0].delta.content
43
-
44
- response += token
45
- yield response
 
 
 
 
 
 
 
 
 
46
 
47
- """
48
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
49
- """
50
- demo = gr.ChatInterface(
51
- respond,
52
- additional_inputs=[
53
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
54
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
55
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
56
- gr.Slider(
57
- minimum=0.1,
58
- maximum=1.0,
59
- value=0.95,
60
- step=0.05,
61
- label="Top-p (nucleus sampling)",
62
- ),
63
- ],
64
- )
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  if __name__ == "__main__":
68
- demo.launch()
 
1
  import os
2
  os.system('sh setup.sh')
3
  import gradio as gr
4
+ import torch
5
+ from transformers import GPT2LMHeadModel, GPT2Tokenizer
 
 
 
 
 
 
 
6
 
7
+ # Load the model and tokenizer
8
+ model_path = "final_model"
9
+ tokenizer = GPT2Tokenizer.from_pretrained(model_path)
10
+ model = GPT2LMHeadModel.from_pretrained(model_path)
11
 
12
+ # Check if CUDA is available and use GPU if possible
13
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
14
+ model.to(device)
 
 
 
 
 
 
15
 
16
+ def generate_response(prompt, model, tokenizer, max_length=100, num_beams=5, temperature=0.5, top_p=0.9, repetition_penalty=4.0):
17
+ # Prepare the prompt
18
+ prompt = f"User: {prompt}\nAssistant:"
19
+ inputs = tokenizer(prompt, return_tensors='pt', padding=True, truncation=True, max_length=512).to(device)
20
+ outputs = model.generate(
21
+ inputs['input_ids'],
22
+ max_length=max_length,
23
+ num_return_sequences=1,
24
+ pad_token_id=tokenizer.eos_token_id,
25
+ num_beams=num_beams,
 
 
 
 
26
  temperature=temperature,
27
  top_p=top_p,
28
+ repetition_penalty=repetition_penalty,
29
+ early_stopping=True
30
+ )
31
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
32
+
33
+ # Post-processing to clean up the response
34
+ response = response.split("Assistant:")[-1].strip()
35
+ response_lines = response.split('\n')
36
+ clean_response = []
37
+ for line in response_lines:
38
+ if "User:" not in line and "Assistant:" not in line:
39
+ clean_response.append(line)
40
+ response = ' '.join(clean_response)
41
+ return response.strip()
42
 
43
+ def chat_interface(user_input, history):
44
+ response = generate_response(user_input, model, tokenizer)
45
+ history.append((user_input, response))
46
+ return history, history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ with gr.Blocks() as demo:
49
+ gr.Markdown("# Chatbot using GPT")
50
+
51
+ chatbot = gr.Chatbot()
52
+ message = gr.Textbox(placeholder="Type your question here...")
53
+ state = gr.State([])
54
+
55
+ with gr.Row():
56
+ clear = gr.Button("Clear")
57
+ submit = gr.Button("Send")
58
+
59
+ submit.click(chat_interface, [message, state], [chatbot, state])
60
+ clear.click(lambda: None, None, chatbot)
61
+ clear.click(lambda: [], None, state)
62
 
63
  if __name__ == "__main__":
64
+ demo.launch()