Spaces:
Running
Running
Update main.py
Browse files
main.py
CHANGED
@@ -157,6 +157,39 @@ async def convert_html_to_docx(input_data: HTMLInput):
|
|
157 |
if temp_filename and os.path.exists(temp_filename):
|
158 |
os.remove(temp_filename)
|
159 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
160 |
if __name__ == "__main__":
|
161 |
import uvicorn
|
162 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
157 |
if temp_filename and os.path.exists(temp_filename):
|
158 |
os.remove(temp_filename)
|
159 |
|
160 |
+
@app.post("/html_to_docx")
|
161 |
+
async def convert_html_to_docx(input_data: HTMLRequest):
|
162 |
+
temp_filename = None
|
163 |
+
try:
|
164 |
+
# Create a new HtmlToDocx parser
|
165 |
+
parser = HtmlToDocx()
|
166 |
+
|
167 |
+
# Parse the HTML string to DOCX
|
168 |
+
docx = parser.parse_html_string(input_data.html_content)
|
169 |
+
|
170 |
+
# Create a unique filename in the temporary folder
|
171 |
+
temp_filename = os.path.join(TEMP_FOLDER, f"temp_{os.urandom(8).hex()}.docx")
|
172 |
+
|
173 |
+
# Save the DOCX to the temporary file
|
174 |
+
docx.save(temp_filename)
|
175 |
+
|
176 |
+
# Open the file and read its contents
|
177 |
+
with open(temp_filename, 'rb') as file:
|
178 |
+
file_contents = file.read()
|
179 |
+
|
180 |
+
# Return the DOCX file as a response
|
181 |
+
return Response(
|
182 |
+
content=file_contents,
|
183 |
+
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
184 |
+
headers={"Content-Disposition": "attachment; filename=converted.docx"}
|
185 |
+
)
|
186 |
+
except Exception as e:
|
187 |
+
raise HTTPException(status_code=500, detail=str(e))
|
188 |
+
finally:
|
189 |
+
# Clean up: remove the temporary file
|
190 |
+
if temp_filename and os.path.exists(temp_filename):
|
191 |
+
os.remove(temp_filename)
|
192 |
+
|
193 |
if __name__ == "__main__":
|
194 |
import uvicorn
|
195 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|