rkihacker commited on
Commit
b269676
·
verified ·
1 Parent(s): 2633cdd

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +74 -0
main.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import httpx
2
+ from bs4 import BeautifulSoup
3
+ from fastapi import FastAPI, HTTPException
4
+ from pydantic import BaseModel
5
+ import uvicorn
6
+
7
+ app = FastAPI()
8
+
9
+ class SearchQuery(BaseModel):
10
+ query: str
11
+
12
+ class BraveSearch:
13
+ def __init__(self, query):
14
+ self.query = query
15
+ self.url = f"https://search.brave.com/search?q={query.replace(' ', '+')}&source=web"
16
+
17
+ async def fetch_results(self):
18
+ try:
19
+ async with httpx.AsyncClient() as client:
20
+ response = await client.get(self.url)
21
+ response.raise_for_status()
22
+
23
+ soup = BeautifulSoup(response.text, "html.parser")
24
+ results = {
25
+ "searchResults": [],
26
+ "additionalData": [],
27
+ "faq": []
28
+ }
29
+
30
+ for el in soup.select(".snippet"):
31
+ title = el.select_one(".title")
32
+ description = el.select_one(".snippet-description")
33
+ link = el.select_one("a")
34
+ results["searchResults"].append({
35
+ "title": title.text.strip() if title else "No Title",
36
+ "description": description.text.strip() if description else "No Description",
37
+ "link": link["href"] if link else "#"
38
+ })
39
+
40
+ for el in soup.select(".t-tertiary.svelte-1yt5tdo"):
41
+ attribution = el.select_one(".attribution")
42
+ citation_link = el.select_one("cite a")
43
+ results["additionalData"].append({
44
+ "attribution": attribution.text.strip() if attribution else "No Attribution",
45
+ "citationLink": citation_link["href"] if citation_link else "#"
46
+ })
47
+
48
+ for el in soup.select(".fq-item"):
49
+ question = el.select_one(".faq-q")
50
+ answer = el.select_one(".faq-a")
51
+ faq_link = el.select_one("a")
52
+ results["faq"].append({
53
+ "question": question.text.strip() if question else "No Question",
54
+ "answer": answer.text.strip() if answer else "No Answer",
55
+ "faqLink": faq_link["href"] if faq_link else "#"
56
+ })
57
+
58
+ return results
59
+ except httpx.HTTPStatusError as e:
60
+ raise HTTPException(status_code=e.response.status_code, detail=f"HTTP error occurred: {e}")
61
+ except Exception as e:
62
+ raise HTTPException(status_code=500, detail=f"An error occurred: {e}")
63
+
64
+ @app.post("/search")
65
+ async def search(search_query: SearchQuery):
66
+ if not search_query.query:
67
+ raise HTTPException(status_code=400, detail="Query is required")
68
+
69
+ search = BraveSearch(search_query.query)
70
+ data = await search.fetch_results()
71
+ return data
72
+
73
+ if __name__ == "__main__":
74
+ uvicorn.run(app, host="0.0.0.0", port=8000)