ikraamkb commited on
Commit
d0fd428
·
verified ·
1 Parent(s): 6f78a44

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +24 -41
main.py CHANGED
@@ -1,4 +1,4 @@
1
- from fastapi import FastAPI, UploadFile, Form, Request, File
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
4
  from fastapi.staticfiles import StaticFiles
@@ -7,9 +7,10 @@ import os
7
  import tempfile
8
  from typing import Optional
9
 
 
10
  app = FastAPI()
11
 
12
- # CORS Configuration
13
  app.add_middleware(
14
  CORSMiddleware,
15
  allow_origins=["*"],
@@ -18,75 +19,57 @@ app.add_middleware(
18
  allow_headers=["*"],
19
  )
20
 
21
- # Static assets
22
  app.mount("/static", StaticFiles(directory="static"), name="static")
23
  app.mount("/resources", StaticFiles(directory="resources"), name="resources")
24
-
25
- # Templates
26
  templates = Jinja2Templates(directory="templates")
27
 
 
 
28
  @app.get("/", response_class=HTMLResponse)
29
  async def serve_home(request: Request):
30
  return templates.TemplateResponse("HomeS.html", {"request": request})
31
 
 
 
32
  @app.post("/summarize/")
33
- async def summarize_document(file: UploadFile = File(...), length: str = Form("medium")):
34
  try:
35
  from app import summarize_api
36
  return await summarize_api(file, length)
37
- except ImportError as e:
38
- return JSONResponse(
39
- {"error": f"Summarization module not available: {str(e)}"},
40
- status_code=501
41
- )
42
  except Exception as e:
43
- return JSONResponse(
44
- {"error": f"Summarization failed: {str(e)}"},
45
- status_code=500
46
- )
47
 
48
  @app.post("/imagecaption/")
49
- async def caption_image(file: UploadFile = File(...)):
50
  try:
51
  from appImage import caption_from_frontend
52
  return await caption_from_frontend(file)
53
- except ImportError as e:
54
- return JSONResponse(
55
- {"error": f"Image captioning module not available: {str(e)}"},
56
- status_code=501
57
- )
58
  except Exception as e:
59
- return JSONResponse(
60
- {"error": f"Image captioning failed: {str(e)}"},
61
- status_code=500
62
- )
63
 
64
  @app.get("/files/{filename}")
65
  async def serve_file(filename: str):
66
- file_path = os.path.join(tempfile.gettempdir(), filename)
67
- if os.path.exists(file_path):
68
- return FileResponse(file_path)
69
  return JSONResponse({"error": "File not found"}, status_code=404)
70
 
71
- # Optional unified endpoint
72
  @app.post("/predict")
73
  async def predict(
74
  file: UploadFile = File(...),
75
- option: str = Form(...), # "Summarize" or "Captioning"
76
- length: Optional[str] = Form(None) # Only for summarize
77
  ):
78
  try:
79
  if option == "Summarize":
80
- return await summarize_document(file, length or "medium")
81
  elif option == "Captioning":
82
- return await caption_image(file)
83
  else:
84
- return JSONResponse(
85
- {"error": "Invalid option - must be 'Summarize' or 'Captioning'"},
86
- status_code=400
87
- )
88
  except Exception as e:
89
- return JSONResponse(
90
- {"error": f"Prediction failed: {str(e)}"},
91
- status_code=500
92
- )
 
1
+ from fastapi import FastAPI, UploadFile, File, Form, Request
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from fastapi.responses import HTMLResponse, JSONResponse, FileResponse
4
  from fastapi.staticfiles import StaticFiles
 
7
  import tempfile
8
  from typing import Optional
9
 
10
+ # Initialize FastAPI
11
  app = FastAPI()
12
 
13
+ # CORS Policy: allow everything (because Hugging Face Spaces needs it open)
14
  app.add_middleware(
15
  CORSMiddleware,
16
  allow_origins=["*"],
 
19
  allow_headers=["*"],
20
  )
21
 
22
+ # Static files and templates
23
  app.mount("/static", StaticFiles(directory="static"), name="static")
24
  app.mount("/resources", StaticFiles(directory="resources"), name="resources")
 
 
25
  templates = Jinja2Templates(directory="templates")
26
 
27
+ # --- Serve Frontend ---
28
+
29
  @app.get("/", response_class=HTMLResponse)
30
  async def serve_home(request: Request):
31
  return templates.TemplateResponse("HomeS.html", {"request": request})
32
 
33
+ # --- API Endpoints that frontend needs ---
34
+
35
  @app.post("/summarize/")
36
+ async def summarize_document_endpoint(file: UploadFile = File(...), length: str = Form("medium")):
37
  try:
38
  from app import summarize_api
39
  return await summarize_api(file, length)
 
 
 
 
 
40
  except Exception as e:
41
+ return JSONResponse({"error": f"Summarization failed: {str(e)}"}, status_code=500)
 
 
 
42
 
43
  @app.post("/imagecaption/")
44
+ async def caption_image_endpoint(file: UploadFile = File(...)):
45
  try:
46
  from appImage import caption_from_frontend
47
  return await caption_from_frontend(file)
 
 
 
 
 
48
  except Exception as e:
49
+ return JSONResponse({"error": f"Image captioning failed: {str(e)}"}, status_code=500)
50
+
51
+ # --- Serve generated audio/pdf files ---
 
52
 
53
  @app.get("/files/{filename}")
54
  async def serve_file(filename: str):
55
+ path = os.path.join(tempfile.gettempdir(), filename)
56
+ if os.path.exists(path):
57
+ return FileResponse(path)
58
  return JSONResponse({"error": "File not found"}, status_code=404)
59
 
60
+ # (Optional) Unified prediction endpoint — Only if you want
61
  @app.post("/predict")
62
  async def predict(
63
  file: UploadFile = File(...),
64
+ option: str = Form(...), # "Summarize" or "Captioning"
65
+ length: Optional[str] = Form(None) # Only for Summarize
66
  ):
67
  try:
68
  if option == "Summarize":
69
+ return await summarize_document_endpoint(file, length or "medium")
70
  elif option == "Captioning":
71
+ return await caption_image_endpoint(file)
72
  else:
73
+ return JSONResponse({"error": "Invalid option"}, status_code=400)
 
 
 
74
  except Exception as e:
75
+ return JSONResponse({"error": f"Prediction failed: {str(e)}"}, status_code=500)