Shreyas094 commited on
Commit
851f58a
·
verified ·
1 Parent(s): 5a18aa8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -36
app.py CHANGED
@@ -1,22 +1,9 @@
1
  import gradio as gr
2
  import requests
3
- from tenacity import retry, wait_exponential, stop_after_attempt, retry_if_exception_type
4
- import json
5
 
6
- # Define custom exceptions for clarity
7
- class RateLimitException(Exception):
8
- pass
9
-
10
- # Retry configuration: Retry up to 5 times with exponential backoff
11
- @retry(
12
- wait=wait_exponential(multiplier=1, min=4, max=10),
13
- stop=stop_after_attempt(5),
14
- retry=retry_if_exception_type(RateLimitException)
15
- )
16
  def search_searx(query, instance_url='https://searx.org', categories='general'):
17
  """
18
- Perform a search using the Searx API with retry logic.
19
-
20
  :param query: The search query string.
21
  :param instance_url: The URL of the Searx instance.
22
  :param categories: Categories to search in (e.g., 'general', 'images', 'videos').
@@ -33,39 +20,29 @@ def search_searx(query, instance_url='https://searx.org', categories='general'):
33
  'safesearch': '0' # Safe search (0: off, 1: moderate, 2: strict)
34
  }
35
 
 
36
  headers = {
37
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
38
- 'AppleWebKit/537.36 (KHTML, like Gecko) ' +
39
- 'Chrome/58.0.3029.110 Safari/537.3'
40
  }
41
-
42
  try:
43
  response = requests.get(search_endpoint, params=params, headers=headers, timeout=10)
44
- if response.status_code == 429:
45
- raise RateLimitException("Rate limit exceeded. Retrying...")
46
  response.raise_for_status() # Raise an error for bad status codes
47
  data = response.json()
48
 
49
  if 'results' not in data or not data['results']:
50
  return "No results found."
51
-
52
  formatted_results = ""
53
  for idx, result in enumerate(data['results'], start=1):
54
  title = result.get('title', 'No Title')
55
  url = result.get('url', 'No URL')
56
  snippet = result.get('content', 'No Description')
57
- # Using Markdown link formatting
58
- formatted_results += f"**{idx}. [{title}]({url})**\n{snippet}\n\n"
59
-
60
  return formatted_results
61
-
62
- except RateLimitException as e:
63
- # After retries, if still failing due to rate limits
64
- return f"Rate limit exceeded. Please try again later.\nError: {e}"
65
  except requests.exceptions.RequestException as e:
66
  return f"An error occurred while searching: {e}"
67
- except json.JSONDecodeError:
68
- return "Failed to parse the response from the Searx instance."
69
 
70
  def create_gradio_interface():
71
  """
@@ -76,7 +53,6 @@ def create_gradio_interface():
76
  gr.Markdown(
77
  "This application allows you to perform private searches using the [Searx](https://searx.org/) metasearch engine."
78
  )
79
-
80
  with gr.Row():
81
  with gr.Column():
82
  query = gr.Textbox(
@@ -97,26 +73,25 @@ def create_gradio_interface():
97
  lines=1
98
  )
99
  search_button = gr.Button("Search")
100
-
101
  with gr.Column():
102
  results = gr.Markdown("### Search Results will appear here...")
103
-
104
  def perform_search(q, url, cats):
105
  return search_searx(q, instance_url=url, categories=cats)
106
-
107
  search_button.click(
108
  perform_search,
109
  inputs=[query, instance_url, categories],
110
  outputs=results
111
  )
112
-
113
  gr.Markdown(
114
  """
115
  ---
116
  **Note:** This application uses the Searx metasearch engine to fetch results from multiple sources while preserving your privacy.
117
  """
118
  )
119
-
120
  return demo
121
 
122
  iface = create_gradio_interface()
 
1
  import gradio as gr
2
  import requests
 
 
3
 
 
 
 
 
 
 
 
 
 
 
4
  def search_searx(query, instance_url='https://searx.org', categories='general'):
5
  """
6
+ Perform a search using the Searx API.
 
7
  :param query: The search query string.
8
  :param instance_url: The URL of the Searx instance.
9
  :param categories: Categories to search in (e.g., 'general', 'images', 'videos').
 
20
  'safesearch': '0' # Safe search (0: off, 1: moderate, 2: strict)
21
  }
22
 
23
+ # Define a user agent
24
  headers = {
25
+ 'User-Agent': 'SearxGradioApp/1.0 (https://github.com/yourusername/searx-gradio-app)'
 
 
26
  }
27
+
28
  try:
29
  response = requests.get(search_endpoint, params=params, headers=headers, timeout=10)
 
 
30
  response.raise_for_status() # Raise an error for bad status codes
31
  data = response.json()
32
 
33
  if 'results' not in data or not data['results']:
34
  return "No results found."
35
+
36
  formatted_results = ""
37
  for idx, result in enumerate(data['results'], start=1):
38
  title = result.get('title', 'No Title')
39
  url = result.get('url', 'No URL')
40
  snippet = result.get('content', 'No Description')
41
+ formatted_results += f"**{idx}. {title}**\n[{url}]({url})\n{snippet}\n\n"
42
+
 
43
  return formatted_results
 
 
 
 
44
  except requests.exceptions.RequestException as e:
45
  return f"An error occurred while searching: {e}"
 
 
46
 
47
  def create_gradio_interface():
48
  """
 
53
  gr.Markdown(
54
  "This application allows you to perform private searches using the [Searx](https://searx.org/) metasearch engine."
55
  )
 
56
  with gr.Row():
57
  with gr.Column():
58
  query = gr.Textbox(
 
73
  lines=1
74
  )
75
  search_button = gr.Button("Search")
 
76
  with gr.Column():
77
  results = gr.Markdown("### Search Results will appear here...")
78
+
79
  def perform_search(q, url, cats):
80
  return search_searx(q, instance_url=url, categories=cats)
81
+
82
  search_button.click(
83
  perform_search,
84
  inputs=[query, instance_url, categories],
85
  outputs=results
86
  )
87
+
88
  gr.Markdown(
89
  """
90
  ---
91
  **Note:** This application uses the Searx metasearch engine to fetch results from multiple sources while preserving your privacy.
92
  """
93
  )
94
+
95
  return demo
96
 
97
  iface = create_gradio_interface()