TiH0 commited on
Commit
4a91e42
·
verified ·
1 Parent(s): efcde4c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -10
app.py CHANGED
@@ -2,16 +2,15 @@ from fastapi import FastAPI, File, UploadFile, Form, HTTPException
2
  from fastapi.responses import FileResponse, HTMLResponse
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from fastapi import BackgroundTasks
5
- from fastapi.responses import FileResponse
6
  import os
7
  import tempfile
8
  import re
9
  from pathlib import Path
10
 
11
- # Import your conversion function
12
  from meta import process_excel_to_word
13
 
14
- app = FastAPI(title="QCM Converter API")
15
 
16
  # Enable CORS for all origins (you can restrict this in production)
17
  app.add_middleware(
@@ -36,7 +35,8 @@ async def root():
36
  return """
37
  <html>
38
  <body>
39
- <h1>QCM Converter API</h1>
 
40
  <p>Upload your Excel files at <a href="/docs">/docs</a></p>
41
  </body>
42
  </html>
@@ -46,15 +46,21 @@ async def root():
46
  async def convert_file(
47
  background_tasks: BackgroundTasks,
48
  file: UploadFile = File(...),
 
49
  use_two_columns: bool = Form(True),
50
  add_separator_line: bool = Form(True),
51
  theme_color: str = Form("5FFFDF")
52
  ):
53
  """
54
- Convert Excel QCM file to Word document
 
 
 
 
55
 
56
  Parameters:
57
  - file: Excel file (.xlsx)
 
58
  - use_two_columns: Use two-column layout
59
  - add_separator_line: Add separator line between columns
60
  - theme_color: Hex color code (without #) e.g., "5FFFDF"
@@ -75,9 +81,21 @@ async def convert_file(
75
  temp_dir = tempfile.mkdtemp()
76
  temp_input_path = os.path.join(temp_dir, f"{original_name}.xlsx")
77
 
 
78
  with open(temp_input_path, "wb") as f:
79
  f.write(await file.read())
80
 
 
 
 
 
 
 
 
 
 
 
 
81
  output_filename = file.filename.replace('.xlsx', '_converted.docx')
82
  temp_output_path = tempfile.mktemp(suffix='.docx')
83
 
@@ -85,6 +103,7 @@ async def convert_file(
85
  process_excel_to_word(
86
  excel_file_path=temp_input_path,
87
  output_word_path=temp_output_path,
 
88
  display_name=None,
89
  use_two_columns=use_two_columns,
90
  add_separator_line=add_separator_line,
@@ -92,18 +111,25 @@ async def convert_file(
92
  theme_hex=theme_color
93
  )
94
 
95
- # Schedule cleanup as a background task
96
- background_tasks.add_task(cleanup_files, temp_input_path, temp_output_path)
 
 
 
 
97
 
98
  return FileResponse(
99
  temp_output_path,
100
  media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
101
  filename=output_filename,
102
- background=None # <-- No lambda here
103
  )
104
 
105
  except Exception as e:
106
- cleanup_files(temp_input_path, temp_output_path)
 
 
 
107
  raise HTTPException(status_code=500, detail=f"Conversion failed: {str(e)}")
108
 
109
  def cleanup_files(*file_paths):
@@ -118,7 +144,7 @@ def cleanup_files(*file_paths):
118
  @app.get("/health")
119
  async def health_check():
120
  """Health check endpoint"""
121
- return {"status": "healthy", "message": "QCM Converter API is running"}
122
 
123
  if __name__ == "__main__":
124
  import uvicorn
 
2
  from fastapi.responses import FileResponse, HTMLResponse
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from fastapi import BackgroundTasks
 
5
  import os
6
  import tempfile
7
  import re
8
  from pathlib import Path
9
 
10
+ # Import your conversion function from meta.py
11
  from meta import process_excel_to_word
12
 
13
+ app = FastAPI(title="QCM Converter API - META")
14
 
15
  # Enable CORS for all origins (you can restrict this in production)
16
  app.add_middleware(
 
35
  return """
36
  <html>
37
  <body>
38
+ <h1>QCM Converter API - META</h1>
39
+ <p>META Version: Answer tables only at the end of each module</p>
40
  <p>Upload your Excel files at <a href="/docs">/docs</a></p>
41
  </body>
42
  </html>
 
46
  async def convert_file(
47
  background_tasks: BackgroundTasks,
48
  file: UploadFile = File(...),
49
+ images: UploadFile = File(None), # Optional ZIP file with images
50
  use_two_columns: bool = Form(True),
51
  add_separator_line: bool = Form(True),
52
  theme_color: str = Form("5FFFDF")
53
  ):
54
  """
55
+ Convert Excel QCM file to Word document (META version)
56
+
57
+ META Version Features:
58
+ - NO empty tables after each course
59
+ - ONLY answer tables at the end of each module
60
 
61
  Parameters:
62
  - file: Excel file (.xlsx)
63
+ - images: Optional ZIP file containing images
64
  - use_two_columns: Use two-column layout
65
  - add_separator_line: Add separator line between columns
66
  - theme_color: Hex color code (without #) e.g., "5FFFDF"
 
81
  temp_dir = tempfile.mkdtemp()
82
  temp_input_path = os.path.join(temp_dir, f"{original_name}.xlsx")
83
 
84
+ # Save the Excel file
85
  with open(temp_input_path, "wb") as f:
86
  f.write(await file.read())
87
 
88
+ # Handle optional image ZIP file
89
+ temp_images_path = None
90
+ if images and images.filename:
91
+ if not images.filename.endswith('.zip'):
92
+ cleanup_files(temp_input_path)
93
+ raise HTTPException(status_code=400, detail="Images must be in a ZIP file")
94
+
95
+ temp_images_path = os.path.join(temp_dir, "images.zip")
96
+ with open(temp_images_path, "wb") as f:
97
+ f.write(await images.read())
98
+
99
  output_filename = file.filename.replace('.xlsx', '_converted.docx')
100
  temp_output_path = tempfile.mktemp(suffix='.docx')
101
 
 
103
  process_excel_to_word(
104
  excel_file_path=temp_input_path,
105
  output_word_path=temp_output_path,
106
+ image_folder=temp_images_path, # Can be None
107
  display_name=None,
108
  use_two_columns=use_two_columns,
109
  add_separator_line=add_separator_line,
 
111
  theme_hex=theme_color
112
  )
113
 
114
+ # Schedule cleanup as a background task
115
+ files_to_cleanup = [temp_input_path, temp_output_path]
116
+ if temp_images_path:
117
+ files_to_cleanup.append(temp_images_path)
118
+
119
+ background_tasks.add_task(cleanup_files, *files_to_cleanup)
120
 
121
  return FileResponse(
122
  temp_output_path,
123
  media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
124
  filename=output_filename,
125
+ background=None
126
  )
127
 
128
  except Exception as e:
129
+ files_to_cleanup = [temp_input_path, temp_output_path]
130
+ if temp_images_path:
131
+ files_to_cleanup.append(temp_images_path)
132
+ cleanup_files(*files_to_cleanup)
133
  raise HTTPException(status_code=500, detail=f"Conversion failed: {str(e)}")
134
 
135
  def cleanup_files(*file_paths):
 
144
  @app.get("/health")
145
  async def health_check():
146
  """Health check endpoint"""
147
+ return {"status": "healthy", "message": "QCM Converter API - META is running"}
148
 
149
  if __name__ == "__main__":
150
  import uvicorn