beyoru commited on
Commit
ead29d0
·
verified ·
1 Parent(s): 9680c53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -72
app.py CHANGED
@@ -1,84 +1,90 @@
1
  import gradio as gr
2
- from PIL import Image
3
  import torch
4
- from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
5
- import requests
6
 
7
- # Load the model and processor
8
- model = Qwen2VLForConditionalGeneration.from_pretrained(
9
- "Qwen/Qwen2-VL-2B-Instruct", torch_dtype="auto",
10
- )
11
- processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct")
12
 
13
- # Process text and image for inference
14
- def generate_response(messages: list):
15
- # Preprocess conversation (text + image)
16
- text_prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
17
-
18
- # Prepare input tensors
19
- images = [msg.get("image") for msg in messages if msg.get("image")]
20
- text = [text_prompt]
21
-
22
- inputs = processor(
23
- text=text, images=images, padding=True, return_tensors="pt"
24
- )
25
 
26
- # Inference: Generate the output
27
- output_ids = model.generate(**inputs, max_new_tokens=128)
28
- generated_ids = [
29
- output_ids[len(input_ids) :]
30
- for input_ids, output_ids in zip(inputs.input_ids, output_ids)
31
- ]
32
- output_text = processor.batch_decode(
33
- generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True
34
- )
35
-
36
- return output_text[0]
37
 
38
- # Gradio chat interface function
39
- def chat_interface(user_input, image: Image = None, history=[]):
40
- # Add user input to the history
41
- if image:
42
- message = {
43
- "role": "user",
44
- "content": [{"type": "image", "image": image}, {"type": "text", "text": user_input}],
45
- }
46
- else:
47
- message = {
48
- "role": "user",
49
- "content": [{"type": "text", "text": user_input}],
50
- }
51
- history.append(message)
52
 
53
- # Get model response
54
- response = generate_response(history)
55
-
56
- # Add model response to the history
57
- history.append({"role": "assistant", "content": [{"type": "text", "text": response}]})
 
 
 
 
 
 
 
 
 
58
 
59
- return history, response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
- # Gradio chat interface setup
62
- def create_gradio_interface():
63
- # Chat interface with image upload and text input
64
- interface = gr.Interface(
65
- fn=chat_interface,
66
- inputs=[
67
- gr.Textbox(type="text", label="Your Message"),
68
- gr.Image(type="pil", label="Upload an Image", optional=True)
69
- ],
70
- outputs=[
71
- gr.Chatbot(label="Chatbot"),
72
- gr.Textbox(label="Model's Response")
73
- ],
74
- title="Chat with Vision Model",
75
- description="This is a multimodal model where you can chat with it using both images and text inputs. The model will respond accordingly based on your input.",
76
- allow_flagging="never"
77
- )
78
 
79
- return interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- # Run the Gradio app
82
  if __name__ == "__main__":
83
- interface = create_gradio_interface()
84
- interface.launch()
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
  import torch
4
+ import numpy as np
5
+ import string
6
 
7
+ # Load tokenizer and model for EOU detection
8
+ tokenizer = AutoTokenizer.from_pretrained("livekit/turn-detector")
9
+ model = AutoModelForCausalLM.from_pretrained("livekit/turn-detector")
 
 
10
 
11
+ # Define function to calculate softmax
12
+ def _softmax(logits: np.ndarray) -> np.ndarray:
13
+ exp_logits = np.exp(logits - np.max(logits))
14
+ return exp_logits / np.sum(exp_logits)
 
 
 
 
 
 
 
 
15
 
16
+ # Define the EOU probability calculation
17
+ def get_eou_probability(chat_ctx: list) -> float:
18
+ """Calculate the probability of End of Utterance (EOU)"""
19
+ # Normalize and prepare the chat context
20
+ text = " ".join([msg["content"] for msg in chat_ctx])
21
+ inputs = tokenizer(text, return_tensors="pt", max_length=512, truncation=True)
 
 
 
 
 
22
 
23
+ # Run the model and get the logits
24
+ with torch.no_grad():
25
+ outputs = model(**inputs)
26
+ logits = outputs.logits[0, -1, :] # Get logits of the last token
27
+ probs = _softmax(logits.numpy()) # Convert logits to probabilities
 
 
 
 
 
 
 
 
 
28
 
29
+ # Assuming <|im_end|> token corresponds to EOU, get the probability of that token
30
+ eou_token_id = tokenizer.encode("<|im_end|>")[-1]
31
+ return probs[eou_token_id]
32
+
33
+ # Define the main response function for Gradio
34
+ def respond(
35
+ message,
36
+ history: list[tuple[str, str]],
37
+ system_message,
38
+ max_tokens,
39
+ temperature,
40
+ top_p,
41
+ ):
42
+ messages = [{"role": "system", "content": system_message}]
43
 
44
+ for val in history:
45
+ if val[0]:
46
+ messages.append({"role": "user", "content": val[0]})
47
+ if val[1]:
48
+ messages.append({"role": "assistant", "content": val[1]})
49
+
50
+ messages.append({"role": "user", "content": message})
51
+
52
+ # Get the response from the Qwen model (e.g., for conversation generation)
53
+ response = ""
54
+ for message in client.chat_completion(
55
+ messages,
56
+ max_tokens=max_tokens,
57
+ stream=True,
58
+ temperature=temperature,
59
+ top_p=top_p,
60
+ ):
61
+ token = message.choices[0].delta.content
62
+ response += token
63
+ yield response
64
 
65
+ # After generating the response, get the EOU probability
66
+ eou_probability = get_eou_probability(messages) # Get EOU prediction
67
+ print(f"EOU Probability: {eou_probability}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
+ # Include the EOU probability in the output
70
+ yield f"\nEOU Probability: {eou_probability:.2f}"
71
+
72
+ # Gradio interface setup
73
+ demo = gr.ChatInterface(
74
+ respond,
75
+ additional_inputs=[
76
+ gr.Textbox(value="Bạn là một trợ lý ảo", label="System message"),
77
+ gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
78
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
79
+ gr.Slider(
80
+ minimum=0.1,
81
+ maximum=1.0,
82
+ value=0.95,
83
+ step=0.05,
84
+ label="Top-p (nucleus sampling)",
85
+ ),
86
+ ],
87
+ )
88
 
 
89
  if __name__ == "__main__":
90
+ demo.launch()