File size: 13,895 Bytes
4a8ac8b
 
 
 
 
 
 
 
7e5261e
 
 
 
 
 
 
 
 
 
 
14d257f
7e5261e
 
 
6cf979c
983867e
f0b6227
6cf979c
 
09ac675
6cf979c
 
f0b6227
983867e
6cf979c
 
f0b6227
983867e
6cf979c
09ac675
 
 
 
7e5261e
4a8ac8b
 
db07900
4a8ac8b
 
 
 
7ea7941
4a8ac8b
 
8276bc3
7ea7941
 
4a8ac8b
8c8d4ad
7ea7941
 
 
4a8ac8b
 
 
 
 
 
 
 
8c8d4ad
4a8ac8b
 
 
 
 
8276bc3
4a8ac8b
 
 
7ea7941
8c8d4ad
7ea7941
 
 
1db2e45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ea7941
666a2c5
4a8ac8b
f105330
7ea7941
1db2e45
06bea5a
 
 
 
 
 
1db2e45
06bea5a
 
 
 
983867e
 
 
 
 
 
 
 
 
1db2e45
6a8f97c
983867e
 
 
 
 
1db2e45
983867e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1db2e45
983867e
 
 
1db2e45
983867e
 
 
 
 
 
 
 
06bea5a
983867e
ecacf71
68eb9a9
 
983867e
06bea5a
983867e
 
06bea5a
 
 
 
 
 
1db2e45
06bea5a
 
 
 
983867e
1db2e45
 
983867e
1db2e45
 
 
983867e
 
 
 
 
 
 
1db2e45
4a8ac8b
1db2e45
 
 
7ea7941
4a8ac8b
 
 
 
 
 
1db2e45
7ea7941
 
 
1db2e45
7ea7941
 
2832f32
7ea7941
aa86625
0f338fe
 
 
1db2e45
7ea7941
 
 
1db2e45
091add3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import gradio as gr
from huggingface_hub import InferenceClient
import json
import uuid
from PIL import Image
from bs4 import BeautifulSoup
import requests
import random
from transformers import LlavaProcessor, LlavaForConditionalGeneration, TextIteratorStreamer
from threading import Thread
import re
import time 
import torch
import cv2

model_id = "llava-hf/llava-interleave-qwen-0.5b-hf"

processor = LlavaProcessor.from_pretrained(model_id)

model = LlavaForConditionalGeneration.from_pretrained(model_id)
model.to("cpu")


def llava(message, history):
    if message["files"]:
        image = message["files"][0]    
    else:
        for hist in history:
            if isinstance(hist[0], tuple):
                image = hist[0][0]
        
    txt = message["text"]
        
    gr.Info("Analyzing image")
    image = Image.open(image).convert("RGB")
    prompt = f"<|im_start|>user <image>\n{txt}<|im_end|><|im_start|>assistant"
    
    inputs = processor(prompt, image, return_tensors="pt")
    
    # Return the dictionary format expected by MultimodalTextbox
    return {"text": txt, "files": [image]}


def extract_text_from_webpage(html_content):
    soup = BeautifulSoup(html_content, 'html.parser')
    for tag in soup(["script", "style", "header", "footer"]):
        tag.extract()
    return soup.get_text(strip=True)

def search(query):
    term = query
    start = 0
    all_results = []
    max_chars_per_page = 8000
    with requests.Session() as session:
        resp = session.get(
            url="https://www.google.com/search",
            headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"},
            params={"q": term, "num": 3, "udm": 14},
            timeout=5,
            verify=None,
        )
        resp.raise_for_status()
        soup = BeautifulSoup(resp.text, "html.parser")
        result_block = soup.find_all("div", attrs={"class": "g"})
        for result in result_block:
            link = result.find("a", href=True)
            link = link["href"]
            try:
                webpage = session.get(link, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"}, timeout=5, verify=False)
                webpage.raise_for_status()
                visible_text = extract_text_from_webpage(webpage.text)
                if len(visible_text) > max_chars_per_page:
                    visible_text = visible_text[:max_chars_per_page]
                all_results.append({"link": link, "text": visible_text})
            except requests.exceptions.RequestException:
                all_results.append({"link": link, "text": None})
    return all_results

# Initialize inference clients for different models
client_gemma = InferenceClient("google/gemma-1.1-7b-it")
client_mixtral = InferenceClient("NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO")
client_llama = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")

import gradio as gr
from huggingface_hub import InferenceClient
import json
import uuid
from PIL import Image
from bs4 import BeautifulSoup
import requests
import random
from transformers import LlavaProcessor, LlavaForConditionalGeneration, TextIteratorStreamer
from threading import Thread
import re
import time 
import torch
import cv2

model_id = "llava-hf/llava-interleave-qwen-0.5b-hf"

processor = LlavaProcessor.from_pretrained(model_id)

model = LlavaForConditionalGeneration.from_pretrained(model_id)
model.to("cpu")


def llava(message, history):
    if message["files"]:
        image = message["files"][0]    
    else:
        for hist in history:
            if isinstance(hist[0], tuple):
                image = hist[0][0]
        
    txt = message["text"]
        
    gr.Info("Analyzing image")
    image = Image.open(image).convert("RGB")
    prompt = f"<|im_start|>user <image>\n{txt}<|im_end|><|im_start|>assistant"
    
    inputs = processor(prompt, image, return_tensors="pt")
    
    # Return the dictionary format expected by MultimodalTextbox
    return {"text": txt, "files": [image]}


def extract_text_from_webpage(html_content):
    soup = BeautifulSoup(html_content, 'html.parser')
    for tag in soup(["script", "style", "header", "footer"]):
        tag.extract()
    return soup.get_text(strip=True)

def search(query):
    term = query
    start = 0
    all_results = []
    max_chars_per_page = 8000
    with requests.Session() as session:
        resp = session.get(
            url="https://www.google.com/search",
            headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"},
            params={"q": term, "num": 3, "udm": 14},
            timeout=5,
            verify=None,
        )
        resp.raise_for_status()
        soup = BeautifulSoup(resp.text, "html.parser")
        result_block = soup.find_all("div", attrs={"class": "g"})
        for result in result_block:
            link = result.find("a", href=True)
            link = link["href"]
            try:
                webpage = session.get(link, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"}, timeout=5, verify=False)
                webpage.raise_for_status()
                visible_text = extract_text_from_webpage(webpage.text)
                if len(visible_text) > max_chars_per_page:
                    visible_text = visible_text[:max_chars_per_page]
                all_results.append({"link": link, "text": visible_text})
            except requests.exceptions.RequestException:
                all_results.append({"link": link, "text": None})
    return all_results

# Initialize inference clients for different models
client_gemma = InferenceClient("google/gemma-1.1-7b-it")
client_mixtral = InferenceClient("NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO")
client_llama = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")

# Corrected the response format to ensure it works with Gradio's multimodal interface.
def respond(message, history):
    func_caller = []

    user_prompt = message
    # Handle image processing
    if message.get("files"):
        inputs = llava(message, history)
        streamer = TextIteratorStreamer(processor, skip_prompt=True, **{"skip_special_tokens": True})
        generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)

        thread = Thread(target=model.generate, kwargs=generation_kwargs)
        thread.start()

        buffer = ""
        for new_text in streamer:
            buffer += new_text
            yield buffer
    else:
        functions_metadata = [
            {"type": "function", "function": {"name": "web_search", "description": "Search query on google", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "web search query"}}, "required": ["query"]}}},
            {"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"]}}},
            {"type": "function", "function": {"name": "image_generation", "description": "Generate image for user", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "image generation prompt"}, "number_of_image": {"type": "integer", "description": "number of images to generate"}}, "required": ["query"]}}},
            {"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"]}}},
        ]
    
        message_text = message["text"]
        func_caller.append({"role": "user", "content": f'[SYSTEM]You are a helpful AI assistant for a discord server called Stars Kingdom, your job is to have fun help users and listen to what they say or want you to act. You have been created by the discord server owner named Star. 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_2": "value_2", ... }} }}  </functioncall>  [USER] {message_text}'})

        response = client_gemma.chat_completion(func_caller, max_tokens=150)
        response = str(response)
        try:
            response = response[int(response.find("{")):int(response.index("</"))]
        except:
            print("An error occurred")
        response = response.replace("\\n", "")
        response = response.replace("\\'", "'")
        response = response.replace('\\"', '"')
        print(f"\n{response}")
    
        func_caller.append({"role": "assistant", "content": f"<functioncall>{response}</functioncall>"})
    
        try:
            json_data = json.loads(str(response))
            if json_data["name"] == "web_search":
                query = json_data["arguments"]["query"]
                gr.Info("Searching Web")
                web_results = search(query)
                gr.Info("Extracting relevant Info")
                web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
                messages = f"<|im_start|>system\nYou are a helpful assistant made by Star. You are provided with WEB results from which you can find informations to answer users query in a structured and better way. Only respond with what’s important!<|im_end|>"
                for msg in history:
                    messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
                    messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
                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"
                stream = client_mixtral.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False)
                output = ""
                for response in stream:
                    if not response.token.text == "<|im_end|>":
                        output += response.token.text
                        yield output
            elif json_data["name"] == "image_generation":
                query = json_data["arguments"]["query"]
                gr.Info("Generating Image, Please wait 10 sec...")
                seed = random.randint(1, 99999)
                image = f"![](https://image.pollinations.ai/prompt/{message_text}{query}?seed={seed}&nologo=True)"
                image = image.replace("\\n", "")
                image = image.replace(" ", "%20")
                yield image
                time.sleep(8)
                gr.Info("We are going to Update Our Image Generation Engine to more powerful ones in Next Update. ThankYou")
            elif json_data["name"] == "image_qna":
                inputs = llava(message, history)
                streamer = TextIteratorStreamer(processor, skip_prompt=True, **{"skip_special_tokens": True})
                generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)

                thread = Thread(target=model.generate, kwargs=generation_kwargs)
                thread.start()

                buffer = ""
                for new_text in streamer:
                    buffer += new_text
                    yield buffer
            else:
                # Default response from llama model if no specific function matched
                messages = f"<|im_start|>system\nYou are a helpful assistant made by Star.<|im_end|>"
                for msg in history:
                    messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
                    messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
                messages += f"\n<|im_start|>user\n{message_text}<|im_end|>\n<|im_start|>assistant\n"
                stream = client_llama.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False)
                output = ""
                for response in stream:
                    if not response.token.text == "<|eot_id|>":
                        output += response.token.text
                        yield output
        except:
            messages = f"<|im_start|>system\nYou are a helpful assistant made by Star. You answer users' queries like a human friend.<|im_end|>"
            for msg in history:
                messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
                messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
            messages += f"\n<|im_start|>user\n{message_text}<|im_end|>\n<|im_start|>assistant\n"
            stream = client_llama.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False)
            output = ""
            for response in stream:
                if not response.token.text == "<|eot_id|>":
                    output += response.token.text
                    yield output

# Gradio Chat Interface
demo = gr.ChatInterface(
    fn=respond,
    chatbot=gr.Chatbot(show_copy_button=True, likeable=True, layout="panel"),
    description="AI assistant for Stars Kingdom",
    textbox=gr.MultimodalTextbox(),
    multimodal=True,
    concurrency_limit=200,
    examples=[
        {"text": "What can I wear with a yellow Kurta?",},
        {"text": "What's the preferred shirt color for an interview?",},
        {"text": "How can I dress more smartly?",},
        {"text": "Tell about some good accessories for a traditional Indian wedding",},
        {"text": "What's the color of the frock in the given image?", "files": ["./frock.png"]},
    ],
    cache_examples=False,
)

demo.launch(share=True)