prithivMLmods commited on
Commit
fd2037f
·
verified ·
1 Parent(s): 5e87250

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -126
app.py CHANGED
@@ -14,35 +14,6 @@ import torch
14
  import cv2
15
  from gradio_client import Client, file
16
 
17
- def image_gen(prompt):
18
- client = Client("prithivMLmods/IMAGINEO-4K")
19
- return client.predict("Image Generation",None, prompt, api_name="/imagineo_4k")
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_end|><|im_start|>assistant"
42
-
43
- inputs = processor(prompt, image, return_tensors="pt")
44
- return inputs
45
-
46
  def extract_text_from_webpage(html_content):
47
  soup = BeautifulSoup(html_content, 'html.parser')
48
  for tag in soup(["script", "style", "header", "footer"]):
@@ -92,113 +63,72 @@ def respond(message, history):
92
  func_caller = []
93
 
94
  user_prompt = message
95
- # Handle image processing
96
- if message["files"]:
97
- inputs = llava(message, history)
98
- streamer = TextIteratorStreamer(processor, skip_prompt=True, **{"skip_special_tokens": True})
99
- generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)
100
-
101
- thread = Thread(target=model.generate, kwargs=generation_kwargs)
102
- thread.start()
103
-
104
- buffer = ""
105
- for new_text in streamer:
106
- buffer += new_text
107
- yield buffer
108
- else:
109
- functions_metadata = [
110
- {"type": "function", "function": {"name": "web_search", "description": "Search query on google", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "web search query"}}, "required": ["query"]}}},
111
- {"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"]}}},
112
- {"type": "function", "function": {"name": "image_generation", "description": "Generate image for user", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "image generation prompt"}}, "required": ["query"]}}},
113
- {"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"]}}},
114
- ]
115
 
116
- for msg in history:
117
- func_caller.append({"role": "user", "content": f"{str(msg[0])}"})
118
- func_caller.append({"role": "assistant", "content": f"{str(msg[1])}"})
119
 
120
- message_text = message["text"]
121
- 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}'})
122
-
123
- response = client_gemma.chat_completion(func_caller, max_tokens=200)
124
- response = str(response)
125
- try:
126
- response = response[int(response.find("{")):int(response.rindex("</"))]
127
- except:
128
- response = response[int(response.find("{")):(int(response.rfind("}"))+1)]
129
- response = response.replace("\\n", "")
130
- response = response.replace("\\'", "'")
131
- response = response.replace('\\"', '"')
132
- response = response.replace('\\', '')
133
- print(f"\n{response}")
134
 
135
- try:
136
- json_data = json.loads(str(response))
137
- if json_data["name"] == "web_search":
138
- query = json_data["arguments"]["query"]
139
- gr.Info("Searching Web")
140
- web_results = search(query)
141
- gr.Info("Extracting relevant Info")
142
- web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
143
- messages = f"<|im_start|>system\nYou are OpenCHAT mini a helpful assistant made by KingNish. 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|>"
144
- for msg in history:
145
- messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
146
- messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
147
- 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"
148
- stream = client_mixtral.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False)
149
- output = ""
150
- for response in stream:
151
- if not response.token.text == "<|im_end|>":
152
- output += response.token.text
153
- yield output
154
- elif json_data["name"] == "image_generation":
155
- query = json_data["arguments"]["query"]
156
- gr.Info("Generating Image, Please wait 10 sec...")
157
- yield "Generating Image, Please wait 10 sec..."
158
- try:
159
- image = image_gen(f"{str(query)}")
160
- yield gr.Image(image[1])
161
- except:
162
- client_sd3 = InferenceClient("stabilityai/stable-diffusion-3-medium-diffusers")
163
- seed = random.randint(0,999999)
164
- image = client_sd3.text_to_image(query, negative_prompt=f"{seed}")
165
- yield gr.Image(image)
166
- elif json_data["name"] == "image_qna":
167
- inputs = llava(message, history)
168
- streamer = TextIteratorStreamer(processor, skip_prompt=True, **{"skip_special_tokens": True})
169
- generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)
170
-
171
- thread = Thread(target=model.generate, kwargs=generation_kwargs)
172
- thread.start()
173
 
174
- buffer = ""
175
- for new_text in streamer:
176
- buffer += new_text
177
- yield buffer
178
- else:
179
- messages = f"<|start_header_id|>system\nYou are OpenCHAT mini a helpful assistant made by KingNish. 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 and reply like human, use short forms, friendly tone and emotions.<|end_header_id|>"
180
- for msg in history:
181
- messages += f"\n<|start_header_id|>user\n{str(msg[0])}<|end_header_id|>"
182
- messages += f"\n<|start_header_id|>assistant\n{str(msg[1])}<|end_header_id|>"
183
- messages+=f"\n<|start_header_id|>user\n{message_text}<|end_header_id|>\n<|start_header_id|>assistant\n"
184
- stream = client_llama.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False)
185
- output = ""
186
- for response in stream:
187
- if not response.token.text == "<|eot_id|>":
188
- output += response.token.text
189
- yield output
190
- except:
191
- messages = f"<|start_header_id|>system\nYou are OpenCHAT mini a helpful assistant made by KingNish. 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 and reply like human, use short forms, friendly tone and emotions.<|end_header_id|>"
192
  for msg in history:
193
- messages += f"\n<|start_header_id|>user\n{str(msg[0])}<|end_header_id|>"
194
- messages += f"\n<|start_header_id|>assistant\n{str(msg[1])}<|end_header_id|>"
195
- messages+=f"\n<|start_header_id|>user\n{message_text}<|end_header_id|>\n<|start_header_id|>assistant\n"
 
 
 
 
 
 
 
 
 
 
 
 
196
  stream = client_llama.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False)
197
  output = ""
198
  for response in stream:
199
- if not response.token.text == "<|eot_id|>":
200
  output += response.token.text
201
  yield output
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
  demo = gr.ChatInterface(
204
  fn=respond,
 
14
  import cv2
15
  from gradio_client import Client, file
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  def extract_text_from_webpage(html_content):
18
  soup = BeautifulSoup(html_content, 'html.parser')
19
  for tag in soup(["script", "style", "header", "footer"]):
 
63
  func_caller = []
64
 
65
  user_prompt = message
66
+ functions_metadata = [
67
+ {"type": "function", "function": {"name": "web_search", "description": "Search query on google", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "web search query"}}, "required": ["query"]}}},
68
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
+ for msg in history:
71
+ func_caller.append({"role": "user", "content": f"{str(msg[0])}"})
72
+ func_caller.append({"role": "assistant", "content": f"{str(msg[1])}"})
73
 
74
+ message_text = message["text"]
75
+ 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}'})
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ response = client_gemma.chat_completion(func_caller, max_tokens=200)
78
+ response = str(response)
79
+ try:
80
+ response = response[int(response.find("{")):int(response.rindex("</"))]
81
+ except:
82
+ response = response[int(response.find("{")):(int(response.rfind("}"))+1)]
83
+ response = response.replace("\\n", "")
84
+ response = response.replace("\\'", "'")
85
+ response = response.replace('\\"', '"')
86
+ response = response.replace('\\', '')
87
+ print(f"\n{response}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
+ try:
90
+ json_data = json.loads(str(response))
91
+ if json_data["name"] == "web_search":
92
+ query = json_data["arguments"]["query"]
93
+ gr.Info("Searching Web")
94
+ web_results = search(query)
95
+ gr.Info("Extracting relevant Info")
96
+ web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
97
+ messages = f"system\nYou are OpenCHAT mini a helpful assistant made by KingNish. 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."
 
 
 
 
 
 
 
 
 
98
  for msg in history:
99
+ messages += f"\nuser\n{str(msg[0])}"
100
+ messages += f"\nassistant\n{str(msg[1])}"
101
+ messages+=f"\nuser\n{message_text}\nweb_result\n{web2}\nassistant\n"
102
+ stream = client_mixtral.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False)
103
+ output = ""
104
+ for response in stream:
105
+ if not response.token.text == "":
106
+ output += response.token.text
107
+ yield output
108
+ else:
109
+ messages = f"system\nYou are OpenCHAT mini a helpful assistant made by KingNish. 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 and reply like human, use short forms, friendly tone and emotions."
110
+ for msg in history:
111
+ messages += f"\nuser\n{str(msg[0])}"
112
+ messages += f"\nassistant\n{str(msg[1])}"
113
+ messages+=f"\nuser\n{message_text}\nassistant\n"
114
  stream = client_llama.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False)
115
  output = ""
116
  for response in stream:
117
+ if not response.token.text == "":
118
  output += response.token.text
119
  yield output
120
+ except:
121
+ messages = f"system\nYou are OpenCHAT mini a helpful assistant made by KingNish. 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 and reply like human, use short forms, friendly tone and emotions."
122
+ for msg in history:
123
+ messages += f"\nuser\n{str(msg[0])}"
124
+ messages += f"\nassistant\n{str(msg[1])}"
125
+ messages+=f"\nuser\n{message_text}\nassistant\n"
126
+ stream = client_llama.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False)
127
+ output = ""
128
+ for response in stream:
129
+ if not response.token.text == "":
130
+ output += response.token.text
131
+ yield output
132
 
133
  demo = gr.ChatInterface(
134
  fn=respond,