File size: 15,094 Bytes
5f52293
ed2f5ce
69f2e98
ed2f5ce
 
2a36ff2
82043d5
1061b7a
ed2f5ce
 
02e5bf0
ed2f5ce
2a200be
8f7c5f5
49f29b5
 
 
8f7c5f5
 
7ad8369
e7e0762
4f446f9
ed2f5ce
1197e50
4fd9098
49f29b5
bd00948
1197e50
1061b7a
2e5a20c
d5685b0
7f9822a
ed2f5ce
d5685b0
1061b7a
724aed2
 
d5685b0
1197e50
79549f2
2a200be
1197e50
ed2f5ce
e1310ff
ed2f5ce
 
 
 
 
 
 
d5685b0
e7e0762
 
 
 
1197e50
e7e0762
4fd9098
 
e7e0762
 
 
 
 
 
 
8f7c5f5
e7e0762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f7c5f5
 
 
 
 
e1310ff
8f7c5f5
 
 
 
 
 
 
 
 
 
 
 
 
 
e7e0762
e1310ff
8f7c5f5
 
df220f6
e7e0762
a685a6f
e1310ff
b7359e6
e1310ff
 
1197e50
e7e0762
 
e1310ff
 
 
 
 
 
5e6cec6
e7e0762
 
 
 
 
 
 
 
 
4fd9098
 
 
 
 
 
 
e7e0762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e6cec6
e7e0762
 
dab87df
e7e0762
dab87df
c39dad7
 
 
 
 
 
 
 
 
 
dab87df
c39dad7
dab87df
1bad456
c39dad7
e7e0762
e1310ff
5c0af0e
e7e0762
5e6cec6
e7e0762
 
 
 
 
 
5c0af0e
e7e0762
 
 
5e6cec6
e7e0762
 
 
6b07c5f
e7e0762
 
 
 
 
 
 
 
 
 
 
 
 
 
df220f6
2a200be
82043d5
2a200be
ac48055
 
 
8f7c5f5
 
ac48055
 
 
 
 
 
 
 
 
8f7c5f5
ac48055
8f7c5f5
 
 
 
 
 
ac48055
 
 
 
 
 
 
 
8f7c5f5
 
 
 
ac48055
 
 
 
 
 
 
 
 
 
8f7c5f5
 
 
 
 
 
 
 
 
 
 
ac48055
 
 
 
8f7c5f5
ac48055
8f7c5f5
ac48055
8f7c5f5
ac48055
8f7c5f5
 
 
 
ac48055
 
 
8f7c5f5
 
 
 
 
 
ac48055
 
 
 
 
 
8f7c5f5
 
 
 
ac48055
 
 
 
 
 
8f7c5f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac48055
8f7c5f5
 
 
 
 
 
 
 
 
 
 
 
ac48055
2a200be
 
 
 
 
 
 
ac48055
2a200be
 
 
 
1197e50
2a200be
 
 
 
 
df220f6
1197e50
2a200be
 
 
 
 
df220f6
2a200be
 
 
 
 
 
 
 
d5685b0
a742a0d
2a200be
df220f6
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
import gradio as gr
import torch
import os
import numpy as np
from groq import Groq
import spaces
from transformers import AutoModel, AutoTokenizer
from diffusers import StableDiffusion3Pipeline
from parler_tts import ParlerTTSForConditionalGeneration
import soundfile as sf
from langchain_groq import ChatGroq
from PIL import Image
from tavily import TavilyClient
from langchain.schema import AIMessage
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import FAISS
from langchain_community.document_loaders import TextLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain.chains import RetrievalQA
from torchvision import transforms
import json
import pandas

# Initialize models and clients
MODEL = 'llama-3.1-70b-versatile'
client = Groq(api_key=os.environ.get("GROQ_API_KEY"))

vqa_model = AutoModel.from_pretrained('openbmb/MiniCPM-V-2', trust_remote_code=True,
                                      device_map="auto", torch_dtype=torch.bfloat16)
tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-V-2', trust_remote_code=True)

tts_model = ParlerTTSForConditionalGeneration.from_pretrained("parler-tts/parler-tts-large-v1")
tts_tokenizer = AutoTokenizer.from_pretrained("parler-tts/parler-tts-large-v1")

# Updated Image generation model
pipe = StableDiffusion3Pipeline.from_pretrained("stabilityai/stable-diffusion-3-medium-diffusers", torch_dtype=torch.float16)
pipe = pipe.to("cuda")

# Tavily Client for web search
tavily_client = TavilyClient(api_key=os.environ.get("TAVILY_API"))

# Function to play voice output
def play_voice_output(response):
    print("Executing play_voice_output function")
    description = "Jon's voice is monotone yet slightly fast in delivery, with a very close recording that almost has no background noise."
    input_ids = tts_tokenizer(description, return_tensors="pt").input_ids.to('cuda')
    prompt_input_ids = tts_tokenizer(response, return_tensors="pt").input_ids.to('cuda')
    generation = tts_model.generate(input_ids=input_ids, prompt_input_ids=prompt_input_ids)
    audio_arr = generation.cpu().numpy().squeeze()
    sf.write("output.wav", audio_arr, tts_model.config.sampling_rate)
    return "output.wav"

# Function to classify user input using LLM
def classify_function(user_prompt):
    prompt = f"""
    You are a function classifier AI assistant. You are given a user input and you need to classify it into one of the following functions:

    - `image_generation`: If the user wants to generate an image.
    - `image_vqa`: If the user wants to ask questions about an image.
    - `document_qa`: If the user wants to ask questions about a document.
    - `text_to_text`: If the user wants a text-based response.

    Respond with a JSON object containing only the chosen function. For example:

    ```json
    {{"function": "image_generation"}}
    ```

    User input: {user_prompt}
    """

    chat_completion = client.chat.completions.create(
        messages=[
            {
                "role": "user",
                "content": prompt,
            }
        ],
        model="llama3-8b-8192",
    )

    try:
        response = json.loads(chat_completion.choices[0].message.content)
        function = response.get("function")
        return function
    except json.JSONDecodeError:
        print(f"Error decoding JSON: {chat_completion.choices[0].message.content}")
        return "text_to_text"  # Default to text-to-text if JSON parsing fails

# Document Question Answering Tool
class DocumentQuestionAnswering:
    def __init__(self, document):
        self.document = document
        self.qa_chain = self._setup_qa_chain()

    def _setup_qa_chain(self):
        print("Setting up DocumentQuestionAnswering tool")
        loader = TextLoader(self.document)
        documents = loader.load()
        text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
        texts = text_splitter.split_documents(documents)
        embeddings = HuggingFaceEmbeddings()
        db = FAISS.from_documents(texts, embeddings)
        retriever = db.as_retriever()
        qa_chain = RetrievalQA.from_chain_type(
            llm=ChatGroq(model=MODEL, api_key=os.environ.get("GROQ_API_KEY")),
            chain_type="stuff",
            retriever=retriever,
        )
        return qa_chain

    def run(self, query: str) -> str:
        print("Executing DocumentQuestionAnswering tool")
        response = self.qa_chain.run(query)
        return str(response)

# Function to handle different input types and choose the right pipeline
def handle_input(user_prompt, image=None, audio=None, websearch=False, document=None):
    print(f"Handling input: {user_prompt}")

    # Initialize the LLM
    llm = ChatGroq(model=MODEL, api_key=os.environ.get("GROQ_API_KEY"))

    # Handle voice-only mode
    if audio:
        print("Processing audio input")
        transcription = client.audio.transcriptions.create(
            file=(audio.name, audio.read()),
            model="whisper-large-v3"
        )
        user_prompt = transcription.text
        response = llm.invoke(query=user_prompt)
        audio_output = play_voice_output(response)
        return "Response generated.", audio_output

    # Handle websearch mode
    if websearch:
        print("Executing Web Search")
        answer = tavily_client.qna_search(query=user_prompt)
        return answer, None

    # Handle cases with only image or document input
    if user_prompt is None or user_prompt.strip() == "":
        if image:
            user_prompt = "Describe this image"
        elif document:
            user_prompt = "Summarize this document"

    # Classify user input using LLM
    function = classify_function(user_prompt)

    # Handle different functions
    if function == "image_generation":
        print("Executing Image Generation")
        image = pipe(
            user_prompt,
            negative_prompt="",
            num_inference_steps=15,
            guidance_scale=7.0,
        ).images[0]
        image.save("output.jpg")
        return "output.jpg", None

    elif function == "image_vqa":
        print("Executing Image Description")
        if image:
            print("1")
            image = Image.open(image).convert('RGB')
            print("2")
    
            # Add preprocessing steps here (see examples above)
            preprocess = transforms.Compose([
                transforms.Resize((512, 512)),  # Example size, replace with the correct one
                transforms.ToTensor(),
            ])
            image = preprocess(image)
            image = image.unsqueeze(0)  # Add batch dimension
            image = image.to(torch.float32)  # Ensure correct data type
    
            print("3")
            messages = [{"role": "user", "content": user_prompt}]
            print("4")
            response,ctxt = vqa_model.chat(image=image, msgs=messages, tokenizer=tokenizer, context=None, temperature=0.5)
            print("5")
            return response, None
        else:
            return "Please upload an imagee.", None

    elif function == "document_qa":
        print("Executing Document Summarization")
        if document:
            document_qa = DocumentQuestionAnswering(document)
            response = document_qa.run(user_prompt)
            return response, None
        else:
            return "Please upload a documentt.", None

    else:  # function == "text_to_text"
        print("Executing Text-to-Text")
        response = llm.invoke(query=user_prompt)
        return response, None

# Main interface function
@spaces.GPU(duration=120)
def main_interface(user_prompt, image=None, audio=None, voice_only=False, websearch=False, document=None):
    print("Starting main_interface function")
    vqa_model.to(device='cuda', dtype=torch.bfloat16)
    tts_model.to("cuda")
    pipe.to("cuda")

    print(f"user_prompt: {user_prompt}, image: {image}, audio: {audio}, voice_only: {voice_only}, websearch: {websearch}, document: {document}")

    try:
        response = handle_input(user_prompt, image=image, audio=audio, websearch=websearch, document=document)
        print("handle_input function executed successfully")
    except Exception as e:
        print(f"Error in handle_input: {e}")
        response = "Error occurred during processing."

    return response

def create_ui():
    with gr.Blocks(css="""
        /* Overall Styling */
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            margin: 0;
            padding: 0;
            color: #333;
        }

        /* Title Styling */
        .gradio-container h1 {
            text-align: center;
            padding: 20px 0;
            background: linear-gradient(45deg, #007bff, #00c6ff);
            color: white;
            font-size: 2.5em;
            font-weight: bold;
            letter-spacing: 1px;
            text-transform: uppercase;
            margin: 0;
            box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
        }

        /* Input Area Styling */
        .gradio-container .gr-row {
            display: flex;
            justify-content: space-around;
            align-items: center;
            padding: 20px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }

        .gradio-container .gr-column {
            flex: 1;
            margin: 0 10px;
        }

        /* Textbox Styling */
        .gradio-container textarea {
            width: calc(100% - 20px);
            padding: 15px;
            border: 2px solid #007bff;
            border-radius: 8px;
            font-size: 1.1em;
            transition: border-color 0.3s, box-shadow 0.3s;
        }

        .gradio-container textarea:focus {
            border-color: #00c6ff;
            box-shadow: 0px 0px 8px rgba(0, 198, 255, 0.5);
            outline: none;
        }

        /* Button Styling */
        .gradio-container button {
            background: linear-gradient(45deg, #007bff, #00c6ff);
            color: white;
            padding: 15px 25px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1.2em;
            font-weight: bold;
            transition: background 0.3s, transform 0.3s;
            box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
        }

        .gradio-container button:hover {
            background: linear-gradient(45deg, #0056b3, #009bff);
            transform: translateY(-3px);
        }

        .gradio-container button:active {
            transform: translateY(0);
        }

        /* Output Area Styling */
        .gradio-container .output-area {
            padding: 20px;
            text-align: center;
            background-color: #f7f9fc;
            border-radius: 10px;
            box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.1);
            margin-top: 20px;
        }

        /* Image Styling */
        .gradio-container img {
            max-width: 100%;
            height: auto;
            border-radius: 10px;
            box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s, box-shadow 0.3s;
        }

        .gradio-container img:hover {
            transform: scale(1.05);
            box-shadow: 0px 6px 12px rgba(0, 0, 0, 0.2);
        }

        /* Checkbox Styling */
        .gradio-container input[type="checkbox"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
            accent-color: #007bff;
            transition: transform 0.3s;
        }

        .gradio-container input[type="checkbox"]:checked {
            transform: scale(1.2);
        }

        /* Audio and Document Upload Styling */
        .gradio-container .gr-file-upload input[type="file"] {
            width: 100%;
            padding: 10px;
            border: 2px solid #007bff;
            border-radius: 8px;
            cursor: pointer;
            background-color: white;
            transition: border-color 0.3s, background-color 0.3s;
        }

        .gradio-container .gr-file-upload input[type="file"]:hover {
            border-color: #00c6ff;
            background-color: #f0f8ff;
        }

        /* Advanced Tooltip Styling */
        .gradio-container .gr-tooltip {
            position: relative;
            display: inline-block;
            cursor: pointer;
        }

        .gradio-container .gr-tooltip .tooltiptext {
            visibility: hidden;
            width: 200px;
            background-color: black;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 5px;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            margin-left: -100px;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .gradio-container .gr-tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }

        /* Footer Styling */
        .gradio-container footer {
            text-align: center;
            padding: 10px;
            background: #007bff;
            color: white;
            font-size: 0.9em;
            border-radius: 0 0 10px 10px;
            box-shadow: 0px -2px 8px rgba(0, 0, 0, 0.1);
        }

    """) as demo:
        gr.Markdown("# AI Assistant")
        with gr.Row():
            with gr.Column(scale=2):
                user_prompt = gr.Textbox(placeholder="Type your message here...", lines=1)
            with gr.Column(scale=1):
                image_input = gr.Image(type="filepath", label="Upload an image", elem_id="image-icon")
                audio_input = gr.Audio(type="filepath", label="Upload audio", elem_id="mic-icon")
                document_input = gr.File(type="filepath", label="Upload a document", elem_id="document-icon")
                voice_only_mode = gr.Checkbox(label="Enable Voice Only Mode", elem_id="voice-only-mode")
                websearch_mode = gr.Checkbox(label="Enable Web Search", elem_id="websearch-mode")
            with gr.Column(scale=1):
                submit = gr.Button("Submit")

        output_label = gr.Label(label="Output")
        audio_output = gr.Audio(label="Audio Output", visible=False)

        submit.click(
            fn=main_interface,
            inputs=[user_prompt, image_input, audio_input, voice_only_mode, websearch_mode, document_input],
            outputs=[output_label, audio_output]
        )

        voice_only_mode.change(
            lambda x: gr.update(visible=not x),
            inputs=voice_only_mode,
            outputs=[user_prompt, image_input, websearch_mode, document_input, submit]
        )
        voice_only_mode.change(
            lambda x: gr.update(visible=x),
            inputs=voice_only_mode,
            outputs=[audio_input]
        )

    return demo

# Launch the UI
demo = create_ui()
demo.launch()