z2learn commited on
Commit
7bb58ee
·
verified ·
1 Parent(s): 6be8085

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -31
app.py CHANGED
@@ -1,24 +1,23 @@
1
  import os
2
- import uuid
3
  import shutil
4
  import subprocess
5
- from fastapi import FastAPI, File, UploadFile, Form, HTTPException
 
6
  from fastapi.responses import FileResponse, RedirectResponse
7
  from fastapi.middleware.cors import CORSMiddleware
8
- import tempfile
9
 
10
  app = FastAPI()
11
 
12
- # Add CORS middleware to allow requests from your frontend
13
  app.add_middleware(
14
  CORSMiddleware,
15
- allow_origins=["*"], # In production, set this to your frontend URL
16
  allow_credentials=True,
17
  allow_methods=["*"],
18
  allow_headers=["*"],
19
  )
20
 
21
- # Create a directory to store temporary files
22
  TEMP_DIR = "temp_files"
23
  os.makedirs(TEMP_DIR, exist_ok=True)
24
 
@@ -28,38 +27,38 @@ def read_root():
28
 
29
  @app.post("/burn-subtitles")
30
  async def burn_subtitles(
 
31
  video: UploadFile = File(...),
32
  subtitle: UploadFile = File(...),
33
  font_size: str = Form("20"),
34
  font_color: str = Form("white"),
35
  output_format: str = Form("mp4")
36
  ):
37
- # Create unique ID for this job
38
- job_id = str(uuid.uuid4())
39
- job_dir = os.path.join(TEMP_DIR, job_id)
40
- os.makedirs(job_dir, exist_ok=True)
41
 
42
  try:
43
- # Save uploaded files
44
  video_path = os.path.join(job_dir, f"input{os.path.splitext(video.filename)[1]}")
45
  subtitle_path = os.path.join(job_dir, "subtitles.srt")
46
  output_path = os.path.join(job_dir, f"output.{output_format}")
47
 
48
- # Write the files to disk
49
  with open(video_path, "wb") as video_file:
50
  shutil.copyfileobj(video.file, video_file)
51
 
 
52
  with open(subtitle_path, "wb") as subtitle_file:
53
  shutil.copyfileobj(subtitle.file, subtitle_file)
54
 
55
- # Ensure font color is in the correct format for FFmpeg
56
  if font_color.startswith('#'):
57
  font_color = font_color.lstrip('#')
58
  if len(font_color) == 6:
59
  r, g, b = font_color[0:2], font_color[2:4], font_color[4:6]
60
  font_color = f"&H{b}{g}{r}&"
61
 
62
- # Run FFmpeg command to burn subtitles
63
  subtitle_style = f"FontSize={font_size},PrimaryColour={font_color}"
64
  command = [
65
  "ffmpeg",
@@ -69,12 +68,14 @@ async def burn_subtitles(
69
  output_path
70
  ]
71
 
 
72
  process = subprocess.run(command, capture_output=True, text=True)
73
-
74
  if process.returncode != 0:
75
  raise HTTPException(status_code=500, detail=f"FFmpeg Error: {process.stderr}")
76
 
77
- # Return the processed video
 
 
78
  return FileResponse(
79
  output_path,
80
  media_type=f"video/{output_format}",
@@ -82,29 +83,23 @@ async def burn_subtitles(
82
  )
83
 
84
  except Exception as e:
85
- if os.path.exists(job_dir):
86
- shutil.rmtree(job_dir)
87
  raise HTTPException(status_code=500, detail=str(e))
88
-
89
- finally:
90
- if os.path.exists(job_dir):
91
- shutil.rmtree(job_dir)
92
 
93
  @app.post("/convert-srt")
94
  async def convert_srt(
 
95
  subtitle: UploadFile = File(...),
96
  ):
97
- # Create unique ID for this job
98
- job_id = str(uuid.uuid4())
99
- job_dir = os.path.join(TEMP_DIR, job_id)
100
- os.makedirs(job_dir, exist_ok=True)
101
 
102
  try:
103
  subtitle_path = os.path.join(job_dir, "subtitles.srt")
104
-
105
  with open(subtitle_path, "wb") as subtitle_file:
106
  shutil.copyfileobj(subtitle.file, subtitle_file)
107
 
 
108
  return FileResponse(
109
  subtitle_path,
110
  media_type="text/plain",
@@ -112,11 +107,8 @@ async def convert_srt(
112
  )
113
 
114
  except Exception as e:
 
115
  raise HTTPException(status_code=500, detail=str(e))
116
-
117
- finally:
118
- if os.path.exists(job_dir):
119
- shutil.rmtree(job_dir)
120
 
121
  @app.get("/health")
122
  def health_check():
 
1
  import os
 
2
  import shutil
3
  import subprocess
4
+ import tempfile
5
+ from fastapi import FastAPI, File, UploadFile, Form, HTTPException, BackgroundTasks
6
  from fastapi.responses import FileResponse, RedirectResponse
7
  from fastapi.middleware.cors import CORSMiddleware
 
8
 
9
  app = FastAPI()
10
 
11
+ # Add CORS middleware (adjust allow_origins for production)
12
  app.add_middleware(
13
  CORSMiddleware,
14
+ allow_origins=["*"],
15
  allow_credentials=True,
16
  allow_methods=["*"],
17
  allow_headers=["*"],
18
  )
19
 
20
+ # Ensure the base temporary directory exists.
21
  TEMP_DIR = "temp_files"
22
  os.makedirs(TEMP_DIR, exist_ok=True)
23
 
 
27
 
28
  @app.post("/burn-subtitles")
29
  async def burn_subtitles(
30
+ background_tasks: BackgroundTasks,
31
  video: UploadFile = File(...),
32
  subtitle: UploadFile = File(...),
33
  font_size: str = Form("20"),
34
  font_color: str = Form("white"),
35
  output_format: str = Form("mp4")
36
  ):
37
+ # Create a unique temporary directory for this job.
38
+ job_dir = tempfile.mkdtemp(prefix='job_', dir=TEMP_DIR)
 
 
39
 
40
  try:
41
+ # Build file paths.
42
  video_path = os.path.join(job_dir, f"input{os.path.splitext(video.filename)[1]}")
43
  subtitle_path = os.path.join(job_dir, "subtitles.srt")
44
  output_path = os.path.join(job_dir, f"output.{output_format}")
45
 
46
+ # Save uploaded video file.
47
  with open(video_path, "wb") as video_file:
48
  shutil.copyfileobj(video.file, video_file)
49
 
50
+ # Save uploaded subtitle file.
51
  with open(subtitle_path, "wb") as subtitle_file:
52
  shutil.copyfileobj(subtitle.file, subtitle_file)
53
 
54
+ # Format the font color for FFmpeg if provided as hex.
55
  if font_color.startswith('#'):
56
  font_color = font_color.lstrip('#')
57
  if len(font_color) == 6:
58
  r, g, b = font_color[0:2], font_color[2:4], font_color[4:6]
59
  font_color = f"&H{b}{g}{r}&"
60
 
61
+ # Build the subtitle style string.
62
  subtitle_style = f"FontSize={font_size},PrimaryColour={font_color}"
63
  command = [
64
  "ffmpeg",
 
68
  output_path
69
  ]
70
 
71
+ # Run the FFmpeg command.
72
  process = subprocess.run(command, capture_output=True, text=True)
 
73
  if process.returncode != 0:
74
  raise HTTPException(status_code=500, detail=f"FFmpeg Error: {process.stderr}")
75
 
76
+ # Schedule cleanup of the job directory after the response is sent.
77
+ background_tasks.add_task(shutil.rmtree, job_dir)
78
+
79
  return FileResponse(
80
  output_path,
81
  media_type=f"video/{output_format}",
 
83
  )
84
 
85
  except Exception as e:
86
+ # Clean up immediately on error.
87
+ shutil.rmtree(job_dir, ignore_errors=True)
88
  raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
89
 
90
  @app.post("/convert-srt")
91
  async def convert_srt(
92
+ background_tasks: BackgroundTasks,
93
  subtitle: UploadFile = File(...),
94
  ):
95
+ job_dir = tempfile.mkdtemp(prefix='job_', dir=TEMP_DIR)
 
 
 
96
 
97
  try:
98
  subtitle_path = os.path.join(job_dir, "subtitles.srt")
 
99
  with open(subtitle_path, "wb") as subtitle_file:
100
  shutil.copyfileobj(subtitle.file, subtitle_file)
101
 
102
+ background_tasks.add_task(shutil.rmtree, job_dir)
103
  return FileResponse(
104
  subtitle_path,
105
  media_type="text/plain",
 
107
  )
108
 
109
  except Exception as e:
110
+ shutil.rmtree(job_dir, ignore_errors=True)
111
  raise HTTPException(status_code=500, detail=str(e))
 
 
 
 
112
 
113
  @app.get("/health")
114
  def health_check():