student2222333051 commited on
Commit
41edee5
·
verified ·
1 Parent(s): 9477161

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +40 -17
main.py CHANGED
@@ -1,12 +1,20 @@
1
- from fastapi import FastAPI, UploadFile, File
 
 
 
2
  from fastapi.middleware.cors import CORSMiddleware
3
- from fastapi.responses import FileResponse
4
  from fastapi.staticfiles import StaticFiles
 
5
 
6
  from summarizer import generate_summary
7
  from pdf_reader import extract_text_from_pdf
8
 
9
- app = FastAPI()
 
 
 
 
10
 
11
  # CORS (frontend ↔ backend)
12
  app.add_middleware(
@@ -16,32 +24,47 @@ app.add_middleware(
16
  allow_headers=["*"],
17
  )
18
 
19
- # Барлық файлдар бір папкада static ретінде қосамыз
20
  app.mount("/static", StaticFiles(directory="."), name="static")
21
 
22
- # Frontend main page
23
  @app.get("/")
24
  async def root():
25
  return FileResponse("index.html")
26
 
27
- # TEXT summarization
28
  @app.post("/summarize/text")
29
  async def summarize_text(data: dict):
30
  text = data.get("text", "")
31
- if not text.strip():
32
- return {"summary": "No text provided."}
 
 
 
 
 
 
33
 
34
- summary = generate_summary(text)
35
- return {"summary": summary}
36
 
37
- # PDF summarization
38
  @app.post("/summarize/pdf")
39
  async def summarize_pdf(file: UploadFile = File(...)):
 
 
40
  pdf_bytes = await file.read()
41
- text = extract_text_from_pdf(pdf_bytes)
42
-
43
- if not text.strip():
44
- return {"summary": "PDF is empty or could not be processed."}
 
 
 
 
 
 
 
 
 
45
 
46
- summary = generate_summary(text)
47
- return {"summary": summary}
 
 
 
1
+ # main.py
2
+ import os
3
+ import logging
4
+ from fastapi import FastAPI, UploadFile, File, HTTPException
5
  from fastapi.middleware.cors import CORSMiddleware
6
+ from fastapi.responses import FileResponse, JSONResponse
7
  from fastapi.staticfiles import StaticFiles
8
+ from starlette.status import HTTP_400_BAD_REQUEST, HTTP_500_INTERNAL_SERVER_ERROR
9
 
10
  from summarizer import generate_summary
11
  from pdf_reader import extract_text_from_pdf
12
 
13
+ # Логтау
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger("summarizer_app")
16
+
17
+ app = FastAPI(title="Scientific Article Summarizer")
18
 
19
  # CORS (frontend ↔ backend)
20
  app.add_middleware(
 
24
  allow_headers=["*"],
25
  )
26
 
27
+ # Статикалық файлдар жобаның түбірінен береді
28
  app.mount("/static", StaticFiles(directory="."), name="static")
29
 
 
30
  @app.get("/")
31
  async def root():
32
  return FileResponse("index.html")
33
 
 
34
  @app.post("/summarize/text")
35
  async def summarize_text(data: dict):
36
  text = data.get("text", "")
37
+ if not text or not text.strip():
38
+ raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="No text provided.")
39
+ try:
40
+ summary = generate_summary(text)
41
+ return {"summary": summary}
42
+ except Exception as e:
43
+ logger.exception("Error while generating text summary")
44
+ raise HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
45
 
46
+ MAX_PDF_BYTES = int(os.getenv("MAX_PDF_BYTES", 10 * 1024 * 1024)) # 10 MB default
 
47
 
 
48
  @app.post("/summarize/pdf")
49
  async def summarize_pdf(file: UploadFile = File(...)):
50
+ if not file.filename.lower().endswith(".pdf"):
51
+ raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="Only PDF files are supported.")
52
  pdf_bytes = await file.read()
53
+ if len(pdf_bytes) == 0:
54
+ raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail="Uploaded PDF is empty.")
55
+ if len(pdf_bytes) > MAX_PDF_BYTES:
56
+ raise HTTPException(status_code=HTTP_400_BAD_REQUEST, detail=f"PDF too large (max {MAX_PDF_BYTES} bytes).")
57
+ try:
58
+ text = extract_text_from_pdf(pdf_bytes)
59
+ if not text or not text.strip():
60
+ return {"summary": "PDF is empty or could not be processed."}
61
+ summary = generate_summary(text)
62
+ return {"summary": summary}
63
+ except Exception as e:
64
+ logger.exception("Error while processing PDF")
65
+ raise HTTPException(status_code=HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
66
 
67
+ # Custom error handler example
68
+ @app.exception_handler(HTTPException)
69
+ async def http_exception_handler(request, exc: HTTPException):
70
+ return JSONResponse(status_code=exc.status_code, content={"error": exc.detail})