Neha100877 commited on
Commit
22e82e8
Β·
verified Β·
1 Parent(s): 869b321

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -50
app.py CHANGED
@@ -1,64 +1,126 @@
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
+ import spaces
3
+ from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
4
+ from qwen_vl_utils import process_vision_info
5
+ import torch
6
+ from PIL import Image
7
+ import subprocess
8
+ from datetime import datetime
9
+ import numpy as np
10
+ import os
11
 
 
 
 
 
12
 
13
+ # subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
14
 
15
+ # models = {
16
+ # "Qwen/Qwen2-VL-7B-Instruct": AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", trust_remote_code=True, torch_dtype="auto", _attn_implementation="flash_attention_2").cuda().eval()
 
 
 
 
 
 
 
17
 
18
+ # }
19
+ def array_to_image_path(image_array):
20
+ if image_array is None:
21
+ raise ValueError("No image provided. Please upload an image before submitting.")
22
+ # Convert numpy array to PIL Image
23
+ img = Image.fromarray(np.uint8(image_array))
24
+
25
+ # Generate a unique filename using timestamp
26
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
27
+ filename = f"image_{timestamp}.png"
28
+
29
+ # Save the image
30
+ img.save(filename)
31
+
32
+ # Get the full path of the saved image
33
+ full_path = os.path.abspath(filename)
34
+
35
+ return full_path
36
+
37
+ models = {
38
+ "Qwen/Qwen2-VL-7B-Instruct": Qwen2VLForConditionalGeneration.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", trust_remote_code=True, torch_dtype="auto").cuda().eval()
39
 
40
+ }
41
 
42
+ processors = {
43
+ "Qwen/Qwen2-VL-7B-Instruct": AutoProcessor.from_pretrained("Qwen/Qwen2-VL-7B-Instruct", trust_remote_code=True)
44
+ }
45
 
46
+ DESCRIPTION = "[Qwen2-VL-7B Demo](https://huggingface.co/Qwen/Qwen2-VL-7B-Instruct)"
 
 
 
 
 
 
 
47
 
48
+ kwargs = {}
49
+ kwargs['torch_dtype'] = torch.bfloat16
50
 
51
+ user_prompt = '<|user|>\n'
52
+ assistant_prompt = '<|assistant|>\n'
53
+ prompt_suffix = "<|end|>\n"
54
 
55
+ @spaces.GPU
56
+ def run_example(image, text_input=None, model_id="Qwen/Qwen2-VL-7B-Instruct"):
57
+ image_path = array_to_image_path(image)
58
+
59
+ print(image_path)
60
+ model = models[model_id]
61
+ processor = processors[model_id]
62
+
63
+ prompt = f"{user_prompt}<|image_1|>\n{text_input}{prompt_suffix}{assistant_prompt}"
64
+ image = Image.fromarray(image).convert("RGB")
65
+ messages = [
66
+ {
67
+ "role": "user",
68
+ "content": [
69
+ {
70
+ "type": "image",
71
+ "image": image_path,
72
+ },
73
+ {"type": "text", "text": text_input},
74
+ ],
75
+ }
76
+ ]
77
+
78
+ # Preparation for inference
79
+ text = processor.apply_chat_template(
80
+ messages, tokenize=False, add_generation_prompt=True
81
+ )
82
+ image_inputs, video_inputs = process_vision_info(messages)
83
+ inputs = processor(
84
+ text=[text],
85
+ images=image_inputs,
86
+ videos=video_inputs,
87
+ padding=True,
88
+ return_tensors="pt",
89
+ )
90
+ inputs = inputs.to("cuda")
91
+
92
+ # Inference: Generation of the output
93
+ generated_ids = model.generate(**inputs, max_new_tokens=1024)
94
+ generated_ids_trimmed = [
95
+ out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
96
+ ]
97
+ output_text = processor.batch_decode(
98
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
99
+ )
100
+
101
+ return output_text[0]
102
+
103
+ css = """
104
+ #output {
105
+ height: 500px;
106
+ overflow: auto;
107
+ border: 1px solid #ccc;
108
+ }
109
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
+ with gr.Blocks(css=css) as demo:
112
+ gr.Markdown(DESCRIPTION)
113
+ with gr.Tab(label="Qwen2-VL-7B Input"):
114
+ with gr.Row():
115
+ with gr.Column():
116
+ input_img = gr.Image(label="Input Picture")
117
+ model_selector = gr.Dropdown(choices=list(models.keys()), label="Model", value="Qwen/Qwen2-VL-7B-Instruct")
118
+ text_input = gr.Textbox(label="Question")
119
+ submit_btn = gr.Button(value="Submit")
120
+ with gr.Column():
121
+ output_text = gr.Textbox(label="Output Text")
122
+
123
+ submit_btn.click(run_example, [input_img, text_input, model_selector], [output_text])
124
 
125
+ demo.queue(api_open=False)
126
+ demo.launch(debug=True)