Avinashnalla7 commited on
Commit
7f82057
·
1 Parent(s): 5c30c41

Fix pdf upload/download storage paths + stop 500s

Browse files
Files changed (1) hide show
  1. backend/api.py +69 -16
backend/api.py CHANGED
@@ -1,50 +1,103 @@
1
  from __future__ import annotations
2
 
 
 
3
  from pathlib import Path
 
 
4
  from fastapi import FastAPI, UploadFile, File, Form, HTTPException
5
- from fastapi.responses import FileResponse
6
 
7
- app = FastAPI()
8
 
9
- PDF_DIR = Path("/data/uploads/pdfs")
 
 
10
  PDF_DIR.mkdir(parents=True, exist_ok=True)
 
 
11
 
12
  @app.get("/health")
13
- async def health():
14
  return {"ok": True}
15
 
 
16
  @app.post("/api/pdf/{pdf_id}")
17
  async def put_pdf(
18
  pdf_id: str,
19
  file: UploadFile = File(...),
20
- pdf_name: str = Form("")
21
- ):
22
  pdf_path = PDF_DIR / f"{pdf_id}.pdf"
23
  name_path = PDF_DIR / f"{pdf_id}.name.txt"
24
 
25
  data = await file.read()
26
- pdf_path.write_bytes(data)
27
- name_path.write_text(pdf_name or file.filename or f"{pdf_id}.pdf", encoding="utf-8")
 
 
 
 
 
 
 
 
 
28
 
29
- return {"ok": True}
30
 
31
  @app.get("/api/pdf/{pdf_id}")
32
  async def get_pdf(pdf_id: str):
33
  pdf_path = PDF_DIR / f"{pdf_id}.pdf"
34
- name_path = PDF_DIR / f"{pdf_id}.name.txt"
35
-
36
  if not pdf_path.exists():
37
  raise HTTPException(status_code=404, detail="pdf not found")
38
 
 
39
  filename = f"{pdf_id}.pdf"
40
- if name_path.exists():
41
- try:
42
- filename = name_path.read_text(encoding="utf-8").strip() or filename
43
- except Exception:
44
- pass
45
 
46
  return FileResponse(
47
  path=str(pdf_path),
48
  media_type="application/pdf",
49
  filename=filename,
 
50
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from __future__ import annotations
2
 
3
+ import json
4
+ import os
5
  from pathlib import Path
6
+ from typing import Any, Dict, Optional
7
+
8
  from fastapi import FastAPI, UploadFile, File, Form, HTTPException
9
+ from fastapi.responses import FileResponse, JSONResponse
10
 
11
+ app = FastAPI(title="PDF Trainer API", version="1.0")
12
 
13
+ DATA_DIR = Path(os.environ.get("DATA_DIR", "/data/uploads")).resolve()
14
+ PDF_DIR = DATA_DIR / "pdfs"
15
+ CFG_DIR = DATA_DIR / "configs"
16
  PDF_DIR.mkdir(parents=True, exist_ok=True)
17
+ CFG_DIR.mkdir(parents=True, exist_ok=True)
18
+
19
 
20
  @app.get("/health")
21
+ async def health() -> Dict[str, Any]:
22
  return {"ok": True}
23
 
24
+
25
  @app.post("/api/pdf/{pdf_id}")
26
  async def put_pdf(
27
  pdf_id: str,
28
  file: UploadFile = File(...),
29
+ pdf_name: Optional[str] = Form(None),
30
+ ) -> Dict[str, Any]:
31
  pdf_path = PDF_DIR / f"{pdf_id}.pdf"
32
  name_path = PDF_DIR / f"{pdf_id}.name.txt"
33
 
34
  data = await file.read()
35
+ if not data:
36
+ raise HTTPException(status_code=400, detail="empty upload")
37
+
38
+ try:
39
+ pdf_path.write_bytes(data)
40
+ final_name = (pdf_name or file.filename or f"{pdf_id}.pdf").strip() or f"{pdf_id}.pdf"
41
+ name_path.write_text(final_name, encoding="utf-8")
42
+ except Exception as e:
43
+ raise HTTPException(status_code=500, detail=f"failed to store pdf: {e}")
44
+
45
+ return {"ok": True, "pdf_id": pdf_id, "bytes": len(data)}
46
 
 
47
 
48
  @app.get("/api/pdf/{pdf_id}")
49
  async def get_pdf(pdf_id: str):
50
  pdf_path = PDF_DIR / f"{pdf_id}.pdf"
 
 
51
  if not pdf_path.exists():
52
  raise HTTPException(status_code=404, detail="pdf not found")
53
 
54
+ name_path = PDF_DIR / f"{pdf_id}.name.txt"
55
  filename = f"{pdf_id}.pdf"
56
+ try:
57
+ if name_path.exists():
58
+ filename = (name_path.read_text(encoding="utf-8").strip() or filename)
59
+ except Exception:
60
+ filename = f"{pdf_id}.pdf"
61
 
62
  return FileResponse(
63
  path=str(pdf_path),
64
  media_type="application/pdf",
65
  filename=filename,
66
+ headers={"x-pdf-name": filename},
67
  )
68
+
69
+
70
+ @app.get("/api/config/{pdf_id}/{template_id}")
71
+ async def get_config(pdf_id: str, template_id: str) -> Dict[str, Any]:
72
+ cfg_path = CFG_DIR / f"{pdf_id}__{template_id}.json"
73
+ if not cfg_path.exists():
74
+ raise HTTPException(status_code=404, detail="config not found")
75
+ try:
76
+ return json.loads(cfg_path.read_text(encoding="utf-8"))
77
+ except Exception as e:
78
+ raise HTTPException(status_code=500, detail=f"bad config json: {e}")
79
+
80
+
81
+ @app.post("/api/send-config")
82
+ async def send_config(payload: Dict[str, Any]) -> Dict[str, Any]:
83
+ pdf_id = (payload.get("pdf_id") or "").strip()
84
+ template_id = (payload.get("template_id") or "").strip()
85
+ config = payload.get("config")
86
+
87
+ if not pdf_id:
88
+ raise HTTPException(status_code=400, detail="Missing pdf_id")
89
+ if not template_id:
90
+ raise HTTPException(status_code=400, detail="Missing template_id")
91
+ if config is None:
92
+ raise HTTPException(status_code=400, detail="Missing config")
93
+
94
+ out = {"pdf_id": pdf_id, "template_id": template_id, "config": config}
95
+ cfg_path = CFG_DIR / f"{pdf_id}__{template_id}.json"
96
+
97
+ try:
98
+ cfg_path.write_text(json.dumps(out, indent=2, sort_keys=True), encoding="utf-8")
99
+ except Exception as e:
100
+ raise HTTPException(status_code=500, detail=f"failed to store config: {e}")
101
+
102
+ pdf_exists = (PDF_DIR / f"{pdf_id}.pdf").exists()
103
+ return {"ok": True, "stored": str(cfg_path), "pdf_exists": pdf_exists, "sftp": "not_implemented_here"}