-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlambda_function.py
More file actions
179 lines (146 loc) · 6.33 KB
/
Copy pathlambda_function.py
File metadata and controls
179 lines (146 loc) · 6.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import os
import urllib.request
from io import BytesIO
from typing import Optional, List
from fastapi import FastAPI, HTTPException, Body
from mangum import Mangum
from pydantic import BaseModel
import pathlib
import json
def debug_file_status():
print("--- PRE-FLIGHT FILE CHECK ---")
files_to_check = ["token.json", ".env"]
for filename in files_to_check:
path = pathlib.Path(filename)
if path.exists():
size = path.stat().st_size
print(f"FILE FOUND: {filename} ({size} bytes)")
if size > 0:
try:
with open(filename, 'r') as f:
content = f.read()
# Verify if it's valid JSON (for token.json)
if filename == "token.json":
json.loads(content)
print(f"VALIDATION: {filename} is VALID JSON.")
# Check first few chars of .env without leaking secrets
if filename == ".env":
print(f"VALIDATION: .env starts with: {content[:10]}...")
except Exception as e:
print(f"VALIDATION FAILED for {filename}: {str(e)}")
else:
print(f"WARNING: {filename} IS EMPTY (0 bytes)!")
else:
print(f"ERROR: {filename} NOT FOUND in {os.getcwd()}")
print("--- END CHECK ---")
debug_file_status()
app = FastAPI(title="SuperDoc API")
PINECONE_INDEX = os.getenv("PINECONE_INDEX", "superdoc-headings")
STAGE_PATH = os.getenv("STAGE_PATH", "/prod")
# --- Request Models ---
class MergePDFRequest(BaseModel):
pdfUrl: str
courseId: str
documentId: Optional[str] = None
index_name: str = PINECONE_INDEX
class HeadingOperation(BaseModel):
courseId: str
documentId: str
heading: str # Used for create/delete
index_name: str = PINECONE_INDEX
class UpdateHeadingRequest(BaseModel):
courseId: str
documentId: str
oldHeading: str
newHeading: str
index_name: str = PINECONE_INDEX
class CreateDocRequest(BaseModel):
courseId: str
documentName: str
# --- Middleware ---
@app.middleware("http")
async def log_requests(request, call_next):
print(f"Incoming request: {request.method} {request.url.path}")
response = await call_next(request)
return response
# --- Endpoints ---
@app.get("/health")
def health_check():
return {"status": "charlie charlie kirky"}
@app.post("/merge_pdf")
def handle_merge_pdf(req: MergePDFRequest):
from superdoc.superdoc import superdoc
try:
with urllib.request.urlopen(req.pdfUrl) as response:
if response.status != 200:
raise HTTPException(status_code=400, detail="Failed to download PDF")
pdf_stream = BytesIO(response.read())
# Initializes superdoc (creates one if documentId is None)
sd = superdoc(DOCUMENT_ID=req.documentId, COURSE_ID=req.courseId, index_name=req.index_name)
sd.merge_pdf_hierarchical(stream=pdf_stream)
return {"status": "success", "documentId": sd.DOCUMENT_ID}
except Exception as e:
print(traceback.format_exc())
raise HTTPException(status_code=500, detail=f"{type(e).__name__}: {str(e)}")
@app.post("/headings/create")
def create_heading(req: HeadingOperation):
from superdoc.superdoc import superdoc
try:
sd = superdoc(DOCUMENT_ID=req.documentId, COURSE_ID=req.courseId, index_name=req.index_name)
sd.create_heading(new_heading=req.heading)
return {"status": "heading created", "documentId": req.documentId}
except Exception as e:
print(traceback.format_exc())
raise HTTPException(status_code=500, detail=f"{type(e).__name__}: {str(e)}")
@app.delete("/headings/delete")
def delete_heading(req: HeadingOperation):
from superdoc.superdoc import superdoc
try:
sd = superdoc(DOCUMENT_ID=req.documentId, COURSE_ID=req.courseId, index_name=req.index_name)
sd.delete_heading(old_heading=req.heading)
return {"status": "heading deleted", "documentId": req.documentId}
except Exception as e:
print(traceback.format_exc())
raise HTTPException(status_code=500, detail=f"{type(e).__name__}: {str(e)}")
@app.put("/headings/update")
def update_heading(req: UpdateHeadingRequest):
from superdoc.superdoc import superdoc
try:
sd = superdoc(DOCUMENT_ID=req.documentId, COURSE_ID=req.courseId, index_name=req.index_name)
sd.update_heading(old_heading=req.oldHeading, new_heading=req.newHeading)
return {"status": "heading updated", "documentId": req.documentId}
except Exception as e:
print(traceback.format_exc())
raise HTTPException(status_code=500, detail=f"{type(e).__name__}: {str(e)}")
@app.get("/documents/{course_id}")
def get_course_documents(course_id: str):
from superdoc.superdoc import superdoc
try:
# We initialize with None to use the class helper methods
sd = superdoc(DOCUMENT_ID="DUMMY", COURSE_ID=course_id)
ids = sd.get_docids(course_id=course_id)
return {"courseId": course_id, "documentIds": ids}
except Exception as e:
print(traceback.format_exc())
raise HTTPException(status_code=500, detail=f"{type(e).__name__}: {str(e)}")
@app.post("/documents/create")
def create_new_document(req: CreateDocRequest):
from superdoc.superdoc import superdoc
try:
# Note: Using the standalone create_document method in the class
sd = superdoc(DOCUMENT_ID="DUMMY", COURSE_ID=req.courseId)
print("superdoc class initalized")
doc_map = sd.get_docids(course_id=req.courseId)
print("doc map retrieved")
if doc_map.get(req.documentName,None):
raise HTTPException(status_code=400, detail=f"A superdoc with the name {req.documentName} already exists!")
print("same name check completed")
response = sd.create_document(name=req.documentName, course_id=req.courseId)
docId = response.get('documentId')
print("response retrieved")
return {"status": "created", "document": docId}
except Exception as e:
print(traceback.format_exc())
raise HTTPException(status_code=500, detail=f"{type(e).__name__}: {str(e)}")
# Lambda Handler
handler = Mangum(app, lifespan="off", api_gateway_base_path=STAGE_PATH)