um41r commited on
Commit
24e4251
·
verified ·
1 Parent(s): 223ca22

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +65 -9
main.py CHANGED
@@ -1,19 +1,48 @@
1
- from fastapi import FastAPI
2
  from fastapi.middleware.cors import CORSMiddleware
 
3
  import os
4
 
5
  from routers import pdf_converter, pdf_compressor, pdf_to_images
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  app = FastAPI(
8
  title="Document Converter API",
9
- description="Convert and manipulate PDF files",
10
  version="1.0.0"
11
  )
12
 
13
  # CORS configuration
14
  app.add_middleware(
15
  CORSMiddleware,
16
- allow_origins=["*"], # In production, replace with your Next.js domain
17
  allow_credentials=True,
18
  allow_methods=["*"],
19
  allow_headers=["*"],
@@ -23,16 +52,37 @@ app.add_middleware(
23
  TEMP_DIR = "/tmp/conversions"
24
  os.makedirs(TEMP_DIR, exist_ok=True)
25
 
26
- # Include routers
27
- app.include_router(pdf_converter.router, prefix="/pdf", tags=["PDF Converter"])
28
- app.include_router(pdf_compressor.router, prefix="/pdf", tags=["PDF Compressor"])
29
- app.include_router(pdf_to_images.router, prefix="/pdf", tags=["PDF to Images"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
 
 
 
31
  @app.get("/")
32
  def read_root():
 
33
  return {
34
  "message": "Document Converter API",
35
  "version": "1.0.0",
 
 
36
  "endpoints": {
37
  "PDF Conversion": {
38
  "/pdf/to-word": "Convert PDF to Word (DOCX)",
@@ -50,14 +100,20 @@ def read_root():
50
  "Utilities": {
51
  "/health": "Health check"
52
  }
 
 
 
 
53
  }
54
  }
55
 
56
  @app.get("/health")
57
  def health_check():
58
- return {"status": "healthy", "service": "Document Converter API"}
 
59
 
60
  if __name__ == "__main__":
61
  import uvicorn
62
  port = int(os.environ.get("PORT", 7860))
63
- uvicorn.run(app, host="0.0.0.0", port=port)
 
 
1
+ from fastapi import FastAPI, Depends, HTTPException, status
2
  from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.security import APIKeyHeader
4
  import os
5
 
6
  from routers import pdf_converter, pdf_compressor, pdf_to_images
7
 
8
+ # =========================
9
+ # API KEY CONFIGURATION
10
+ # =========================
11
+ API_KEY = os.getenv("PD_TOOLS_API_KEY")
12
+
13
+ if not API_KEY:
14
+ raise RuntimeError("❌ PD_TOOLS_API_KEY not found in environment variables or HF Space Secrets")
15
+
16
+ # API Key Header
17
+ api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)
18
+
19
+ def verify_api_key(api_key: str = Depends(api_key_header)):
20
+ """Verify the API key from request headers"""
21
+ if not api_key:
22
+ raise HTTPException(
23
+ status_code=status.HTTP_401_UNAUTHORIZED,
24
+ detail="Missing API key. Please provide X-API-Key header."
25
+ )
26
+ if api_key != API_KEY:
27
+ raise HTTPException(
28
+ status_code=status.HTTP_401_UNAUTHORIZED,
29
+ detail="Invalid API key"
30
+ )
31
+ return api_key
32
+
33
+ # =========================
34
+ # FASTAPI APP
35
+ # =========================
36
  app = FastAPI(
37
  title="Document Converter API",
38
+ description="Convert and manipulate PDF files with API key authentication",
39
  version="1.0.0"
40
  )
41
 
42
  # CORS configuration
43
  app.add_middleware(
44
  CORSMiddleware,
45
+ allow_origins=["*"],
46
  allow_credentials=True,
47
  allow_methods=["*"],
48
  allow_headers=["*"],
 
52
  TEMP_DIR = "/tmp/conversions"
53
  os.makedirs(TEMP_DIR, exist_ok=True)
54
 
55
+ # Include routers with API key dependency
56
+ app.include_router(
57
+ pdf_converter.router,
58
+ prefix="/pdf",
59
+ tags=["PDF Converter"],
60
+ dependencies=[Depends(verify_api_key)] # Add API key protection
61
+ )
62
+ app.include_router(
63
+ pdf_compressor.router,
64
+ prefix="/pdf",
65
+ tags=["PDF Compressor"],
66
+ dependencies=[Depends(verify_api_key)] # Add API key protection
67
+ )
68
+ app.include_router(
69
+ pdf_to_images.router,
70
+ prefix="/pdf",
71
+ tags=["PDF to Images"],
72
+ dependencies=[Depends(verify_api_key)] # Add API key protection
73
+ )
74
 
75
+ # =========================
76
+ # PUBLIC ENDPOINTS
77
+ # =========================
78
  @app.get("/")
79
  def read_root():
80
+ """Public endpoint - no authentication required"""
81
  return {
82
  "message": "Document Converter API",
83
  "version": "1.0.0",
84
+ "secured": True,
85
+ "authentication": "Required for all /pdf/* endpoints",
86
  "endpoints": {
87
  "PDF Conversion": {
88
  "/pdf/to-word": "Convert PDF to Word (DOCX)",
 
100
  "Utilities": {
101
  "/health": "Health check"
102
  }
103
+ },
104
+ "usage": {
105
+ "header": "X-API-Key",
106
+ "example": "curl -H 'X-API-Key: your-api-key-here' https://your-space.hf.space/pdf/to-word"
107
  }
108
  }
109
 
110
  @app.get("/health")
111
  def health_check():
112
+ """Public health check endpoint - no authentication required"""
113
+ return {"status": "healthy", "service": "Document Converter API", "secured": True}
114
 
115
  if __name__ == "__main__":
116
  import uvicorn
117
  port = int(os.environ.get("PORT", 7860))
118
+ uvicorn.run(app, host="0.0.0.0", port=port)
119
+