Update app/main.py
Browse files4 unmodified lines5678910111213141516171 unmodified line192021222324252627283 unmodified lines323334353637383940414243444546474849505152535455565758593 unmodified lines636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091104 unmodified linesfrom newspaper import Articleimport pdfplumberimport requestsfrom typing import Optionalfrom bs4 import BeautifulSoupimport ioapp = FastAPI()# CORS middleware for frontend or external accessapp.add_middleware(CORSMiddleware,allow_origins=["*"],1 unmodified lineallow_headers=["*"],)# Load summarizer from local model directorysummarizer = pipeline("summarization", model="/app/model/t5-base")# Extract text from PDFdef extract_text_from_pdf(file):text = ""with pdfplumber.open(file) as pdf:3 unmodified linestext += page_text + "\n"return text.strip()# Extract text from URL (Wikipedia handled differently)def extract_text_from_url(url):try:if "wikipedia.org" in url:res = requests.get(url, timeout=10)res.raise_for_status()soup = BeautifulSoup(res.content, "html.parser")paragraphs = soup.find_all("p")text_content = "\n".join(p.text.strip() for p in paragraphs if p.text.strip())text_parts = text_content.split("\n")limited_text = "\n".join(text_parts[:50])return limited_text.strip()else:article = Article(url)article.download()article.parse()return article.text.strip()except Exception as e:print(f"URL extraction failed: {e}")return ""# Summarize contentdef generate_summary(text, mode="paragraph", length="medium"):length_map = {"short": 50,3 unmodified linesmax_new_tokens = length_map.get(length, 120)prompt_prefix = "summarize: " if mode == "paragraph" else "summarize as bullet points: "input_text = prompt_prefix + textsummary_result = summarizer(input_text,max_new_tokens=max_new_tokens,do_sample=False)return summary_result[0]['summary_text']# Health check@app.get("/")def home():return {"message": "✅ AI Summarizer API Running!"}# Unified endpoint — text / pdf / url@app.post("/summarize")async def summarize(text: Optional[str] = Form(None),pdf_file: Optional[UploadFile] = File(None),url: Optional[str] = Form(None),mode: str = Form("paragraph"),length: str = Form("medium")):content = ""if text and text.strip():content = text.strip()elif pdf_file and pdf_file.filename:content = extract_text_from_pdf(pdf_file.file)if not content:return JSONResponse({"error": "❌ No readable text extracted from the PDF."}, 400)elif url and url.strip():content = extract_text_from_url(url.strip())if not content:return JSONResponse({"error": "❌ Unable to extract content from the URL."}, 400)else:return JSONResponse({"error": "❌ Provide either text, PDF file, or URL."}, 400)if len(content.split()) < 30:return JSONResponse({"error": "❌ Content too short. Minimum 30 words."}, 400)summary = generate_summary(content, mode=mode, length=length)return {"summary": summary,"originalLength": len(content),4 unmodified lines567891011121314151 unmodified line171819202122232425263 unmodified lines30313233343536373839404142434445464748493 unmodified lines53545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161174 unmodified linesfrom newspaper import Articleimport pdfplumberimport requestsfrom bs4 import BeautifulSoupapp = FastAPI()# CORS for frontend/web clientsapp.add_middleware(CORSMiddleware,allow_origins=["*"],1 unmodified lineallow_headers=["*"],)# Load summarizer modelsummarizer = pipeline("summarization", model="/app/model/t5-base")# PDF Text Extractordef extract_text_from_pdf(file):text = ""with pdfplumber.open(file) as pdf:3 unmodified linestext += page_text + "\n"return text.strip()# URL Text Extractordef extract_text_from_url(url):try:res = requests.get(url, timeout=10)res.raise_for_status()soup = BeautifulSoup(res.content, "html.parser")paragraphs = soup.find_all("p")text_content = "\n".join(p.text.strip() for p in paragraphs if p.text.strip())return "\n".join(text_content.split("\n")[:50])except Exception as e:print(f"URL extraction failed: {e}")return ""# Summarizer functiondef generate_summary(text, mode="paragraph", length="medium"):length_map = {"short": 50,3 unmodified linesmax_new_tokens = length_map.get(length, 120)prompt_prefix = "summarize: " if mode == "paragraph" else "summarize as bullet points: "input_text = prompt_prefix + textsummary_result = summarizer(input_text, max_new_tokens=max_new_tokens, do_sample=False)return summary_result[0]['summary_text']# Health check@app.get("/")def home():return {"message": "✅ AI Summarizer API running!"}# Summarize Text Endpoint@app.post("/summarize/text")async def summarize_text(text: str = Form(...),mode: str = Form("paragraph"),length: str = Form("medium")):content = text.strip()if len(content.split()) < 30:return JSONResponse({"error": "❌ Text too short. Minimum 30 words."}, status_code=400)summary = generate_summary(content, mode, length)return {"summary": summary,"originalLength": len(content),"summaryLength": len(summary),"mode": mode}# Summarize PDF Endpoint@app.post("/summarize/pdf")async def summarize_pdf(pdf_file: UploadFile = File(...),mode: str = Form("paragraph"),length: str = Form("medium")):content = extract_text_from_pdf(pdf_file.file)if not content:return JSONResponse({"error": "❌ No readable text extracted from the PDF."}, status_code=400)if len(content.split()) < 30:return JSONResponse({"error": "❌ Text too short. Minimum 30 words."}, status_code=400)summary = generate_summary(content, mode, length)return {"summary": summary,"originalLength": len(content),"summaryLength": len(summary),"mode": mode}# Summarize URL Endpoint@app.post("/summarize/url")async def summarize_url(url: str = Form(...),mode: str = Form("paragraph"),length: str = Form("medium")):content = extract_text_from_url(url)if not content:return JSONResponse({"error": "❌ Couldn’t extract text from URL."}, status_code=400)if len(content.split()) < 30:return JSONResponse({"error": "❌ Text too short. Minimum 30 words."}, status_code=400)summary = generate_summary(content, mode, length)return {"summary": summary,"originalLength": len(content),
app/main.py+58-51