seawolf2357 commited on
Commit
6097fb2
โ€ข
1 Parent(s): 2efa0ec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -80
app.py CHANGED
@@ -1,98 +1,78 @@
1
  import gradio as gr
2
  import requests
3
- import json
4
- from functools import lru_cache
5
- from datetime import datetime, timedelta
6
 
7
- # Google Custom Search API ํ‚ค์™€ ๊ฒ€์ƒ‰ ์—”์ง„ ID
8
- API_KEY = "AIzaSyB8wNdEL8-SAvelRq-zenLLU-cUEmsj7uE"
9
- SEARCH_ENGINE_ID = "c01abc75e1b95483d"
10
 
11
- # ์ง€์›๋˜๋Š” ๊ตญ๊ฐ€ ๋ฆฌ์ŠคํŠธ
12
- COUNTRIES = {
13
- 'United States': 'US', 'United Kingdom': 'GB', 'Canada': 'CA', 'Australia': 'AU', 'India': 'IN',
14
- 'Germany': 'DE', 'France': 'FR', 'Japan': 'JP', 'South Korea': 'KR', 'Brazil': 'BR',
15
- 'Mexico': 'MX', 'Spain': 'ES', 'Italy': 'IT', 'Netherlands': 'NL', 'Russia': 'RU',
16
- 'Sweden': 'SE', 'Switzerland': 'CH', 'Poland': 'PL', 'Turkey': 'TR', 'Saudi Arabia': 'SA'
17
- }
18
 
19
- @lru_cache(maxsize=100)
20
- def cached_search(cache_key):
21
- return search_news_impl(*json.loads(cache_key))
22
-
23
- def search_news(keyword, country):
24
- cache_key = json.dumps((keyword, country))
25
- return cached_search(cache_key)
26
-
27
- def search_news_impl(keyword, country):
28
- url = "https://www.googleapis.com/customsearch/v1"
29
-
30
- # 24์‹œ๊ฐ„ ์ „ ๋‚ ์งœ ๊ณ„์‚ฐ
31
- one_day_ago = (datetime.utcnow() - timedelta(days=1)).strftime("%Y-%m-%d")
32
 
33
  params = {
34
- 'key': API_KEY,
35
- 'cx': SEARCH_ENGINE_ID,
36
- 'q': keyword,
37
- 'dateRestrict': 'd1', # ์ตœ๊ทผ 1์ผ ๋‚ด ๊ฒฐ๊ณผ๋งŒ
38
- 'sort': 'date', # ๋‚ ์งœ์ˆœ ์ •๋ ฌ
39
- 'num': 10, # ๊ฒฐ๊ณผ ์ˆ˜
40
- 'tbm': 'nws', # ๋‰ด์Šค ๊ฒ€์ƒ‰์œผ๋กœ ์ œํ•œ
 
 
 
 
41
  }
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- if country != 'All Countries':
44
- params['gl'] = COUNTRIES[country]
45
-
46
- try:
47
- response = requests.get(url, params=params)
48
- response.raise_for_status()
49
- results = response.json()
50
-
51
- debug_info = f"API Request URL: {response.url}\n"
52
- debug_info += f"API Response Status: {response.status_code}\n"
53
- debug_info += f"API Response Headers: {json.dumps(dict(response.headers), indent=2)}\n"
54
- debug_info += f"API Response Body: {json.dumps(results, indent=2)}\n"
55
-
56
  formatted_results = ""
57
- if 'items' in results:
58
- for item in results['items']:
59
- title = item['title']
60
- link = item['link']
61
- snippet = item.get('snippet', 'No snippet available')
62
- published_date = item.get('pagemap', {}).get('metatags', [{}])[0].get('article:published_time', 'Unknown date')
63
- formatted_results += f"<h3><a href='{link}' target='_blank'>{title}</a></h3>"
64
- formatted_results += f"<p>Published: {published_date}</p>"
65
- formatted_results += f"<p>{snippet}</p><br>"
66
- formatted_results += f"<p>Total results: {len(results['items'])}</p>"
67
- else:
68
- formatted_results = f"No news found for '{keyword}' in {country} within the last 24 hours."
69
-
70
- except requests.exceptions.HTTPError as e:
71
- formatted_results = f"An error occurred: {str(e)}"
72
- debug_info = f"Error: {str(e)}\n"
73
- debug_info += f"API Response Status: {e.response.status_code}\n"
74
- debug_info += f"API Response Headers: {json.dumps(dict(e.response.headers), indent=2)}\n"
75
- debug_info += f"API Response Body: {e.response.text}\n"
76
-
77
- except Exception as e:
78
- formatted_results = f"An unexpected error occurred: {str(e)}"
79
- debug_info = f"Unexpected Error: {str(e)}\n"
80
-
81
- formatted_results += f"<details><summary>Debug Info</summary><pre>{debug_info}</pre></details>"
82
 
83
- return formatted_results
 
 
84
 
85
- # Gradio ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์„ฑ
86
  iface = gr.Interface(
87
- fn=search_news,
88
  inputs=[
89
- gr.Textbox(label="Enter keyword (in English)"),
90
- gr.Dropdown(choices=['All Countries'] + list(COUNTRIES.keys()), label="Select Country")
 
 
 
 
 
 
 
 
 
91
  ],
92
- outputs=gr.HTML(),
93
- title="Google News Search",
94
- description="Search for news articles from the last 24 hours using Google Custom Search API."
95
  )
96
 
97
- # ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜ ์‹คํ–‰
98
  iface.launch()
 
1
  import gradio as gr
2
  import requests
 
 
 
3
 
4
+ API_KEY = "V38CNn4HXpLtynJQyOeoUensTEYoFy8PBUxKpDqAW1pawT1vfJ2BWtPQ98h6"
 
 
5
 
6
+ # List of English-speaking countries supported by SERPHouse API
7
+ ENGLISH_SPEAKING_COUNTRIES = [
8
+ "United States", "United Kingdom", "Canada", "Australia", "New Zealand",
9
+ "Ireland", "South Africa", "Jamaica", "Trinidad and Tobago", "Guyana",
10
+ "Belize", "Barbados", "Bahamas", "Antigua and Barbuda", "Saint Kitts and Nevis",
11
+ "Dominica", "Saint Lucia", "Saint Vincent and the Grenadines", "Grenada"
12
+ ]
13
 
14
+ def search_serphouse(query, domain, language, device, serp_type, location, country, verbatim, gfilter, page, num_result):
15
+ url = "https://api.serphouse.com/serp/live"
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  params = {
18
+ "q": query,
19
+ "domain": domain,
20
+ "lang": language,
21
+ "device": device,
22
+ "serp_type": serp_type,
23
+ "loc": location,
24
+ "country": country, # Added country parameter
25
+ "verbatim": verbatim,
26
+ "gfilter": gfilter,
27
+ "page": page,
28
+ "num_result": num_result
29
  }
30
+
31
+ headers = {
32
+ "Authorization": f"Bearer {API_KEY}"
33
+ }
34
+
35
+ response = requests.get(url, params=params, headers=headers)
36
+
37
+ if response.status_code == 200:
38
+ return response.json()
39
+ else:
40
+ return f"Error: {response.status_code} - {response.text}"
41
 
42
+ def format_results(results):
43
+ if isinstance(results, dict) and "results" in results:
44
+ organic_results = results["results"].get("organic", [])
 
 
 
 
 
 
 
 
 
 
45
  formatted_results = ""
46
+ for i, result in enumerate(organic_results, 1):
47
+ formatted_results += f"{i}. {result['title']}\n"
48
+ formatted_results += f" URL: {result['link']}\n"
49
+ formatted_results += f" Snippet: {result['snippet']}\n\n"
50
+ return formatted_results
51
+ else:
52
+ return str(results)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ def serphouse_search(query, domain, language, device, serp_type, location, country, verbatim, gfilter, page, num_result):
55
+ results = search_serphouse(query, domain, language, device, serp_type, location, country, verbatim, gfilter, page, num_result)
56
+ return format_results(results)
57
 
 
58
  iface = gr.Interface(
59
+ fn=serphouse_search,
60
  inputs=[
61
+ gr.Textbox(label="Search Query"),
62
+ gr.Dropdown(["google.com", "google.co.uk", "google.ca", "google.com.au"], label="Domain"),
63
+ gr.Dropdown(["en"], label="Language"),
64
+ gr.Radio(["desktop", "mobile"], label="Device"),
65
+ gr.Dropdown(["web", "news", "images"], label="SERP Type"),
66
+ gr.Textbox(label="Location"),
67
+ gr.Dropdown(ENGLISH_SPEAKING_COUNTRIES, label="Country"), # Added country dropdown
68
+ gr.Checkbox(label="Verbatim"),
69
+ gr.Checkbox(label="Google Filter"),
70
+ gr.Slider(1, 10, 1, label="Page"),
71
+ gr.Slider(1, 100, 10, label="Number of Results")
72
  ],
73
+ outputs="text",
74
+ title="SERPHouse Search Interface",
75
+ description="Enter your search parameters to get results from the SERPHouse API. You can now select an English-speaking country."
76
  )
77
 
 
78
  iface.launch()