-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathapp.py
More file actions
168 lines (146 loc) · 5.8 KB
/
app.py
File metadata and controls
168 lines (146 loc) · 5.8 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
import json
import os
import subprocess
import base64
import logging
import tempfile
from typing import Dict, Any
# Configure logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def handler(event: Dict[Any, Any], context: Any) -> Dict[str, Any]:
"""
AWS Lambda function handler to convert documents using Pandoc.
Expected event structure:
{
"input_format": "markdown",
"output_format": "html",
"content": "<base64-encoded-content>",
"options": ["--standalone", "--toc"] # Optional pandoc arguments
}
Returns:
{
"statusCode": 200,
"body": "<base64-encoded-converted-content>",
"headers": {"Content-Type": "text/html"}
}
"""
try:
logger.info("Received event: %s", json.dumps(event))
# Extract parameters
input_format = event.get('input_format', 'markdown')
output_format = event.get('output_format', 'html')
content_base64 = event.get('content', '')
options = event.get('options', [])
if not content_base64:
return {
'statusCode': 400,
'body': json.dumps({'error': 'No content provided'})
}
# Decode content - handle binary formats differently
content_bytes = base64.b64decode(content_base64)
# Define list of binary formats
binary_formats = ['docx', 'doc', 'pdf', 'odt', 'epub', 'xlsx', 'pptx']
# Define list of text formats
text_formats = ['html', 'markdown', 'md', 'txt', 'tex', 'rst', 'json', 'xml']
# Create temporary files for input and output
with tempfile.NamedTemporaryFile(suffix=f'.{input_format}', delete=False) as input_file:
# Write binary data directly for binary formats, no UTF-8 encoding/decoding
if input_format in binary_formats:
input_file.write(content_bytes)
else:
# For text formats, decode to string first
content = content_bytes.decode('utf-8')
input_file.write(content.encode('utf-8'))
input_file_path = input_file.name
output_file_path = f"{input_file_path}.{output_format}"
# Build pandoc command
cmd = ['pandoc', input_file_path, '-o', output_file_path]
# Add format flags if specified
if input_format:
cmd.extend(['-f', input_format])
if output_format:
cmd.extend(['-t', output_format])
# Add any additional options
cmd.extend(options)
logger.info(f"Running command: {' '.join(cmd)}")
# Run pandoc
result = subprocess.run(cmd, capture_output=True, text=True)
# Check if pandoc ran successfully
if result.returncode != 0:
logger.error(f"Pandoc error: {result.stderr}")
return {
'statusCode': 500,
'body': json.dumps({
'error': 'Conversion failed',
'details': result.stderr
})
}
# Read output file
with open(output_file_path, 'rb') as f:
output_content = f.read()
# Clean up temporary files
os.unlink(input_file_path)
os.unlink(output_file_path)
# Determine content type based on output format
content_type_map = {
'html': 'text/html',
'pdf': 'application/pdf',
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'odt': 'application/vnd.oasis.opendocument.text',
'epub': 'application/epub+zip',
}
content_type = content_type_map.get(output_format, 'text/plain')
# Return the converted content based on format type
if output_format in text_formats:
# For text formats, decode to UTF-8 and include directly in JSON
try:
text_content = output_content.decode('utf-8')
return {
'statusCode': 200,
'body': json.dumps({
'content': text_content,
'format': output_format,
'contentType': content_type
}),
'headers': {
'Content-Type': 'application/json'
}
}
except UnicodeDecodeError:
# If we can't decode as UTF-8, fall back to base64
return {
'statusCode': 200,
'body': json.dumps({
'content': base64.b64encode(output_content).decode('utf-8'),
'format': output_format,
'contentType': content_type,
'encoding': 'base64'
}),
'headers': {
'Content-Type': 'application/json'
}
}
else:
# For binary formats, still need to use base64 encoding
return {
'statusCode': 200,
'body': json.dumps({
'content': base64.b64encode(output_content).decode('utf-8'),
'format': output_format,
'contentType': content_type,
'encoding': 'base64'
}),
'headers': {
'Content-Type': 'application/json'
}
}
except Exception as e:
logger.error(f"Error: {str(e)}")
return {
'statusCode': 500,
'body': json.dumps({
'error': 'Internal server error',
'details': str(e)
})
}