ygauravyy commited on
Commit
8c63db9
1 Parent(s): a3044ee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -34
app.py CHANGED
@@ -5,23 +5,16 @@ from fastapi.responses import JSONResponse
5
  from fastapi.staticfiles import StaticFiles
6
  import uvicorn
7
 
8
- # Define directories for uploads and outputs
9
  UPLOAD_FOLDER = 'uploads_gradio'
10
  OUTPUT_FOLDER = 'outputs_gradio'
11
 
12
- # Create directories if they don't exist
13
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
14
  os.makedirs(OUTPUT_FOLDER, exist_ok=True)
15
 
16
  def animate_image(file_path):
17
  """
18
- Function to process the uploaded image and generate an animated GIF.
19
-
20
- Args:
21
- file_path (str): Path to the uploaded file.
22
-
23
- Returns:
24
- str: Path to the generated GIF.
25
  """
26
  if not file_path:
27
  raise ValueError("No file uploaded.")
@@ -29,31 +22,28 @@ def animate_image(file_path):
29
  input_path = file_path
30
  filename = os.path.basename(input_path)
31
  base, ext = os.path.splitext(filename)
32
-
33
- # Define the annotation directory for this specific image
 
 
 
 
 
34
  char_anno_dir = os.path.join(OUTPUT_FOLDER, f"{base}_out")
35
  os.makedirs(char_anno_dir, exist_ok=True)
36
-
 
37
  try:
38
- # Validate file extension
39
- allowed_extensions = ['.png', '.jpg', '.jpeg', '.bmp']
40
- if ext.lower() not in allowed_extensions:
41
- raise ValueError("Unsupported file type. Please upload an image file (png, jpg, jpeg, bmp).")
42
-
43
- # Run the image_to_animation.py script with required arguments
44
  subprocess.run([
45
  'python', 'examples/image_to_animation.py',
46
  input_path, char_anno_dir
47
  ], check=True)
48
-
49
- # Path to the generated GIF
50
  gif_path = os.path.join(char_anno_dir, "video.gif")
51
-
52
- if os.path.exists(gif_path):
53
- return gif_path
54
- else:
55
- raise FileNotFoundError("Animation failed to generate. Please ensure the input image contains clear humanoid drawings.")
56
-
57
  except subprocess.CalledProcessError as e:
58
  raise RuntimeError(f"Error during processing: {e}")
59
  except Exception as e:
@@ -61,22 +51,23 @@ def animate_image(file_path):
61
 
62
  app = FastAPI()
63
 
64
- # Serve the outputs folder as static files so that generated GIFs can be accessed directly
65
  app.mount("/outputs", StaticFiles(directory=OUTPUT_FOLDER), name="outputs")
66
 
67
  @app.post("/animate")
68
  async def animate_endpoint(file: UploadFile = File(...)):
69
  try:
70
- # Save the uploaded file
71
  file_path = os.path.join(UPLOAD_FOLDER, file.filename)
72
  with open(file_path, "wb") as f:
73
  f.write(await file.read())
74
-
75
  gif_path = animate_image(file_path)
76
-
77
- # Construct a URL to access the generated GIF
78
- gif_url = f"/outputs/{os.path.basename(os.path.dirname(gif_path))}/{os.path.basename(gif_path)}"
79
-
 
80
  return JSONResponse({"gif_url": gif_url})
81
  except ValueError as ve:
82
  raise HTTPException(status_code=400, detail=str(ve))
@@ -87,7 +78,6 @@ async def animate_endpoint(file: UploadFile = File(...)):
87
  except Exception as e:
88
  raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")
89
 
90
-
91
  if __name__ == "__main__":
92
  # Use the PORT environment variable provided by Hugging Face Spaces
93
  port = int(os.getenv("PORT", "7860"))
 
5
  from fastapi.staticfiles import StaticFiles
6
  import uvicorn
7
 
 
8
  UPLOAD_FOLDER = 'uploads_gradio'
9
  OUTPUT_FOLDER = 'outputs_gradio'
10
 
11
+ # Ensure directories exist
12
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
13
  os.makedirs(OUTPUT_FOLDER, exist_ok=True)
14
 
15
  def animate_image(file_path):
16
  """
17
+ Process the uploaded image and generate an animated GIF.
 
 
 
 
 
 
18
  """
19
  if not file_path:
20
  raise ValueError("No file uploaded.")
 
22
  input_path = file_path
23
  filename = os.path.basename(input_path)
24
  base, ext = os.path.splitext(filename)
25
+
26
+ # Validate extension
27
+ allowed_extensions = ['.png', '.jpg', '.jpeg', '.bmp']
28
+ if ext.lower() not in allowed_extensions:
29
+ raise ValueError("Unsupported file type. Please upload png, jpg, jpeg, or bmp.")
30
+
31
+ # Create output directory for this specific image
32
  char_anno_dir = os.path.join(OUTPUT_FOLDER, f"{base}_out")
33
  os.makedirs(char_anno_dir, exist_ok=True)
34
+
35
+ # Run the image_to_animation script
36
  try:
 
 
 
 
 
 
37
  subprocess.run([
38
  'python', 'examples/image_to_animation.py',
39
  input_path, char_anno_dir
40
  ], check=True)
41
+
 
42
  gif_path = os.path.join(char_anno_dir, "video.gif")
43
+ if not os.path.exists(gif_path):
44
+ raise FileNotFoundError("Failed to generate animation. Ensure the input image contains clear humanoid drawings.")
45
+ return gif_path
46
+
 
 
47
  except subprocess.CalledProcessError as e:
48
  raise RuntimeError(f"Error during processing: {e}")
49
  except Exception as e:
 
51
 
52
  app = FastAPI()
53
 
54
+ # Serve the outputs directory statically so that generated GIFs can be accessed via URL
55
  app.mount("/outputs", StaticFiles(directory=OUTPUT_FOLDER), name="outputs")
56
 
57
  @app.post("/animate")
58
  async def animate_endpoint(file: UploadFile = File(...)):
59
  try:
60
+ # Save uploaded file
61
  file_path = os.path.join(UPLOAD_FOLDER, file.filename)
62
  with open(file_path, "wb") as f:
63
  f.write(await file.read())
64
+
65
  gif_path = animate_image(file_path)
66
+ # Construct a URL to the generated GIF
67
+ relative_gif_dir = os.path.basename(os.path.dirname(gif_path))
68
+ gif_filename = os.path.basename(gif_path)
69
+ gif_url = f"/outputs/{relative_gif_dir}/{gif_filename}"
70
+
71
  return JSONResponse({"gif_url": gif_url})
72
  except ValueError as ve:
73
  raise HTTPException(status_code=400, detail=str(ve))
 
78
  except Exception as e:
79
  raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")
80
 
 
81
  if __name__ == "__main__":
82
  # Use the PORT environment variable provided by Hugging Face Spaces
83
  port = int(os.getenv("PORT", "7860"))