Niansuh commited on
Commit
50baff6
1 Parent(s): 06cd8c2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +398 -0
app.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, Query # Make sure Query is imported
2
+ from fastapi.responses import JSONResponse
3
+ from webscout import WEBS, transcriber, LLM
4
+ from typing import Optional, List, Dict, Union # Import List, Dict, Union
5
+ from fastapi.encoders import jsonable_encoder
6
+ from bs4 import BeautifulSoup
7
+ import requests
8
+ import urllib.parse
9
+
10
+ app = FastAPI()
11
+
12
+ @app.get("/")
13
+ async def root():
14
+ return {"message": "API documentation can be found at /docs"}
15
+
16
+ @app.get("/health")
17
+ async def health_check():
18
+ return {"status": "OK"}
19
+
20
+ @app.get("/api/search")
21
+ async def search(
22
+ q: str,
23
+ max_results: int = 10,
24
+ timelimit: Optional[str] = None,
25
+ safesearch: str = "moderate",
26
+ region: str = "wt-wt",
27
+ backend: str = "api"
28
+ ):
29
+ """Perform a text search."""
30
+ try:
31
+ with WEBS() as webs:
32
+ results = webs.text(keywords=q, region=region, safesearch=safesearch, timelimit=timelimit, backend=backend, max_results=max_results)
33
+ return JSONResponse(content=jsonable_encoder(results))
34
+ except Exception as e:
35
+ raise HTTPException(status_code=500, detail=f"Error during search: {e}")
36
+
37
+ @app.get("/api/images")
38
+ async def images(
39
+ q: str,
40
+ max_results: int = 10,
41
+ safesearch: str = "moderate",
42
+ region: str = "wt-wt",
43
+ timelimit: Optional[str] = None,
44
+ size: Optional[str] = None,
45
+ color: Optional[str] = None,
46
+ type_image: Optional[str] = None,
47
+ layout: Optional[str] = None,
48
+ license_image: Optional[str] = None
49
+ ):
50
+ """Perform an image search."""
51
+ try:
52
+ with WEBS() as webs:
53
+ results = webs.images(keywords=q, region=region, safesearch=safesearch, timelimit=timelimit, size=size, color=color, type_image=type_image, layout=layout, license_image=license_image, max_results=max_results)
54
+ return JSONResponse(content=jsonable_encoder(results))
55
+ except Exception as e:
56
+ raise HTTPException(status_code=500, detail=f"Error during image search: {e}")
57
+
58
+ @app.get("/api/videos")
59
+ async def videos(
60
+ q: str,
61
+ max_results: int = 10,
62
+ safesearch: str = "moderate",
63
+ region: str = "wt-wt",
64
+ timelimit: Optional[str] = None,
65
+ resolution: Optional[str] = None,
66
+ duration: Optional[str] = None,
67
+ license_videos: Optional[str] = None
68
+ ):
69
+ """Perform a video search."""
70
+ try:
71
+ with WEBS() as webs:
72
+ results = webs.videos(keywords=q, region=region, safesearch=safesearch, timelimit=timelimit, resolution=resolution, duration=duration, license_videos=license_videos, max_results=max_results)
73
+ return JSONResponse(content=jsonable_encoder(results))
74
+ except Exception as e:
75
+ raise HTTPException(status_code=500, detail=f"Error during video search: {e}")
76
+
77
+ @app.get("/api/news")
78
+ async def news(
79
+ q: str,
80
+ max_results: int = 10,
81
+ safesearch: str = "moderate",
82
+ region: str = "wt-wt",
83
+ timelimit: Optional[str] = None
84
+ ):
85
+ """Perform a news search."""
86
+ try:
87
+ with WEBS() as webs:
88
+ results = webs.news(keywords=q, region=region, safesearch=safesearch, timelimit=timelimit, max_results=max_results)
89
+ return JSONResponse(content=jsonable_encoder(results))
90
+ except Exception as e:
91
+ raise HTTPException(status_code=500, detail=f"Error during news search: {e}")
92
+
93
+ @app.get("/api/llm")
94
+ async def llm_chat(
95
+ model: str,
96
+ message: str,
97
+ system_prompt: str = Query(None, description="Optional custom system prompt")
98
+ ):
99
+ """Interact with a specified large language model with an optional system prompt."""
100
+ try:
101
+ messages = [{"role": "user", "content": message}]
102
+ if system_prompt:
103
+ messages.insert(0, {"role": "system", "content": system_prompt}) # Add system message at the beginning
104
+
105
+ llm = LLM(model=model)
106
+ response = llm.chat(messages=messages)
107
+ return JSONResponse(content={"response": response})
108
+ except Exception as e:
109
+ raise HTTPException(status_code=500, detail=f"Error during LLM chat: {e}")
110
+
111
+
112
+ @app.get("/api/answers")
113
+ async def answers(q: str):
114
+ """Get instant answers for a query."""
115
+ try:
116
+ with WEBS() as webs:
117
+ results = webs.answers(keywords=q)
118
+ return JSONResponse(content=jsonable_encoder(results))
119
+ except Exception as e:
120
+ raise HTTPException(status_code=500, detail=f"Error getting instant answers: {e}")
121
+
122
+ @app.get("/api/suggestions")
123
+ async def suggestions(q: str, region: str = "wt-wt"):
124
+ """Get search suggestions for a query."""
125
+ try:
126
+ with WEBS() as webs:
127
+ results = webs.suggestions(keywords=q, region=region)
128
+ return JSONResponse(content=jsonable_encoder(results))
129
+ except Exception as e:
130
+ raise HTTPException(status_code=500, detail=f"Error getting search suggestions: {e}")
131
+
132
+ @app.get("/api/chat")
133
+ async def chat(
134
+ q: str,
135
+ model: str = "gpt-3.5"
136
+ ):
137
+ """Perform a text search."""
138
+ try:
139
+ with WEBS() as webs:
140
+ results = webs.chat(keywords=q, model=model)
141
+ return JSONResponse(content=jsonable_encoder(results))
142
+ except Exception as e:
143
+ raise HTTPException(status_code=500, detail=f"Error getting chat results: {e}")
144
+
145
+ def extract_text_from_webpage(html_content):
146
+ """Extracts visible text from HTML content using BeautifulSoup."""
147
+ soup = BeautifulSoup(html_content, "html.parser")
148
+ # Remove unwanted tags
149
+ for tag in soup(["script", "style", "header", "footer", "nav"]):
150
+ tag.extract()
151
+ # Get the remaining visible text
152
+ visible_text = soup.get_text(strip=True)
153
+ return visible_text
154
+
155
+ @app.get("/api/web_extract")
156
+ async def web_extract(
157
+ url: str,
158
+ max_chars: int = 12000, # Adjust based on token limit
159
+ ):
160
+ """Extracts text from a given URL."""
161
+ try:
162
+ response = requests.get(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"})
163
+ response.raise_for_status()
164
+ visible_text = extract_text_from_webpage(response.text)
165
+ if len(visible_text) > max_chars:
166
+ visible_text = visible_text[:max_chars] + "..."
167
+ return {"url": url, "text": visible_text}
168
+ except requests.exceptions.RequestException as e:
169
+ raise HTTPException(status_code=500, detail=f"Error fetching or processing URL: {e}")
170
+
171
+ @app.get("/api/search-and-extract")
172
+ async def web_search_and_extract(
173
+ q: str,
174
+ max_results: int = 3,
175
+ timelimit: Optional[str] = None,
176
+ safesearch: str = "moderate",
177
+ region: str = "wt-wt",
178
+ backend: str = "api",
179
+ max_chars: int = 6000,
180
+ extract_only: bool = False
181
+ ):
182
+ """
183
+ Searches using WEBS, extracts text from the top results, and returns both.
184
+ """
185
+ try:
186
+ with WEBS() as webs:
187
+ # Perform WEBS search
188
+ search_results = webs.text(keywords=q, region=region, safesearch=safesearch,
189
+ timelimit=timelimit, backend=backend, max_results=max_results)
190
+
191
+ # Extract text from each result's link
192
+ extracted_results = []
193
+ for result in search_results:
194
+ if 'href' in result:
195
+ link = result['href']
196
+ try:
197
+ response = requests.get(link, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"})
198
+ response.raise_for_status()
199
+ visible_text = extract_text_from_webpage(response.text)
200
+ if len(visible_text) > max_chars:
201
+ visible_text = visible_text[:max_chars] + "..."
202
+ extracted_results.append({"link": link, "text": visible_text})
203
+ except requests.exceptions.RequestException as e:
204
+ print(f"Error fetching or processing {link}: {e}")
205
+ extracted_results.append({"link": link, "text": None})
206
+ else:
207
+ extracted_results.append({"link": None, "text": None})
208
+ if extract_only:
209
+ return JSONResponse(content=jsonable_encoder({extracted_results}))
210
+ else:
211
+ return JSONResponse(content=jsonable_encoder({"search_results": search_results, "extracted_results": extracted_results}))
212
+ except Exception as e:
213
+ raise HTTPException(status_code=500, detail=f"Error during search and extraction: {e}")
214
+
215
+ @app.get("/api/adv_web_search")
216
+ async def adv_web_search(
217
+ q: str,
218
+ model: str = "gpt-3.5",
219
+ max_results: int = 3,
220
+ timelimit: Optional[str] = None,
221
+ safesearch: str = "moderate",
222
+ region: str = "wt-wt",
223
+ backend: str = "api",
224
+ max_chars: int = 6000,
225
+ system_prompt: str = "You are Most Advanced and Powerful Ai chatbot, User ask you questions and you have to answer that, You are also provided with Google Search Results, To increase your accuracy and providing real time data. Your task is to answer in best way to user."
226
+ ):
227
+ """
228
+ Combines web search, web extraction, and LLM chat for advanced search.
229
+ """
230
+ try:
231
+ with WEBS() as webs:
232
+ # 1. Perform the web search
233
+ search_results = webs.text(keywords=q, region=region,
234
+ safesearch=safesearch,
235
+ timelimit=timelimit, backend=backend,
236
+ max_results=max_results)
237
+
238
+ # 2. Extract text from top search result URLs
239
+ extracted_text = ""
240
+ for result in search_results:
241
+ if 'href' in result:
242
+ link = result['href']
243
+ try:
244
+ response = requests.get(link, headers={"User-Agent": "Mozilla/5.0"})
245
+ response.raise_for_status()
246
+ visible_text = extract_text_from_webpage(response.text)
247
+ if len(visible_text) > max_chars:
248
+ visible_text = visible_text[:max_chars] + "..."
249
+ extracted_text += f"## Content from: {link}\n\n{visible_text}\n\n"
250
+ except requests.exceptions.RequestException as e:
251
+ print(f"Error fetching or processing {link}: {e}")
252
+ else:
253
+ pass
254
+
255
+ # 3. Construct the prompt for the LLM
256
+ llm_prompt = f"Query by user: {q} , Answer the query asked by user in detail. Now, You are provided with Google Search Results, To increase your accuracy and providing real time data. SEarch Result: {extracted_text}"
257
+
258
+ # 4. Get the LLM's response using LLM class (similar to /api/llm)
259
+ messages = [{"role": "user", "content": llm_prompt}]
260
+ if system_prompt:
261
+ messages.insert(0, {"role": "system", "content": system_prompt})
262
+
263
+ llm = LLM(model=model)
264
+ llm_response = llm.chat(messages=messages)
265
+
266
+ # 5. Return the results
267
+ return JSONResponse(content=jsonable_encoder({ "llm_response": llm_response }))
268
+
269
+ except Exception as e:
270
+ raise HTTPException(status_code=500, detail=f"Error during advanced search: {e}")
271
+
272
+
273
+ @app.get("/api/website_summarizer")
274
+ async def website_summarizer(url: str):
275
+ """Summarizes the content of a given URL using a chat model."""
276
+ try:
277
+ # Extract text from the given URL
278
+ response = requests.get(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"})
279
+ response.raise_for_status()
280
+ visible_text = extract_text_from_webpage(response.text)
281
+ if len(visible_text) > 7500: # Adjust max_chars based on your needs
282
+ visible_text = visible_text[:7500] + "..."
283
+
284
+ # Use chat model to summarize the extracted text
285
+ with WEBS() as webs:
286
+ summary_prompt = f"Summarize this in detail in Paragraph: {visible_text}"
287
+ summary_result = webs.chat(keywords=summary_prompt, model="gpt-3.5")
288
+
289
+ # Return the summary result
290
+ return JSONResponse(content=jsonable_encoder({summary_result}))
291
+
292
+ except requests.exceptions.RequestException as e:
293
+ raise HTTPException(status_code=500, detail=f"Error fetching or processing URL: {e}")
294
+ except Exception as e:
295
+ raise HTTPException(status_code=500, detail=f"Error during summarization: {e}")
296
+
297
+ @app.get("/api/ask_website")
298
+ async def ask_website(url: str, question: str, model: str = "llama-3-70b"):
299
+ """
300
+ Asks a question about the content of a given website.
301
+ """
302
+ try:
303
+ # Extract text from the given URL
304
+ response = requests.get(url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"})
305
+ response.raise_for_status()
306
+ visible_text = extract_text_from_webpage(response.text)
307
+ if len(visible_text) > 7500: # Adjust max_chars based on your needs
308
+ visible_text = visible_text[:7500] + "..."
309
+
310
+ # Construct a prompt for the chat model
311
+ prompt = f"Based on the following text, answer this question in Paragraph: [QUESTION] {question} [TEXT] {visible_text}"
312
+
313
+ # Use chat model to get the answer
314
+ with WEBS() as webs:
315
+ answer_result = webs.chat(keywords=prompt, model=model)
316
+
317
+ # Return the answer result
318
+ return JSONResponse(content=jsonable_encoder({answer_result}))
319
+
320
+ except requests.exceptions.RequestException as e:
321
+ raise HTTPException(status_code=500, detail=f"Error fetching or processing URL: {e}")
322
+ except Exception as e:
323
+ raise HTTPException(status_code=500, detail=f"Error during question answering: {e}")
324
+
325
+ @app.get("/api/maps")
326
+ async def maps(
327
+ q: str,
328
+ place: Optional[str] = None,
329
+ street: Optional[str] = None,
330
+ city: Optional[str] = None,
331
+ county: Optional[str] = None,
332
+ state: Optional[str] = None,
333
+ country: Optional[str] = None,
334
+ postalcode: Optional[str] = None,
335
+ latitude: Optional[str] = None,
336
+ longitude: Optional[str] = None,
337
+ radius: int = 0,
338
+ max_results: int = 10
339
+ ):
340
+ """Perform a maps search."""
341
+ try:
342
+ with WEBS() as webs:
343
+ results = webs.maps(keywords=q, place=place, street=street, city=city, county=county, state=state, country=country, postalcode=postalcode, latitude=latitude, longitude=longitude, radius=radius, max_results=max_results)
344
+ return JSONResponse(content=jsonable_encoder(results))
345
+ except Exception as e:
346
+ raise HTTPException(status_code=500, detail=f"Error during maps search: {e}")
347
+
348
+ @app.get("/api/translate")
349
+ async def translate(
350
+ q: str,
351
+ from_: Optional[str] = None,
352
+ to: str = "en"
353
+ ):
354
+ """Translate text."""
355
+ try:
356
+ with WEBS() as webs:
357
+ results = webs.translate(keywords=q, from_=from_, to=to)
358
+ return JSONResponse(content=jsonable_encoder(results))
359
+ except Exception as e:
360
+ raise HTTPException(status_code=500, detail=f"Error during translation: {e}")
361
+
362
+ @app.get("/api/youtube/transcript")
363
+ async def youtube_transcript(
364
+ video_id: str,
365
+ languages: str = "en",
366
+ preserve_formatting: bool = False
367
+ ):
368
+ """Get the transcript of a YouTube video."""
369
+ try:
370
+ languages_list = languages.split(",")
371
+ transcript = transcriber.get_transcript(video_id, languages=languages_list, preserve_formatting=preserve_formatting)
372
+ return JSONResponse(content=jsonable_encoder(transcript))
373
+ except Exception as e:
374
+ raise HTTPException(status_code=500, detail=f"Error getting YouTube transcript: {e}")
375
+
376
+ import requests
377
+ @app.get("/weather/json/{location}")
378
+ def get_weather_json(location: str):
379
+ url = f"https://wttr.in/{location}?format=j1"
380
+ response = requests.get(url)
381
+ if response.status_code == 200:
382
+ return response.json()
383
+ else:
384
+ return {"error": f"Unable to fetch weather data. Status code: {response.status_code}"}
385
+
386
+ @app.get("/weather/ascii/{location}")
387
+ def get_ascii_weather(location: str):
388
+ url = f"https://wttr.in/{location}"
389
+ response = requests.get(url, headers={'User-Agent': 'curl'})
390
+ if response.status_code == 200:
391
+ return response.text
392
+ else:
393
+ return {"error": f"Unable to fetch weather data. Status code: {response.status_code}"}
394
+
395
+ # Run the API server if this script is executed
396
+ if __name__ == "__main__":
397
+ import uvicorn
398
+ uvicorn.run(app, host="0.0.0.0", port=8083)