Nithish310 commited on
Commit
5a8275a
·
verified ·
1 Parent(s): a094aa3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +120 -125
app.py CHANGED
@@ -16,25 +16,29 @@ from gradio_client import Client, file
16
 
17
  def image_gen(prompt):
18
  client = Client("KingNish/Image-Gen-Pro")
19
- return client.predict("Image Generation", None, prompt, api_name="/image_gen_pro")
20
 
21
  model_id = "llava-hf/llava-interleave-qwen-0.5b-hf"
 
22
  processor = LlavaProcessor.from_pretrained(model_id)
 
23
  model = LlavaForConditionalGeneration.from_pretrained(model_id)
24
  model.to("cpu")
25
 
 
26
  def llava(message, history):
27
  if message["files"]:
28
  image = message["files"][0]
29
  else:
30
  for hist in history:
31
- if type(hist[0]) == tuple:
32
  image = hist[0][0]
33
 
34
  txt = message["text"]
35
 
 
36
  image = Image.open(image).convert("RGB")
37
- prompt = f"user <image>\n{txt}assistant"
38
 
39
  inputs = processor(prompt, image, return_tensors="pt")
40
  return inputs
@@ -85,132 +89,123 @@ client_yi = InferenceClient("01-ai/Yi-1.5-34B-Chat")
85
  def respond(message, history):
86
  func_caller = []
87
 
88
- if isinstance(message, dict):
89
- user_prompt = message
90
- if "files" in message and message["files"]:
91
- inputs = llava(message, history)
92
- streamer = TextIteratorStreamer(None, skip_prompt=True, **{"skip_special_tokens": True})
93
- generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)
94
-
95
- thread = Thread(target=None.generate, kwargs=generation_kwargs) # Replace None with actual model
96
- thread.start()
97
-
98
- buffer = ""
99
- for new_text in streamer:
100
- buffer += new_text
101
- yield buffer
102
- else:
103
- functions_metadata = [
104
- {"type": "function", "function": {"name": "web_search", "description": "Search query on google", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "web search query"}}, "required": ["query"]}}},
105
- {"type": "function", "function": {"name": "general_query", "description": "Reply general query of USER", "parameters": {"type": "object", "properties": {"prompt": {"type": "string", "description": "A detailed prompt"}}, "required": ["prompt"]}}},
106
- {"type": "function", "function": {"name": "image_generation", "description": "Generate image for user", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "image generation prompt"}}, "required": ["query"]}}},
107
- {"type": "function", "function": {"name": "image_qna", "description": "Answer question asked by user related to image", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "Question by user"}}, "required": ["query"]}}},
108
- ]
109
-
110
- for msg in history:
111
- func_caller.append({"role": "user", "content": f"{str(msg[0])}"})
112
- func_caller.append({"role": "assistant", "content": f"{str(msg[1])}"})
113
 
114
- message_text = message["text"]
115
- func_caller.append({"role": "user", "content": f'[SYSTEM]You are a helpful assistant. You have access to the following functions: \n {str(functions_metadata)}\n\nTo use these functions respond with:\n<functioncall> {{ "name": "function_name", "arguments": {{ "arg_1": "value_1", "arg_1": "value_1", ... }} }} </functioncall> [USER] {message_text}'})
116
-
117
- response = None.chat_completion(func_caller, max_tokens=200) # Replace None with actual model
118
- response = str(response)
119
- try:
120
- response = response[int(response.find("{")):int(response.rindex("</"))]
121
- except:
122
- response = response[int(response.find("{")):(int(response.rfind("}"))+1)]
123
- response = response.replace("\\n", "")
124
- response = response.replace("\\'", "'")
125
- response = response.replace('\\"', '"')
126
- response = response.replace('\\', '')
127
- print(f"\n{response}")
128
-
129
- try:
130
- json_data = json.loads(str(response))
131
- if json_data["name"] == "web_search":
132
- query = json_data["arguments"]["query"]
133
- yield "Searching Web"
134
- web_results = search(query)
135
- yield "Extracting relevant Info"
136
- web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
137
- messages = f"system\nYou are OpenCHAT mini a helpful assistant made by Nithish. You are provided with WEB results from which you can find informations to answer users query in Structured and More better way. You do not say Unnecesarry things Only say thing which is important and relevant. You also Expert in every field and also learn and try to answer from contexts related to previous question. Try your best to give best response possible to user. You also try to show emotions using Emojis and reply like human, use short forms, friendly tone and emotions."
138
- for msg in history:
139
- messages += f"\nuser\n{str(msg[0])}"
140
- messages += f"\nassistant\n{str(msg[1])}"
141
- messages+=f"\nuser\n{message_text}\nweb_result\n{web2}\nassistant\n"
142
- stream = None.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False) # Replace None with actual model
143
- output = ""
144
- for response in stream:
145
- if not response.token.text == "":
146
- output += response.token.text
147
- yield output
148
- elif json_data["name"] == "image_generation":
149
- query = json_data["arguments"]["query"]
150
- yield "Generating Image, Please wait 10 sec..."
151
- try:
152
- image = image_gen(f"{str(query)}")
153
- yield gr.Image(image[1])
154
- except:
155
- client_sd3 = None.InferenceClient("stabilityai/stable-diffusion-3-medium-diffusers") # Replace None with actual model
156
- seed = random.randint(0, 999999)
157
- image = client_sd3.text_to_image(query, negative_prompt=f"{seed}")
158
- yield gr.Image(image)
159
- elif json_data["name"] == "image_qna":
160
- if "files" in message:
161
- image = message["files"][0]
162
- else:
163
- for hist in history:
164
- if type(hist[0]) == tuple:
165
- image = hist[0][0]
166
-
167
- txt = json_data["arguments"]["query"]
168
-
169
- image = Image.open(image).convert("RGB")
170
- prompt = f"user <image>\n{txt}assistant"
171
-
172
- inputs = None(prompt, image, return_tensors="pt") # Replace None with actual model
173
- streamer = TextIteratorStreamer(None, skip_prompt=True, **{"skip_special_tokens": True})
174
- generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)
175
-
176
- thread = Thread(target=None.generate, kwargs=generation_kwargs) # Replace None with actual model
177
- thread.start()
178
-
179
- buffer = ""
180
- for new_text in streamer:
181
- buffer += new_text
182
- yield buffer
183
- except:
184
- messages = ""
185
  for msg in history:
186
- messages += f"\nuser\n{str(msg[0])}"
187
- messages += f"\nassistant\n{str(msg[1])}"
188
- messages += f"\nuser\n{str(message)}"
189
- stream = None.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False) # Replace None with actual model
190
  output = ""
191
  for response in stream:
192
- if not response.token.text == "":
193
  output += response.token.text
194
  yield output
195
- else:
196
- yield "Error: Message format is incorrect."
197
-
198
- # Interface Layout
199
- with gr.Blocks() as demo:
200
- chatbot = gr.Chatbot(label="ChatGPT Style Chatbot", height=500)
201
-
202
- with gr.Row():
203
- upload_button = gr.File(label="Upload File", elem_id="upload-button")
204
- with gr.Column(scale=8):
205
- text_input = gr.Textbox(label="", placeholder="Type your message here...", lines=1)
206
- submit_button = gr.Button("Send")
207
-
208
- def update_chat(message, history):
209
- return chatbot.update(respond(message, history))
210
-
211
- text_input.submit(update_chat, inputs=[text_input, chatbot], outputs=chatbot)
212
- submit_button.click(update_chat, inputs=[text_input, chatbot], outputs=chatbot)
213
- upload_button.change(lambda file: {"text": "", "files": [file]}, inputs=upload_button, outputs=text_input)
214
-
215
- # Run the demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  demo.launch()
 
16
 
17
  def image_gen(prompt):
18
  client = Client("KingNish/Image-Gen-Pro")
19
+ return client.predict("Image Generation",None, prompt, api_name="/image_gen_pro")
20
 
21
  model_id = "llava-hf/llava-interleave-qwen-0.5b-hf"
22
+
23
  processor = LlavaProcessor.from_pretrained(model_id)
24
+
25
  model = LlavaForConditionalGeneration.from_pretrained(model_id)
26
  model.to("cpu")
27
 
28
+
29
  def llava(message, history):
30
  if message["files"]:
31
  image = message["files"][0]
32
  else:
33
  for hist in history:
34
+ if type(hist[0])==tuple:
35
  image = hist[0][0]
36
 
37
  txt = message["text"]
38
 
39
+ gr.Info("Analyzing image")
40
  image = Image.open(image).convert("RGB")
41
+ prompt = f"<|im_start|>user <image>\n{txt}<|im_start|>assistant"
42
 
43
  inputs = processor(prompt, image, return_tensors="pt")
44
  return inputs
 
89
  def respond(message, history):
90
  func_caller = []
91
 
92
+ user_prompt = message
93
+ # Handle image processing
94
+ if message["files"]:
95
+ inputs = llava(message, history)
96
+ streamer = TextIteratorStreamer(processor, skip_prompt=True, **{"skip_special_tokens": True})
97
+ generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
100
+ thread.start()
101
+
102
+ buffer = ""
103
+ for new_text in streamer:
104
+ buffer += new_text
105
+ yield buffer
106
+ else:
107
+ functions_metadata = [
108
+ {"type": "function", "function": {"name": "web_search", "description": "Search query on google", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "web search query"}}, "required": ["query"]}}},
109
+ {"type": "function", "function": {"name": "general_query", "description": "Reply general query of USER", "parameters": {"type": "object", "properties": {"prompt": {"type": "string", "description": "A detailed prompt"}}, "required": ["prompt"]}}},
110
+ {"type": "function", "function": {"name": "image_generation", "description": "Generate image for user", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "image generation prompt"}}, "required": ["query"]}}},
111
+ {"type": "function", "function": {"name": "image_qna", "description": "Answer question asked by user related to image", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "Question by user"}}, "required": ["query"]}}},
112
+ ]
113
+
114
+ for msg in history:
115
+ func_caller.append({"role": "user", "content": f"{str(msg[0])}"})
116
+ func_caller.append({"role": "assistant", "content": f"{str(msg[1])}"})
117
+
118
+ message_text = message["text"]
119
+ func_caller.append({"role": "user", "content": f'[SYSTEM]You are a helpful assistant. You have access to the following functions: \n {str(functions_metadata)}\n\nTo use these functions respond with:\n<functioncall> {{ "name": "function_name", "arguments": {{ "arg_1": "value_1", "arg_1": "value_1", ... }} }} </functioncall> [USER] {message_text}'})
120
+
121
+ response = client_gemma.chat_completion(func_caller, max_tokens=200)
122
+ response = str(response)
123
+ try:
124
+ response = response[int(response.find("{")):int(response.rindex("</"))]
125
+ except:
126
+ response = response[int(response.find("{")):(int(response.rfind("}"))+1)]
127
+ response = response.replace("\\n", "")
128
+ response = response.replace("\\'", "'")
129
+ response = response.replace('\\"', '"')
130
+ response = response.replace('\\', '')
131
+ print(f"\n{response}")
132
+
133
+ try:
134
+ json_data = json.loads(str(response))
135
+ if json_data["name"] == "web_search":
136
+ query = json_data["arguments"]["query"]
137
+ gr.Info("Searching Web")
138
+ web_results = search(query)
139
+ gr.Info("Extracting relevant Info")
140
+ web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
141
+ messages = f"<|im_start|>system\nYou are OpenCHAT mini a helpful assistant made by Nithish. You are provided with WEB results from which you can find informations to answer users query in Structured and More better way. You do not say Unnecesarry things Only say thing which is important and relevant. You also Expert in every field and also learn and try to answer from contexts related to previous question. Try your best to give best response possible to user. You also try to show emotions using Emojis and reply like human, use short forms, friendly tone and emotions.<|im_end|>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
  for msg in history:
143
+ messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
144
+ messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
145
+ messages+=f"\n<|im_start|>user\n{message_text}<|im_end|>\n<|im_start|>web_result\n{web2}<|im_end|>\n<|im_start|>assistant\n"
146
+ stream = client_mixtral.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False)
147
  output = ""
148
  for response in stream:
149
+ if not response.token.text == "<|im_end|>":
150
  output += response.token.text
151
  yield output
152
+ elif json_data["name"] == "image_generation":
153
+ query = json_data["arguments"]["query"]
154
+ gr.Info("Generating Image, Please wait 10 sec...")
155
+ yield "Generating Image, Please wait 10 sec..."
156
+ try:
157
+ image = image_gen(f"{str(query)}")
158
+ yield gr.Image(image[1])
159
+ except:
160
+ client_sd3 = InferenceClient("stabilityai/stable-diffusion-3-medium-diffusers")
161
+ seed = random.randint(0,999999)
162
+ image = client_sd3.text_to_image(query, negative_prompt=f"{seed}")
163
+ yield gr.Image(image)
164
+ elif json_data["name"] == "image_qna":
165
+ inputs = llava(message, history)
166
+ streamer = TextIteratorStreamer(processor, skip_prompt=True, **{"skip_special_tokens": True})
167
+ generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)
168
+
169
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
170
+ thread.start()
171
+
172
+ buffer = ""
173
+ for new_text in streamer:
174
+ buffer += new_text
175
+ yield buffer
176
+ else:
177
+ messages = f"<|im_start|>system\nYou are OpenCHAT mini a helpful assistant made by Nithish. You answers users query like human friend. You are also Expert in every field and also learn and try to answer from contexts related to previous question. Try your best to give best response possible to user. You also try to show emotions using Emojis only in required case and reply like human, use short forms, friendly tone and emotions.<|im_end|>"
178
+ for msg in history:
179
+ messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
180
+ messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
181
+ messages+=f"\n<|im_start|>user\n{message_text}<|im_end|>\n<|im_start|>assistant\n"
182
+ stream = client_yi.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False)
183
+ output = ""
184
+ for response in stream:
185
+ if not response.token.text == "<|endoftext|>":
186
+ output += response.token.text
187
+ yield output
188
+ except:
189
+ messages = f"<|start_header_id|>system\nYou are OpenCHAT mini a helpful assistant made by Nithish. You answers users query like human friend. You are also Expert in every field and also learn and try to answer from contexts related to previous question. Try your best to give best response possible to user. You also try to show emotions using Emojis only in required case and reply like human, use short forms, friendly tone and emotions.<|end_header_id|>"
190
+ for msg in history:
191
+ messages += f"\n<|start_header_id|>user\n{str(msg[0])}<|end_header_id|>"
192
+ messages += f"\n<|start_header_id|>assistant\n{str(msg[1])}<|end_header_id|>"
193
+ messages+=f"\n<|start_header_id|>user\n{message_text}<|end_header_id|>\n<|start_header_id|>assistant\n"
194
+ stream = client_llama.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False)
195
+ output = ""
196
+ for response in stream:
197
+ if not response.token.text == "<|eot_id|>":
198
+ output += response.token.text
199
+ yield output
200
+
201
+ # Create the Gradio interface
202
+ demo = gr.ChatInterface(
203
+ fn=respond,
204
+ chatbot=gr.Chatbot(show_copy_button=True, likeable=True, layout="panel"),
205
+ description ="# OpenGPT 4o \n ### chat, generate images, perform web searches, and Q&A with images.",
206
+ textbox=gr.MultimodalTextbox(),
207
+ multimodal=True,
208
+ concurrency_limit=200,
209
+ cache_examples=False,
210
+ )
211
  demo.launch()