Xkev commited on
Commit
d710af7
1 Parent(s): bfdc60d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -54
app.py CHANGED
@@ -1,64 +1,88 @@
 
 
 
 
 
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
+ from transformers import MllamaForConditionalGeneration, AutoProcessor, TextIteratorStreamer
2
+ from PIL import Image
3
+ import requests
4
+ import torch
5
+ from threading import Thread
6
  import gradio as gr
7
+ from gradio import FileData
8
+ import time
9
+ import spaces
10
+ ckpt = "Xkev/Llama-3.2V-11B-cot"
11
+ model = MllamaForConditionalGeneration.from_pretrained(ckpt,
12
+ torch_dtype=torch.bfloat16).to("cuda")
13
+ processor = AutoProcessor.from_pretrained(ckpt)
14
 
 
 
 
 
15
 
16
+ @spaces.GPU
17
+ def bot_streaming(message, history, max_new_tokens=250):
18
+
19
+ txt = message["text"]
20
+ ext_buffer = f"{txt}"
21
+
22
+ messages= []
23
+ images = []
24
+
25
 
26
+ for i, msg in enumerate(history):
27
+ if isinstance(msg[0], tuple):
28
+ messages.append({"role": "user", "content": [{"type": "text", "text": history[i+1][0]}, {"type": "image"}]})
29
+ messages.append({"role": "assistant", "content": [{"type": "text", "text": history[i+1][1]}]})
30
+ images.append(Image.open(msg[0][0]).convert("RGB"))
31
+ elif isinstance(history[i-1], tuple) and isinstance(msg[0], str):
32
+ # messages are already handled
33
+ pass
34
+ elif isinstance(history[i-1][0], str) and isinstance(msg[0], str): # text only turn
35
+ messages.append({"role": "user", "content": [{"type": "text", "text": msg[0]}]})
36
+ messages.append({"role": "assistant", "content": [{"type": "text", "text": msg[1]}]})
37
 
38
+ # add current message
39
+ if len(message["files"]) == 1:
40
+
41
+ if isinstance(message["files"][0], str): # examples
42
+ image = Image.open(message["files"][0]).convert("RGB")
43
+ else: # regular input
44
+ image = Image.open(message["files"][0]["path"]).convert("RGB")
45
+ images.append(image)
46
+ messages.append({"role": "user", "content": [{"type": "text", "text": txt}, {"type": "image"}]})
47
+ else:
48
+ messages.append({"role": "user", "content": [{"type": "text", "text": txt}]})
49
 
 
50
 
51
+ texts = processor.apply_chat_template(messages, add_generation_prompt=True)
52
 
53
+ if images == []:
54
+ inputs = processor(text=texts, return_tensors="pt").to("cuda")
55
+ else:
56
+ inputs = processor(text=texts, images=images, return_tensors="pt").to("cuda")
57
+
58
+ generation_kwargs = dict(inputs, max_new_tokens=max_new_tokens)
59
+ generated_text = ""
60
+
61
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
62
+ thread.start()
63
+ buffer = ""
64
+
65
+ for new_text in streamer:
66
+ buffer += new_text
67
+ generated_text_without_prompt = buffer
68
+ time.sleep(0.01)
69
+ yield buffer
70
 
 
 
71
 
72
+ demo = gr.ChatInterface(fn=bot_streaming, title="LLaVA-CoT",
73
+ textbox=gr.MultimodalTextbox(),
74
+ additional_inputs = [gr.Slider(
75
+ minimum=512,
76
+ maximum=1024,
77
+ value=512,
78
+ step=1,
79
+ label="Maximum number of new tokens to generate",
80
+ )
81
+ ],
82
+ cache_examples=False,
83
+ description="Upload an image, and start chatting about it. To learn more about LLaVA-CoT, visit [oir GitHub page](https://github.com/PKU-YuanGroup/LLaVA-CoT). ",
84
+ stop_btn="Stop Generation",
85
+ fill_height=True,
86
+ multimodal=True)
87
+
88
+ demo.launch(debug=True)