MrOvkill commited on
Commit
8b482e1
·
1 Parent(s): fe2b226
Files changed (1) hide show
  1. app.py +313 -2
app.py CHANGED
@@ -1,3 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from transformers import AutoTokenizer, AutoModelForCausalLM
2
  import gradio as gr
3
  import spaces
@@ -27,8 +338,8 @@ def moondream2(question, image, history=None):
27
  for itm in history:
28
  ress.append(itm)
29
  ress.append({
30
- "answer": res if question["answer"] is not None and question != "" else None,
31
- "caption": res if question["caption"] is None or question == "" else None,
32
  "sha256": hsh,
33
  "image_b64": b64
34
  })
 
1
+
2
+ """
3
+
4
+ import gradio as gr
5
+ from transformers import AutoTokenizer, AutoModelForCausalLM
6
+ import json
7
+ import torch
8
+ import requests
9
+ import time
10
+ import random
11
+ from PIL import Image
12
+ from typing import Union
13
+ import os
14
+ import base64
15
+ from together import Together
16
+ import pathlib
17
+ import gradio_client as grc
18
+ import spaces
19
+
20
+ global shrd
21
+ shrd = gr.JSON(visible=False)
22
+
23
+ device = "cuda" if torch.cuda.is_available() else "cpu"
24
+ print(f"Using {device}" if device != "cpu" else "Using CPU")
25
+
26
+ def _load_model():
27
+ tokenizer = AutoTokenizer.from_pretrained("vikhyatk/moondream2", trust_remote_code=True, revision="2024-05-08", torch_dtype=(torch.bfloat16 if device == 'cuda' else torch.float32))
28
+ model = AutoModelForCausalLM.from_pretrained("vikhyatk/moondream2", device_map=device, trust_remote_code=True, revision="2024-05-08")
29
+ return (model, tokenizer)
30
+
31
+ class MoonDream():
32
+ def __init__(self, model=None, tokenizer=None):
33
+ self.model, self.tokenizer = (model, tokenizer)
34
+ if not model or model is None or not tokenizer or tokenizer is None:
35
+ self.model, self.tokenizer = _load_model()
36
+ self.device = device
37
+ self.model.to(self.device)
38
+ def __call__(self, question, imgs):
39
+ imn = 0
40
+ for img in imgs:
41
+ img = self.model.encode_image(img)
42
+ res = self.model.answer_question(question=question, image_embeds=img, tokenizer=self.tokenizer)
43
+ yield res
44
+ return
45
+
46
+ md = MoonDream()
47
+
48
+ SYSTEM_PROMPT = "You are Llama 3 70b. You have been given access to Moondream 2 for VQA when given images. When you have a question about an image, simple start your response with the text, '@question\\nMy question?'. When you do this, the request will be sent to Moondream 2. User can see this happening if they turn debug on, so be professional and stay on topic. Any chat from anyone starting with @answer is the answer to last question asked. If something appears out of sync, ask User to clear the chat."
49
+
50
+ @spaces.GPU
51
+ def _respond_one(question, img):
52
+ txt = ""
53
+ yield (txt := txt + MoonDream()(question, [img]))
54
+ return txt
55
+
56
+ def respond_batch(question, **imgs):
57
+ md = MoonDream()
58
+ for img in imgs.values():
59
+ res = md(question, img)
60
+ for r in res:
61
+ yield r
62
+ yield "\n\n\n\n\n\n"
63
+ return
64
+
65
+ def dual_images(img1: Image):
66
+ # Ran once for each img to it's respective output. Output should be detailed str of description/feature extraction/interrogation.
67
+ md = MoonDream()
68
+ res = md("Describe the image in plain english ", [img1])
69
+ txt = ""
70
+ for r in res:
71
+ yield (txt := txt + r)
72
+ return
73
+
74
+ import os
75
+
76
+ def merge_descriptions_to_prompt(mi, d1, d2):
77
+ from together import Together
78
+ tog = Together(api_key=os.getenv("TOGETHER_KEY"))
79
+ res = tog.completions.create(prompt=f""" """Describe what would result if the following two descriptions were describing one thing.
80
+ ### Description 1:
81
+ """ """
82
+ ```text
83
+ {d1}
84
+ ```
85
+ ### Description 2:
86
+ ```text
87
+ {d2}
88
+ ```
89
+ Merge-Specific Instructions:
90
+ ```text
91
+ {mi}
92
+ ```
93
+ Ensure you end your output with ```\\n
94
+ ---
95
+ Complete Description:
96
+ ```text"""
97
+
98
+ """, model="meta-llama/Meta-Llama-3-70B", stop=["```"], max_tokens=1024)
99
+ return res.choices[0].text.split("```")[0]
100
+
101
+ def xform_image_description(img, inst):
102
+ #md = MoonDream()
103
+ from together import Together
104
+ desc = dual_images(img)
105
+ tog = Together(api_key=os.getenv("TOGETHER_KEY"))
106
+ prompt=f""" """Describe the image in aggressively verbose detail. I must know every freckle upon a man's brow and each blade of the grass intimately.\nDescription: ```text\n{desc}\n```\nInstructions:\n```text\n{inst}\n```\n\n\n---\nDetailed Description:\n```text """ """
107
+ res = tog.completions.create(prompt=prompt, model="meta-llama/Meta-Llama-3-70B", stop=["```"], max_tokens=1024)
108
+ return res.choices[0].text[len(prompt):].split("```")[0]
109
+
110
+ def simple_desc(img, prompt):
111
+ import base64
112
+ gen = md(prompt, [img])
113
+ total = ""
114
+ for resp in gen:
115
+ print(total := total + resp)
116
+ img.resize((192,192)).save("tmp.png")
117
+ bts = False
118
+ with open("tmp.png", "rb") as f:
119
+ bts = f.read()
120
+ if bts:
121
+ os.remove("tmp.png")
122
+ res = {
123
+ 'image_b64': base64.b64encode(bts).decode('utf-8'),
124
+ 'description': total,
125
+ }
126
+ cl = grc.Client("http://127.0.0.1:7860/")
127
+ result = cl.predict(
128
+ message="Here's the description of your latest image, repeat any relevant details to keep them in context. Here's the description:\n```text\n" + total + "\n```\n\nAnd what the user wanted to begin with: `" + prompt + "`.",
129
+ api_name="/chat"
130
+ )
131
+ print(result)
132
+ return total, res, {**res, 'chat': result}
133
+
134
+ ifc_imgprompt2text = gr.Interface(simple_desc, inputs=[gr.Image(label="input", type="pil"), gr.Textbox(label="prompt")], outputs=[gr.Textbox(label="description"), gr.JSON(label="json")])
135
+
136
+ def chat(inpt, mess, desc):
137
+ from together import Together
138
+ print(inpt, mess)
139
+ if mess is None:
140
+ mess = []
141
+
142
+ tog = Together(api_key=os.getenv("TOGETHER_KEY"))
143
+ messages = [{
144
+ 'role': 'system',
145
+ 'content': SYSTEM_PROMPT
146
+ }]
147
+ if desc is not None and desc != "":
148
+ messages.append({
149
+ 'role': 'system',
150
+ 'content': 'Here is a description of what you can see at the moment:\n```text\n' + desc + '\n```\nKeep this in mind when answering User\'s questions.'
151
+ })
152
+ messages.append({
153
+ 'role': 'user',
154
+ 'content': inpt
155
+ })
156
+ for cht in mess:
157
+ print(cht)
158
+ res = tog.chat.completions.create(
159
+ messages=messages,
160
+ model="meta-llama/Llama-3-70b-chat-hf", stop=["<|eot_id|>"], stream=True, safety_model="Meta-LLama/Llama-Guard-7b")
161
+ txt = ""
162
+ for pk in res:
163
+ print(pk)
164
+ txt += pk.choices[0].delta.content
165
+ #mess[-1][-2] += pk.choices[0].delta.content
166
+ yield txt #, json.dumps(messages)#mess#, json.dumps(messages)
167
+
168
+ chatbot = gr.Chatbot(
169
+ [
170
+ ["Hello?", "### Greetings\n\nWell, it seems I have a visitor! What can I do for you? &lt3;\n\n---"]
171
+ ],
172
+ elem_id="chatbot",
173
+ bubble_full_width=False,
174
+ sanitize_html=False,
175
+ show_copy_button=True,
176
+ avatar_images=[
177
+ pathlib.Path("image.jpeg"),
178
+ pathlib.Path("image2.jpeg")
179
+ ])
180
+
181
+ wizard_chatbot = gr.Chatbot(
182
+ [
183
+ ["Hello?", "### Greetings\n\nWell, it seems I have a visitor! What can I do for you? &lt3;\n\n---"]
184
+ ],
185
+ elem_id="chatbot_wizard",
186
+ bubble_full_width=True,
187
+ sanitize_html=False,
188
+ show_copy_button=True,
189
+ avatar_images=[
190
+ pathlib.Path("image.png"),
191
+ pathlib.Path("image2.jpeg")
192
+ ]
193
+ )
194
+
195
+ def wizard_chat(inpt, mess):
196
+ from together import Together
197
+ print(inpt, mess)
198
+ if mess is None:
199
+ mess = []
200
+
201
+ tog = Together(api_key=os.getenv("TOGETHER_KEY"))
202
+ messages = []
203
+ messages.append({
204
+ 'role': 'user',
205
+ 'content': "English; Please reply in English. " + inpt
206
+ })
207
+ for cht in mess:
208
+ print(cht)
209
+ res = tog.chat.completions.create(
210
+ messages=messages,
211
+ model="microsoft/WizardLM-2-8x22B", stop=["</s>"], stream=True, safety_model="Meta-LLama/Llama-Guard-7b")
212
+ txt = ""
213
+ for pk in res:
214
+ print(pk)
215
+ txt += pk.choices[0].delta.content
216
+ #mess[-1][-2] += pk.choices[0].delta.content
217
+ yield txt #, json.dumps(messages)#mess#, json.dumps(messages
218
+
219
+ botroom = None
220
+
221
+ def group_chat(room: str, **models):
222
+ wzn = json.loads(wzn)
223
+ lmn = json.loads(lmn)
224
+ print(wzn, lmn)
225
+ if not "replace_token" in wzn:
226
+ wzn["replace_token"] = "<|wizard|>"
227
+ if not "replace_token" in lmn:
228
+ lmn["replace_token"] = "</Llama>"
229
+ while room.find(lmn['replace_token']) != -1 or room.find(wzn['replace_token']) != -1:
230
+ if not "prompt" in wzn and room.find(wzn['replace_token']) != -1:
231
+ wzn["prompt"] = room[0:room.find(wzn['replace_token'])]
232
+ if not "prompt" in lmn and room.find(lmn['replace_token']) != -1:
233
+ lmn["prompt"] = room[0:room.find(lmn['replace_token'])]
234
+ print(wzn, lmn)
235
+ if "prompt" in wzn:
236
+ print(wzn)
237
+ res = wizard_chat(wzn['prompt'], [])
238
+ tx = ""
239
+ for r in res:
240
+ yield cdd + r
241
+ tx = r
242
+ return cdd + txt
243
+ # Let's make a more genetic model-merge with shadow config that has basic sane defaults for any model.
244
+ # top_k 42
245
+ # top_p 0.842
246
+ # max_tokens 1536
247
+ # temperature 0.693
248
+
249
+ shadow_config = {
250
+ "top_k": 42,
251
+ "top_p": 0.842,
252
+ "max_tokens": 1536,
253
+ "temperature": 0.693,
254
+ "repetition_penalty": 1.12
255
+ }
256
+
257
+ #models = {#
258
+
259
+ # }
260
+
261
+ arch_room = None
262
+
263
+ def wizard_complete(cdd, wzs):
264
+ tog = Together(api_key=os.getenv("TOGETHER_KEY"))
265
+ if wzs.startswith("root="):
266
+ wzs = wzs[5:]
267
+ wzs = json.loads(wzs)
268
+ print(wzs)
269
+ if not "stop" in wzs:
270
+ wzs["stop"] = ['###', '\n\n\n', '<|im_end|>', '<|im_start|>']
271
+ if not "model" in wzs:
272
+ wzs["model"] = "WizardLM/WizardCoder-Python-34B-V1.0"
273
+ if not "prompt" in wzs:
274
+ wzs["prompt"] = cdd
275
+ res = tog.completions.create(prompt=wzs["prompt"], model=wzs["model"], stop=wzs["stop"], max_tokens=1024, stream=False)
276
+ txt = cdd + res.choices[0].text
277
+ return txt, txt
278
+
279
+ with gr.Blocks() as arch_room:
280
+ with gr.Row():
281
+ gr.Markdown(f"""
282
+ ## Arcanistry
283
+
284
+ """
285
+ *POOF* -- You walk in, to a cloudy room filled with heavy smoke. In the center of the room rests a waist-height table. Upon the table, you see a... You don't understand... It's dark and light and cold and warm but... As you extend your hand, you hear the voice travel up your arm and into your ears...
286
+
287
+ ---
288
+ """ """)
289
+ with gr.Row():
290
+ cdd = gr.Code(""" """### Human
291
+ I require a Python script that serves a simple file server in Python over MongoDB.
292
+
293
+ ### Wizard
294
+ Sure! Here's the script:
295
+ ```python""" """, language="markdown")
296
+ with gr.Row():
297
+ wzs = gr.Code(json.dumps({
298
+ 'token': '<|wizard|>',
299
+ 'model': 'WizardLM/WizardCoder-Python-34B-V1.0',
300
+ 'stop': ['###', '\n\n\n', '<|im_end|>', '<|im_start|>']
301
+ }))
302
+ with gr.Row():
303
+ rnd = gr.Markdown("")
304
+ with gr.Row():
305
+ subm_prompt = gr.Button("Run Prompt")
306
+ subm_prompt.click(wizard_complete, inputs=[cdd, wzs], outputs=[cdd, rnd])
307
+
308
+ with gr.TabbedInterface([ifc_imgprompt2text, c_ifc := gr.ChatInterface(chat, chatbot=chatbot, submit_btn=gr.Button(scale=1)), gr.ChatInterface(wizard_chat), arch_room], ["Prompt & Image 2 Text", "Chat w/ Llama 3 70b", "Chat w/ WizardLM 8x22B", "Arcanistry"]) as ifc:
309
+ shrd = gr.JSON(visible=False)
310
+ ifc.launch(share=False, debug=True, show_error=True) """
311
+
312
  from transformers import AutoTokenizer, AutoModelForCausalLM
313
  import gradio as gr
314
  import spaces
 
338
  for itm in history:
339
  ress.append(itm)
340
  ress.append({
341
+ "answer": res["answer"] if question is not None and question != "" else None,
342
+ "caption": res["caption"] if question is None or question == "" else None,
343
  "sha256": hsh,
344
  "image_b64": b64
345
  })