Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,9 @@
|
|
1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
def search_knowledge_base(issue):
|
4 |
"""
|
@@ -15,15 +20,108 @@ def search_knowledge_base(issue):
|
|
15 |
return "Adjust display cable. Update graphics drivers. Restart the system."
|
16 |
return "No predefined solution found in the knowledge base."
|
17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
def search_web(query):
|
19 |
"""
|
20 |
-
|
21 |
Args:
|
22 |
query (str): The search query
|
23 |
Returns:
|
24 |
-
str:
|
25 |
"""
|
26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
|
28 |
def format_response(raw_steps):
|
29 |
"""
|
@@ -33,6 +131,9 @@ def format_response(raw_steps):
|
|
33 |
Returns:
|
34 |
str: Formatted numbered list of steps
|
35 |
"""
|
|
|
|
|
|
|
36 |
steps = raw_steps.split(". ")
|
37 |
steps = [f"{i+1}. {step.strip('.')}" for i, step in enumerate(steps) if step.strip()]
|
38 |
return "\n".join(steps)
|
@@ -40,32 +141,32 @@ def format_response(raw_steps):
|
|
40 |
# Knowledge Base Search Interface
|
41 |
demo1 = gr.Interface(
|
42 |
fn=search_knowledge_base,
|
43 |
-
inputs=[gr.Textbox("wifi connection problem")],
|
44 |
-
outputs=[gr.Textbox()],
|
45 |
title="Knowledge Base Search",
|
46 |
description="Enter a technical issue to search for solutions in the knowledge base."
|
47 |
)
|
48 |
|
49 |
-
# Web Search Interface
|
50 |
demo2 = gr.Interface(
|
51 |
fn=search_web,
|
52 |
-
inputs=[gr.Textbox("latest tech news")],
|
53 |
-
outputs=[gr.Textbox()],
|
54 |
title="Web Search",
|
55 |
-
description="Enter a search query to get
|
56 |
)
|
57 |
|
58 |
# Response Formatter Interface
|
59 |
demo3 = gr.Interface(
|
60 |
fn=format_response,
|
61 |
-
inputs=[gr.Textbox("
|
62 |
-
outputs=[gr.Textbox()],
|
63 |
title="Response Formatter",
|
64 |
description="Enter raw steps separated by periods to format them as a numbered list."
|
65 |
)
|
66 |
|
67 |
-
# Combine all interfaces using Tabs
|
68 |
demo = gr.TabbedInterface([demo1, demo2, demo3], ["Knowledge Base", "Web Search", "Formatter"])
|
69 |
|
70 |
if __name__ == "__main__":
|
71 |
-
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
import requests
|
3 |
+
from bs4 import BeautifulSoup
|
4 |
+
import json
|
5 |
+
from urllib.parse import quote_plus
|
6 |
+
import time
|
7 |
|
8 |
def search_knowledge_base(issue):
|
9 |
"""
|
|
|
20 |
return "Adjust display cable. Update graphics drivers. Restart the system."
|
21 |
return "No predefined solution found in the knowledge base."
|
22 |
|
23 |
+
def search_web_duckduckgo(query):
|
24 |
+
"""
|
25 |
+
Perform actual web search using DuckDuckGo API.
|
26 |
+
Args:
|
27 |
+
query (str): The search query
|
28 |
+
Returns:
|
29 |
+
str: Formatted search results
|
30 |
+
"""
|
31 |
+
try:
|
32 |
+
# DuckDuckGo Instant Answer API
|
33 |
+
url = f"https://api.duckduckgo.com/?q={quote_plus(query)}&format=json&no_html=1&skip_disambig=1"
|
34 |
+
|
35 |
+
response = requests.get(url, timeout=10)
|
36 |
+
response.raise_for_status()
|
37 |
+
|
38 |
+
data = response.json()
|
39 |
+
|
40 |
+
results = []
|
41 |
+
|
42 |
+
# Get instant answer if available
|
43 |
+
if data.get('AbstractText'):
|
44 |
+
results.append(f"**Summary:** {data['AbstractText']}")
|
45 |
+
|
46 |
+
# Get related topics
|
47 |
+
if data.get('RelatedTopics'):
|
48 |
+
results.append("\n**Related Information:**")
|
49 |
+
for i, topic in enumerate(data['RelatedTopics'][:3], 1):
|
50 |
+
if isinstance(topic, dict) and topic.get('Text'):
|
51 |
+
results.append(f"{i}. {topic['Text']}")
|
52 |
+
|
53 |
+
# Get definition if available
|
54 |
+
if data.get('Definition'):
|
55 |
+
results.append(f"\n**Definition:** {data['Definition']}")
|
56 |
+
|
57 |
+
if results:
|
58 |
+
return "\n".join(results)
|
59 |
+
else:
|
60 |
+
return f"Search completed for '{query}' but no detailed results available. Try a more specific query."
|
61 |
+
|
62 |
+
except requests.RequestException as e:
|
63 |
+
return f"Error performing web search: {str(e)}"
|
64 |
+
except Exception as e:
|
65 |
+
return f"Unexpected error: {str(e)}"
|
66 |
+
|
67 |
+
def search_web_scraper(query):
|
68 |
+
"""
|
69 |
+
Alternative web search using web scraping (backup method).
|
70 |
+
Args:
|
71 |
+
query (str): The search query
|
72 |
+
Returns:
|
73 |
+
str: Formatted search results
|
74 |
+
"""
|
75 |
+
try:
|
76 |
+
# Use DuckDuckGo HTML search as backup
|
77 |
+
search_url = f"https://duckduckgo.com/html/?q={quote_plus(query)}"
|
78 |
+
|
79 |
+
headers = {
|
80 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
|
81 |
+
}
|
82 |
+
|
83 |
+
response = requests.get(search_url, headers=headers, timeout=10)
|
84 |
+
response.raise_for_status()
|
85 |
+
|
86 |
+
soup = BeautifulSoup(response.content, 'html.parser')
|
87 |
+
|
88 |
+
# Extract search results
|
89 |
+
results = []
|
90 |
+
result_links = soup.find_all('a', class_='result__a')[:5] # Get top 5 results
|
91 |
+
|
92 |
+
for i, link in enumerate(result_links, 1):
|
93 |
+
title = link.get_text(strip=True)
|
94 |
+
if title:
|
95 |
+
results.append(f"{i}. {title}")
|
96 |
+
|
97 |
+
if results:
|
98 |
+
return f"**Search Results for '{query}':**\n" + "\n".join(results)
|
99 |
+
else:
|
100 |
+
return f"No results found for '{query}'. Try different keywords."
|
101 |
+
|
102 |
+
except Exception as e:
|
103 |
+
return f"Error in backup search: {str(e)}"
|
104 |
+
|
105 |
def search_web(query):
|
106 |
"""
|
107 |
+
Main web search function that tries multiple methods.
|
108 |
Args:
|
109 |
query (str): The search query
|
110 |
Returns:
|
111 |
+
str: Formatted search results
|
112 |
"""
|
113 |
+
if not query.strip():
|
114 |
+
return "Please enter a search query."
|
115 |
+
|
116 |
+
# Try DuckDuckGo API first
|
117 |
+
result = search_web_duckduckgo(query)
|
118 |
+
|
119 |
+
# If API fails, try scraping method
|
120 |
+
if "Error" in result:
|
121 |
+
print("API method failed, trying scraping method...")
|
122 |
+
result = search_web_scraper(query)
|
123 |
+
|
124 |
+
return result
|
125 |
|
126 |
def format_response(raw_steps):
|
127 |
"""
|
|
|
131 |
Returns:
|
132 |
str: Formatted numbered list of steps
|
133 |
"""
|
134 |
+
if not raw_steps.strip():
|
135 |
+
return "Please enter some text to format."
|
136 |
+
|
137 |
steps = raw_steps.split(". ")
|
138 |
steps = [f"{i+1}. {step.strip('.')}" for i, step in enumerate(steps) if step.strip()]
|
139 |
return "\n".join(steps)
|
|
|
141 |
# Knowledge Base Search Interface
|
142 |
demo1 = gr.Interface(
|
143 |
fn=search_knowledge_base,
|
144 |
+
inputs=[gr.Textbox(label="Technical Issue", placeholder="Enter your technical problem (e.g., wifi connection problem)")],
|
145 |
+
outputs=[gr.Textbox(label="Solution")],
|
146 |
title="Knowledge Base Search",
|
147 |
description="Enter a technical issue to search for solutions in the knowledge base."
|
148 |
)
|
149 |
|
150 |
+
# Web Search Interface
|
151 |
demo2 = gr.Interface(
|
152 |
fn=search_web,
|
153 |
+
inputs=[gr.Textbox(label="Search Query", placeholder="Enter your search query (e.g., latest tech news)")],
|
154 |
+
outputs=[gr.Textbox(label="Search Results")],
|
155 |
title="Web Search",
|
156 |
+
description="Enter a search query to get real web search results from DuckDuckGo."
|
157 |
)
|
158 |
|
159 |
# Response Formatter Interface
|
160 |
demo3 = gr.Interface(
|
161 |
fn=format_response,
|
162 |
+
inputs=[gr.Textbox(label="Raw Steps", placeholder="Enter steps separated by periods")],
|
163 |
+
outputs=[gr.Textbox(label="Formatted Steps")],
|
164 |
title="Response Formatter",
|
165 |
description="Enter raw steps separated by periods to format them as a numbered list."
|
166 |
)
|
167 |
|
168 |
+
# Combine all interfaces using Tabs
|
169 |
demo = gr.TabbedInterface([demo1, demo2, demo3], ["Knowledge Base", "Web Search", "Formatter"])
|
170 |
|
171 |
if __name__ == "__main__":
|
172 |
+
demo.launch(share=True) # Added share=True for public access
|