Spaces:
Running
Running
Commit ·
862e1ff
1
Parent(s): 2720004
[Cursor] Simplify serverless handler
Browse files
index.py
CHANGED
|
@@ -1,4 +1,3 @@
|
|
| 1 |
-
from flask import Flask, request, jsonify
|
| 2 |
import json
|
| 3 |
import os
|
| 4 |
import tempfile
|
|
@@ -6,16 +5,11 @@ import magic
|
|
| 6 |
import requests
|
| 7 |
from werkzeug.utils import secure_filename
|
| 8 |
import datetime
|
| 9 |
-
import base64
|
| 10 |
|
| 11 |
-
|
| 12 |
-
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 # 10MB max file size
|
| 13 |
-
|
| 14 |
-
def is_valid_file(file_obj):
|
| 15 |
"""Check if file type is allowed using python-magic"""
|
| 16 |
try:
|
| 17 |
-
mime = magic.from_buffer(
|
| 18 |
-
file_obj.seek(0) # Reset file pointer
|
| 19 |
allowed_mimes = [
|
| 20 |
'application/pdf',
|
| 21 |
'text/plain',
|
|
@@ -65,60 +59,82 @@ def download_file(url):
|
|
| 65 |
except Exception as e:
|
| 66 |
raise ValueError(f"Failed to download file: {str(e)}")
|
| 67 |
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
"
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
"
|
| 80 |
-
|
| 81 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
-
|
| 84 |
-
def parse_file():
|
| 85 |
try:
|
| 86 |
-
if '
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
"
|
| 90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
}), 400
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
"
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
# Save to temp file
|
| 106 |
-
|
| 107 |
-
fd, temp_path = tempfile.mkstemp(suffix=os.path.splitext(filename)[1])
|
| 108 |
os.close(fd)
|
| 109 |
-
file.save(temp_path)
|
| 110 |
|
| 111 |
try:
|
|
|
|
|
|
|
|
|
|
| 112 |
# Process file here
|
| 113 |
-
return
|
| 114 |
-
"
|
| 115 |
-
"
|
| 116 |
-
"
|
| 117 |
-
"
|
| 118 |
-
"
|
| 119 |
-
"
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
| 122 |
finally:
|
| 123 |
# Clean up temp file
|
| 124 |
try:
|
|
@@ -127,41 +143,80 @@ def parse_file():
|
|
| 127 |
pass
|
| 128 |
|
| 129 |
except Exception as e:
|
| 130 |
-
return
|
| 131 |
-
"
|
| 132 |
-
"
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
-
|
| 136 |
-
def parse_url():
|
| 137 |
try:
|
| 138 |
-
|
| 139 |
-
if
|
| 140 |
-
return
|
| 141 |
-
"
|
| 142 |
-
"
|
| 143 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
url = data['url']
|
| 146 |
if not url.startswith(('http://', 'https://')):
|
| 147 |
-
return
|
| 148 |
-
"
|
| 149 |
-
"
|
| 150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
# Download and process file
|
| 153 |
temp_path, content_type = download_file(url)
|
| 154 |
try:
|
| 155 |
# Process file here
|
| 156 |
-
return
|
| 157 |
-
"
|
| 158 |
-
"
|
| 159 |
-
"
|
| 160 |
-
"
|
| 161 |
-
"
|
| 162 |
-
"
|
| 163 |
-
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
finally:
|
| 166 |
# Clean up temp file
|
| 167 |
try:
|
|
@@ -170,74 +225,66 @@ def parse_url():
|
|
| 170 |
pass
|
| 171 |
|
| 172 |
except ValueError as e:
|
| 173 |
-
return
|
| 174 |
-
"
|
| 175 |
-
"
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
except Exception as e:
|
| 178 |
-
return
|
| 179 |
-
"
|
| 180 |
-
"
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
def handler(event, context):
|
| 184 |
"""Serverless handler for Vercel"""
|
| 185 |
|
| 186 |
-
#
|
| 187 |
-
|
| 188 |
-
|
|
|
|
|
|
|
|
|
|
| 189 |
|
| 190 |
# Handle OPTIONS request for CORS
|
| 191 |
-
if
|
| 192 |
return {
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
| 197 |
-
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
|
| 198 |
-
},
|
| 199 |
-
'body': ''
|
| 200 |
}
|
| 201 |
|
| 202 |
-
#
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
headers
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
}
|
| 225 |
-
)
|
| 226 |
-
|
| 227 |
-
# Prepare response
|
| 228 |
-
response_headers = dict(response.headers)
|
| 229 |
-
response_headers.update({
|
| 230 |
-
'Access-Control-Allow-Origin': '*',
|
| 231 |
-
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
| 232 |
-
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
|
| 233 |
-
})
|
| 234 |
-
|
| 235 |
-
return {
|
| 236 |
-
'statusCode': response.status_code,
|
| 237 |
-
'headers': response_headers,
|
| 238 |
-
'body': response.get_data(as_text=True)
|
| 239 |
}
|
| 240 |
-
|
| 241 |
-
#
|
| 242 |
-
|
| 243 |
-
|
|
|
|
|
|
|
| 1 |
import json
|
| 2 |
import os
|
| 3 |
import tempfile
|
|
|
|
| 5 |
import requests
|
| 6 |
from werkzeug.utils import secure_filename
|
| 7 |
import datetime
|
|
|
|
| 8 |
|
| 9 |
+
def is_valid_file(file_data):
|
|
|
|
|
|
|
|
|
|
| 10 |
"""Check if file type is allowed using python-magic"""
|
| 11 |
try:
|
| 12 |
+
mime = magic.from_buffer(file_data, mime=True)
|
|
|
|
| 13 |
allowed_mimes = [
|
| 14 |
'application/pdf',
|
| 15 |
'text/plain',
|
|
|
|
| 59 |
except Exception as e:
|
| 60 |
raise ValueError(f"Failed to download file: {str(e)}")
|
| 61 |
|
| 62 |
+
def handle_root():
|
| 63 |
+
return {
|
| 64 |
+
"statusCode": 200,
|
| 65 |
+
"headers": {
|
| 66 |
+
"Content-Type": "application/json"
|
| 67 |
+
},
|
| 68 |
+
"body": json.dumps({
|
| 69 |
+
"status": "ok",
|
| 70 |
+
"message": "Document Processing API",
|
| 71 |
+
"version": "1.0.0"
|
| 72 |
+
})
|
| 73 |
+
}
|
| 74 |
|
| 75 |
+
def handle_health():
|
| 76 |
+
return {
|
| 77 |
+
"statusCode": 200,
|
| 78 |
+
"headers": {
|
| 79 |
+
"Content-Type": "application/json"
|
| 80 |
+
},
|
| 81 |
+
"body": json.dumps({
|
| 82 |
+
"status": "healthy",
|
| 83 |
+
"timestamp": str(datetime.datetime.now(datetime.UTC))
|
| 84 |
+
})
|
| 85 |
+
}
|
| 86 |
|
| 87 |
+
def handle_parse_file(event):
|
|
|
|
| 88 |
try:
|
| 89 |
+
# Check if there's a file in the request
|
| 90 |
+
if 'body' not in event or not event['body']:
|
| 91 |
+
return {
|
| 92 |
+
"statusCode": 400,
|
| 93 |
+
"headers": {"Content-Type": "application/json"},
|
| 94 |
+
"body": json.dumps({
|
| 95 |
+
"error": "No file provided",
|
| 96 |
+
"details": "Please provide a file in the request body"
|
| 97 |
+
})
|
| 98 |
+
}
|
| 99 |
|
| 100 |
+
# Get file data
|
| 101 |
+
file_data = event['body']
|
| 102 |
+
if event.get('isBase64Encoded', False):
|
| 103 |
+
import base64
|
| 104 |
+
file_data = base64.b64decode(file_data)
|
|
|
|
| 105 |
|
| 106 |
+
# Validate file type
|
| 107 |
+
if not is_valid_file(file_data):
|
| 108 |
+
return {
|
| 109 |
+
"statusCode": 400,
|
| 110 |
+
"headers": {"Content-Type": "application/json"},
|
| 111 |
+
"body": json.dumps({
|
| 112 |
+
"error": "Invalid file type",
|
| 113 |
+
"details": "Supported formats: PDF, TXT, HTML, MD, DOCX"
|
| 114 |
+
})
|
| 115 |
+
}
|
| 116 |
|
| 117 |
# Save to temp file
|
| 118 |
+
fd, temp_path = tempfile.mkstemp()
|
|
|
|
| 119 |
os.close(fd)
|
|
|
|
| 120 |
|
| 121 |
try:
|
| 122 |
+
with open(temp_path, 'wb') as f:
|
| 123 |
+
f.write(file_data)
|
| 124 |
+
|
| 125 |
# Process file here
|
| 126 |
+
return {
|
| 127 |
+
"statusCode": 200,
|
| 128 |
+
"headers": {"Content-Type": "application/json"},
|
| 129 |
+
"body": json.dumps({
|
| 130 |
+
"status": "success",
|
| 131 |
+
"message": "File processed successfully",
|
| 132 |
+
"metadata": {
|
| 133 |
+
"size": os.path.getsize(temp_path),
|
| 134 |
+
"mime_type": magic.from_file(temp_path, mime=True)
|
| 135 |
+
}
|
| 136 |
+
})
|
| 137 |
+
}
|
| 138 |
finally:
|
| 139 |
# Clean up temp file
|
| 140 |
try:
|
|
|
|
| 143 |
pass
|
| 144 |
|
| 145 |
except Exception as e:
|
| 146 |
+
return {
|
| 147 |
+
"statusCode": 500,
|
| 148 |
+
"headers": {"Content-Type": "application/json"},
|
| 149 |
+
"body": json.dumps({
|
| 150 |
+
"error": "Processing failed",
|
| 151 |
+
"details": str(e)
|
| 152 |
+
})
|
| 153 |
+
}
|
| 154 |
|
| 155 |
+
def handle_parse_url(event):
|
|
|
|
| 156 |
try:
|
| 157 |
+
# Get request body
|
| 158 |
+
if 'body' not in event or not event['body']:
|
| 159 |
+
return {
|
| 160 |
+
"statusCode": 400,
|
| 161 |
+
"headers": {"Content-Type": "application/json"},
|
| 162 |
+
"body": json.dumps({
|
| 163 |
+
"error": "No request body",
|
| 164 |
+
"details": "Please provide a URL in the request body"
|
| 165 |
+
})
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
# Parse JSON body
|
| 169 |
+
try:
|
| 170 |
+
body = json.loads(event['body'])
|
| 171 |
+
except:
|
| 172 |
+
return {
|
| 173 |
+
"statusCode": 400,
|
| 174 |
+
"headers": {"Content-Type": "application/json"},
|
| 175 |
+
"body": json.dumps({
|
| 176 |
+
"error": "Invalid JSON",
|
| 177 |
+
"details": "Request body must be valid JSON"
|
| 178 |
+
})
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
# Get URL from body
|
| 182 |
+
url = body.get('url')
|
| 183 |
+
if not url:
|
| 184 |
+
return {
|
| 185 |
+
"statusCode": 400,
|
| 186 |
+
"headers": {"Content-Type": "application/json"},
|
| 187 |
+
"body": json.dumps({
|
| 188 |
+
"error": "No URL provided",
|
| 189 |
+
"details": "Please provide a URL in the request body"
|
| 190 |
+
})
|
| 191 |
+
}
|
| 192 |
|
|
|
|
| 193 |
if not url.startswith(('http://', 'https://')):
|
| 194 |
+
return {
|
| 195 |
+
"statusCode": 400,
|
| 196 |
+
"headers": {"Content-Type": "application/json"},
|
| 197 |
+
"body": json.dumps({
|
| 198 |
+
"error": "Invalid URL",
|
| 199 |
+
"details": "URL must start with http:// or https://"
|
| 200 |
+
})
|
| 201 |
+
}
|
| 202 |
|
| 203 |
# Download and process file
|
| 204 |
temp_path, content_type = download_file(url)
|
| 205 |
try:
|
| 206 |
# Process file here
|
| 207 |
+
return {
|
| 208 |
+
"statusCode": 200,
|
| 209 |
+
"headers": {"Content-Type": "application/json"},
|
| 210 |
+
"body": json.dumps({
|
| 211 |
+
"status": "success",
|
| 212 |
+
"message": "URL processed successfully",
|
| 213 |
+
"metadata": {
|
| 214 |
+
"url": url,
|
| 215 |
+
"content_type": content_type,
|
| 216 |
+
"size": os.path.getsize(temp_path)
|
| 217 |
+
}
|
| 218 |
+
})
|
| 219 |
+
}
|
| 220 |
finally:
|
| 221 |
# Clean up temp file
|
| 222 |
try:
|
|
|
|
| 225 |
pass
|
| 226 |
|
| 227 |
except ValueError as e:
|
| 228 |
+
return {
|
| 229 |
+
"statusCode": 400,
|
| 230 |
+
"headers": {"Content-Type": "application/json"},
|
| 231 |
+
"body": json.dumps({
|
| 232 |
+
"error": "Invalid request",
|
| 233 |
+
"details": str(e)
|
| 234 |
+
})
|
| 235 |
+
}
|
| 236 |
except Exception as e:
|
| 237 |
+
return {
|
| 238 |
+
"statusCode": 500,
|
| 239 |
+
"headers": {"Content-Type": "application/json"},
|
| 240 |
+
"body": json.dumps({
|
| 241 |
+
"error": "Processing failed",
|
| 242 |
+
"details": str(e)
|
| 243 |
+
})
|
| 244 |
+
}
|
| 245 |
|
| 246 |
def handler(event, context):
|
| 247 |
"""Serverless handler for Vercel"""
|
| 248 |
|
| 249 |
+
# Add CORS headers to all responses
|
| 250 |
+
cors_headers = {
|
| 251 |
+
"Access-Control-Allow-Origin": "*",
|
| 252 |
+
"Access-Control-Allow-Headers": "Content-Type, Authorization",
|
| 253 |
+
"Access-Control-Allow-Methods": "GET, POST, OPTIONS"
|
| 254 |
+
}
|
| 255 |
|
| 256 |
# Handle OPTIONS request for CORS
|
| 257 |
+
if event.get('httpMethod') == 'OPTIONS':
|
| 258 |
return {
|
| 259 |
+
"statusCode": 204,
|
| 260 |
+
"headers": cors_headers,
|
| 261 |
+
"body": ""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
}
|
| 263 |
|
| 264 |
+
# Get path and method
|
| 265 |
+
path = event.get('path', '/').rstrip('/')
|
| 266 |
+
method = event.get('httpMethod', 'GET')
|
| 267 |
+
|
| 268 |
+
# Route request
|
| 269 |
+
response = None
|
| 270 |
+
if path == '' or path == '/':
|
| 271 |
+
response = handle_root()
|
| 272 |
+
elif path == '/health':
|
| 273 |
+
response = handle_health()
|
| 274 |
+
elif path == '/parse/file' and method == 'POST':
|
| 275 |
+
response = handle_parse_file(event)
|
| 276 |
+
elif path == '/parse/url' and method == 'POST':
|
| 277 |
+
response = handle_parse_url(event)
|
| 278 |
+
else:
|
| 279 |
+
response = {
|
| 280 |
+
"statusCode": 404,
|
| 281 |
+
"headers": {"Content-Type": "application/json"},
|
| 282 |
+
"body": json.dumps({
|
| 283 |
+
"error": "Not Found",
|
| 284 |
+
"details": f"Path {path} not found"
|
| 285 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
}
|
| 287 |
+
|
| 288 |
+
# Add CORS headers to response
|
| 289 |
+
response['headers'].update(cors_headers)
|
| 290 |
+
return response
|