hellorahulk commited on
Commit
862e1ff
·
1 Parent(s): 2720004

[Cursor] Simplify serverless handler

Browse files
Files changed (1) hide show
  1. index.py +184 -137
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
- app = Flask(__name__)
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(file_obj.read(2048), mime=True)
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
- @app.route('/')
69
- def home():
70
- return jsonify({
71
- "status": "ok",
72
- "message": "Document Processing API",
73
- "version": "1.0.0"
74
- })
 
 
 
 
 
75
 
76
- @app.route('/health')
77
- def health():
78
- return jsonify({
79
- "status": "healthy",
80
- "timestamp": str(datetime.datetime.now(datetime.UTC))
81
- })
 
 
 
 
 
82
 
83
- @app.route('/parse/file', methods=['POST'])
84
- def parse_file():
85
  try:
86
- if 'file' not in request.files:
87
- return jsonify({
88
- "error": "No file provided",
89
- "details": "Please provide a file in the 'file' field"
90
- }), 400
 
 
 
 
 
91
 
92
- file = request.files['file']
93
- if not file.filename:
94
- return jsonify({
95
- "error": "No file selected",
96
- "details": "Please select a file to upload"
97
- }), 400
98
 
99
- if not is_valid_file(file):
100
- return jsonify({
101
- "error": "Invalid file type",
102
- "details": "Supported formats: PDF, TXT, HTML, MD, DOCX"
103
- }), 400
 
 
 
 
 
104
 
105
  # Save to temp file
106
- filename = secure_filename(file.filename)
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 jsonify({
114
- "status": "success",
115
- "message": "File processed successfully",
116
- "metadata": {
117
- "filename": filename,
118
- "size": os.path.getsize(temp_path),
119
- "mime_type": magic.from_file(temp_path, mime=True)
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 jsonify({
131
- "error": "Processing failed",
132
- "details": str(e)
133
- }), 500
 
 
 
 
134
 
135
- @app.route('/parse/url', methods=['POST'])
136
- def parse_url():
137
  try:
138
- data = request.get_json()
139
- if not data or 'url' not in data:
140
- return jsonify({
141
- "error": "No URL provided",
142
- "details": "Please provide a URL in the request body"
143
- }), 400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
- url = data['url']
146
  if not url.startswith(('http://', 'https://')):
147
- return jsonify({
148
- "error": "Invalid URL",
149
- "details": "URL must start with http:// or https://"
150
- }), 400
 
 
 
 
151
 
152
  # Download and process file
153
  temp_path, content_type = download_file(url)
154
  try:
155
  # Process file here
156
- return jsonify({
157
- "status": "success",
158
- "message": "URL processed successfully",
159
- "metadata": {
160
- "url": url,
161
- "content_type": content_type,
162
- "size": os.path.getsize(temp_path)
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 jsonify({
174
- "error": "Invalid request",
175
- "details": str(e)
176
- }), 400
 
 
 
 
177
  except Exception as e:
178
- return jsonify({
179
- "error": "Processing failed",
180
- "details": str(e)
181
- }), 500
 
 
 
 
182
 
183
  def handler(event, context):
184
  """Serverless handler for Vercel"""
185
 
186
- # Get HTTP method and path
187
- http_method = event.get('httpMethod', 'GET')
188
- path = event.get('path', '/')
 
 
 
189
 
190
  # Handle OPTIONS request for CORS
191
- if http_method == 'OPTIONS':
192
  return {
193
- 'statusCode': 204,
194
- 'headers': {
195
- 'Access-Control-Allow-Origin': '*',
196
- 'Access-Control-Allow-Headers': 'Content-Type, Authorization',
197
- 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
198
- },
199
- 'body': ''
200
  }
201
 
202
- # Create test client
203
- with app.test_client() as client:
204
- # Prepare headers
205
- headers = event.get('headers', {})
206
-
207
- # Handle body
208
- body = None
209
- if 'body' in event:
210
- if event.get('isBase64Encoded', False):
211
- body = base64.b64decode(event['body'])
212
- else:
213
- body = event['body'].encode('utf-8') if event['body'] else None
214
-
215
- # Make request to Flask app
216
- response = client.open(
217
- path,
218
- method=http_method,
219
- headers=headers,
220
- data=body,
221
- environ_base={
222
- 'CONTENT_LENGTH': str(len(body)) if body else '0',
223
- 'CONTENT_TYPE': headers.get('content-type', 'application/json')
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
- # For local development
242
- if __name__ == '__main__':
243
- app.run(debug=True)
 
 
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