File size: 6,844 Bytes
28d8100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# import gradio as gr
# import httpx
# import json
# from typing import Tuple, Any

# # Define the FastAPI endpoint URL
# FASTAPI_ENDPOINT = "http://localhost:8000/websearch"


# def query_api(query: str) -> Tuple[Any, Any]:
#     try:
#         # Send POST request to FastAPI endpoint with streaming enabled
#         with httpx.Client() as client:
#             with client.stream("POST", FASTAPI_ENDPOINT, json={"query": query}, timeout=60.0) as response:
#                 response.raise_for_status()  # Raise an exception for 4xx or 5xx status codes
                
#                 # Process the streaming response
#                 response_data = ""
#                 for chunk in response.iter_text():
#                     response_data += chunk
                
#                 # Parse the accumulated response data as JSON
#                 response_json = json.loads(response_data)
                
#                 # Extract content and citations from the response JSON
#                 content = response_json.get("content", "")
#                 citations = response_json.get("citations", [])
                
#                 # Beautify content using Markdown formatting
#                 beautified_content = f"# Search Results\n\n{content}"
                
#                 # Beautify citations by adding Markdown links
#                 beautified_citations = "# Citations\n\n"
#                 for i, citation in enumerate(citations, start=1):
#                     beautified_citations += f"{i}. [{citation}]({citation})\n"
                
#                 # Yield the beautified content and citations
#                 yield beautified_content, beautified_citations
#     except httpx.TimeoutException:
#         yield "Request timed out. Please try again later.", ""
#     except httpx.HTTPStatusError as e:
#         yield f"HTTP error occurred: {e}", ""
#     except Exception as e:
#         yield f"An error occurred: {e}", ""


# # Create Gradio interface
# with gr.Blocks(css=".gradio-container { background-color: #f5f5f5; padding: 20px; border-radius: 10px; }") as demo:
#     gr.Markdown("# Web Search Application")
    
#     with gr.Row():
#         with gr.Column():
#             query = gr.Textbox(
#                 label="Enter your query",
#                 placeholder="Type your search query here...",
#                 lines=2,
#                 max_lines=4,
#                 value="",
#                 elem_id="query-input"
#             )
#             submit_button = gr.Button("Search")
        
#         with gr.Column():
#             output_content = gr.Textbox(
#                 label="Response Content",
#                 placeholder="Search results will appear here...",
#                 lines=10,
#                 max_lines=20,
#                 value="",
#                 elem_id="response-content"
#             )
#             output_citations = gr.Textbox(
#                 label="Citations",
#                 placeholder="Citations will appear here...",
#                 lines=5,
#                 max_lines=10,
#                 value="",
#                 elem_id="response-citations"
#             )
    
#     # Set up event listener
#     submit_button.click(query_api, inputs=query, outputs=[output_content, output_citations])
    
#     gr.Markdown("Powered by FastAPI and Gradio")

# # Launch the Gradio application
# demo.launch()


import gradio as gr
import httpx
import json

# Define the FastAPI endpoint URL
FASTAPI_ENDPOINT = "http://localhost:8000/websearch"

def query_api(query: str) -> tuple:
    try:
        # Send POST request to FastAPI endpoint with streaming enabled
        with httpx.Client() as client:
            with client.stream("POST", FASTAPI_ENDPOINT, json={"query": query}, timeout=60.0) as response:
                response.raise_for_status()  # Raise an exception for 4xx or 5xx status codes
                
                # Process the streaming response
                response_data = ""
                for chunk in response.iter_text():
                    response_data += chunk
                
                # Parse the accumulated response data as JSON
                response_json = json.loads(response_data)
                
                # Extract content and citations from the response JSON
                content = response_json.get("content", "")
                citations = response_json.get("citations", [])
                
                # Beautify content using Markdown formatting
                beautified_content = f"# Search Results\n\n{content}"
                
                # Beautify citations by adding Markdown links
                beautified_citations = "# Citations/Sources\n\n"
                for i, citation in enumerate(citations, start=1):
                    beautified_citations += f"{i}. [{citation}]({citation})\n"
                
                # Yield the beautified content and citations
                yield beautified_content, beautified_citations
    except httpx.TimeoutException:
        yield "# Request Timeout\n\nRequest timed out. Please try again later.", ""
    except httpx.HTTPStatusError as e:
        yield f"# HTTP Error\n\nHTTP error occurred: {e}", ""
    except Exception as e:
        yield f"# Error\n\nAn error occurred: {e}", ""

# Create Gradio interface
with gr.Blocks(css=".gradio-container { background-color: #f5f5f5; padding: 20px; border-radius: 10px; }", theme=gr.themes.Citrus()) as demo:
    gr.Markdown("# Web Search Application")
    
    with gr.Row():
        with gr.Column(
            render=True,
            show_progress=True
        ):
            query = gr.Textbox(
                label="Enter your query",
                placeholder="Type your search query here...",
                lines=2,
                max_lines=4,
                value="",
                elem_id="query-input"
            )
            submit_button = gr.Button("Search")
        
        with gr.Column(
            render=True,
            show_progress=True
        ):
            output_content = gr.Markdown(
                label="Response Content",
                value="",
                elem_id="response-content",
                height="600px",
                visible=True,
                show_label=True
                
            )
            output_citations = gr.Markdown(
                label="Citations",
                value="",
                elem_id="response-citations",
                height="200px",
                visible=True,
                show_label=True
            )
    
    # Set up event listener
    submit_button.click(query_api, inputs=query, outputs=[output_content, output_citations])
    
    gr.Markdown("Powered by FastAPI and Gradio")

# Launch the Gradio application
demo.launch()