NihalGazi commited on
Commit
a204909
·
verified ·
1 Parent(s): 23ffa03

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -0
app.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.responses import HTMLResponse
3
+ from newspaper import Article
4
+ import requests
5
+ from bs4 import BeautifulSoup
6
+
7
+ app = FastAPI()
8
+
9
+ # 1. Extract text + title from input URL
10
+ def extract_text_from_url(url: str):
11
+ article = Article(url)
12
+ article.download()
13
+ article.parse()
14
+ return article.title, article.text
15
+
16
+ # 2. Ask Pollinations to generate a Wikipedia-style HTML page
17
+ def generate_ai_wiki(topic: str, content: str):
18
+ prompt = (
19
+ f"Write a detailed Wikipedia-style article about '{topic}'. "
20
+ f"Base it loosely on this content: {content[:2000]} "
21
+ f"Use headings, sections, references. Return in valid HTML format."
22
+ )
23
+ r = requests.get("https://text.pollinations.ai/prompt/" + prompt)
24
+ return r.text
25
+
26
+ # 3. Rewrite all internal links to loop back to this app (/wikipedia/)
27
+ def rewrite_links(html: str):
28
+ soup = BeautifulSoup(html, "html.parser")
29
+ for a in soup.find_all("a", href=True):
30
+ topic = a.get_text().strip().replace(" ", "_")
31
+ a["href"] = f"/wikipedia/{topic}"
32
+ return str(soup)
33
+
34
+ # 4. Endpoint: Generate article from URL
35
+ @app.get("/wikipedia/")
36
+ def generate_from_url(url: str):
37
+ title, content = extract_text_from_url(url)
38
+ raw_html = generate_ai_wiki(title, content)
39
+ final_html = rewrite_links(raw_html)
40
+ return HTMLResponse(final_html)
41
+
42
+ # 5. Endpoint: Direct topic access (/wikipedia/<topic>)
43
+ @app.get("/wikipedia/{topic}")
44
+ def generate_from_topic(topic: str):
45
+ raw_html = generate_ai_wiki(topic, "")
46
+ final_html = rewrite_links(raw_html)
47
+ return HTMLResponse(final_html)