File size: 6,097 Bytes
4d7825a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4e9129
4d7825a
 
 
 
f4e9129
4d7825a
 
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
from agent import Agent
from indexing import indexing
import uuid
import gradio as gr
from langchain_groq import ChatGroq
from safety import safe_call
from vision import image_to_data_uri,ask_vision
import os
from dotenv import load_dotenv
from tools import tools
from rag import mainwork
load_dotenv()
llm=ChatGroq(
    model="llama-3.3-70b-versatile",
    api_key=os.getenv("GROQ_API_KEY")
)
agent=Agent(llm,tools,12)
os.makedirs("chroma_store", exist_ok=True)

if not os.path.exists("memory.json"):
    with open("memory.json", "w") as f:
        f.write("{}")

@safe_call
def handle_image(image_path, resolution):

    if image_path is None:
        return (
            None,  
            """
### 📊 Image Metadata

⚠️ No image uploaded.

Please upload an image first.
""",
            False  # image_ready
        )
    result = image_to_data_uri(
        image_path,
        resolution
    )

    

    metadata = result["metadata"]

    metadata_md = f"""
### 📊 Image Metadata

**Original Resolution**
{metadata["original_width"]} × {metadata["original_height"]}

**Current Resolution**
{metadata["new_width"]} × {metadata["new_height"]}

**Resolution**
{metadata["resolution_percent"]}%

**Image Size**
{metadata["image_size_kb"]} KB

**Estimated Tokens**
{metadata["estimated_tokens"]}

**Recommended**
{"✅ Yes" if metadata["recommended"] else "⚠️ Reduce Resolution"}
"""

    if metadata["recommended"]:
        agent.current_image=result["data_uri"]
        return result["data_uri"], metadata_md, metadata["recommended"]
    
    return None, metadata_md, metadata["recommended"]




@safe_call
def chat(message,history,session_id):
    
    final_answer,trace_log=agent.run(message,session_id)
        
    if history is None:
        history=[]
    
    history.append(
    {
        "role": "user",
        "content": message
    })

    history.append(
        {
            "role": "assistant",
            "content": final_answer
        }
    )

    return history, session_id, trace_log or "No tools were called."

with gr.Blocks() as demo:

    session_id=gr.State(value=lambda: str(uuid.uuid4()))
    image_uri_state = gr.State(value=None)
    image_ready = gr.State(value=False)
    gr.Markdown("# 👁️ HybridSight — RAG + Web + Vision Agent")
        
    with gr.Tab("💬 Hybrid Chat"):

        with gr.Row():
            with gr.Column(scale=3):
                chatbot = gr.Chatbot(height=440, label="Conversation")
                msg_box = gr.Textbox(placeholder="Ask anything…", show_label=False)
                submit_btn = gr.Button("Send", variant="primary")
                
            
            with gr.Column(scale=1):
                with gr.Accordion("Reasoning Trace", open=False):
                    trace_box = gr.Textbox(label="Tools called during last response",lines=14, interactive=False)
            
            submit_btn.click(
                    chat,
                    inputs=[msg_box, chatbot, session_id],
                    outputs=[chatbot, session_id,trace_box]
                ).then(lambda: (""),outputs=[msg_box])
            msg_box.submit(
                chat,
                inputs=[msg_box, chatbot, session_id],
                outputs=[chatbot, session_id,trace_box]
            ).then(lambda: (""),outputs=[msg_box])


    with gr.Tab("📄 Document QA"):
        with gr.Row():
            with gr.Column():
                pdf_upload = gr.File(label="Upload a PDF", file_types=[".pdf"])
            with gr.Column():
                index_status = gr.Textbox(label="Indexing status", interactive=False)
                index_btn = gr.Button("📥 Index Document", variant="primary")

        index_btn.click(
    indexing,
    inputs=[pdf_upload, session_id],
    outputs=[index_status]
).then(lambda: None, outputs=[pdf_upload])
        doc_chatbot=gr.Chatbot(height=380)
        doc_input=gr.Textbox(placeholder="Ask about the document…", show_label=False)
        doc_submit_btn=gr.Button("Ask", variant="primary")
        doc_submit_btn.click(
            mainwork,
            inputs=[doc_input,doc_chatbot,session_id],
            outputs=[doc_chatbot]
        ).then(lambda: (""),outputs=[doc_input])
        doc_input.submit(
            mainwork,
            inputs=[doc_input,doc_chatbot,session_id],
            outputs=[doc_chatbot]
        ).then(lambda: (""),outputs=[doc_input])
        
    
    with gr.Tab("🖼️ Image Studio"):

        gr.Markdown("## 🖼️ Image Studio")
        gr.Markdown("Upload an image, adjust its resolution, and ask questions about it.")
        with gr.Row():
            with gr.Column(scale=1):
                image_upload = gr.Image(label="Upload Image",type="filepath")

                resolution_slider = gr.Slider(minimum=10,maximum=100,value=50,step=5,label="Image Resolution (%)")

                metadata_box = gr.Markdown("""
### 📊 Image Metadata

No image uploaded.
""")

                analyse_btn = gr.Button(
                    "🔍 Analyse Image",
                    variant="primary"
                )

            with gr.Column(scale=2):

                image_question = gr.Textbox(
                placeholder="Ask anything about the uploaded image...",
                label="Question"
            )
                ask_btn = gr.Button("Ask")
                image_answer = gr.Textbox(
                label="Vision Response",
                lines=12,
                interactive=False
            )
        
        analyse_btn.click(
        handle_image,
        inputs=[image_upload,resolution_slider],
        outputs=[image_uri_state,metadata_box,image_ready])
        ask_btn.click(
            ask_vision,
            inputs=[image_uri_state,image_ready,image_question],
            outputs=[image_answer]
        ).then(lambda: (""),outputs=[image_question])
        image_question.submit(
            ask_vision,
            inputs=[image_uri_state,image_ready,image_question],
            outputs=[image_answer]
        ).then(lambda: (""),outputs=[image_question])
demo.queue()
demo.launch()