ygauravyy commited on
Commit
7822cdd
1 Parent(s): ac59e76

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -68
app.py CHANGED
@@ -1,8 +1,8 @@
1
  import os
2
  import subprocess
3
  from fastapi import FastAPI, File, UploadFile, HTTPException
4
- from fastapi.responses import FileResponse
5
- from fastapi.middleware.cors import CORSMiddleware
6
  import uvicorn
7
 
8
  # Define directories for uploads and outputs
@@ -13,28 +13,13 @@ OUTPUT_FOLDER = 'outputs_gradio'
13
  os.makedirs(UPLOAD_FOLDER, exist_ok=True)
14
  os.makedirs(OUTPUT_FOLDER, exist_ok=True)
15
 
16
- app = FastAPI(
17
- title="Animated Drawings API",
18
- description="Upload your drawing and receive an animated GIF.",
19
- version="1.0.0"
20
- )
21
-
22
- # Enable CORS (optional, adjust origins as needed)
23
- app.add_middleware(
24
- CORSMiddleware,
25
- allow_origins=["*"], # Update with specific origins in production
26
- allow_credentials=True,
27
- allow_methods=["*"],
28
- allow_headers=["*"],
29
- )
30
-
31
- def animate_image(file_path: str) -> str:
32
  """
33
- Process the uploaded image and generate an animated GIF.
34
-
35
  Args:
36
  file_path (str): Path to the uploaded file.
37
-
38
  Returns:
39
  str: Path to the generated GIF.
40
  """
@@ -44,88 +29,66 @@ def animate_image(file_path: str) -> str:
44
  input_path = file_path
45
  filename = os.path.basename(input_path)
46
  base, ext = os.path.splitext(filename)
47
-
48
  # Define the annotation directory for this specific image
49
  char_anno_dir = os.path.join(OUTPUT_FOLDER, f"{base}_out")
50
  os.makedirs(char_anno_dir, exist_ok=True)
51
-
52
  try:
53
  # Validate file extension
54
  allowed_extensions = ['.png', '.jpg', '.jpeg', '.bmp']
55
  if ext.lower() not in allowed_extensions:
56
  raise ValueError("Unsupported file type. Please upload an image file (png, jpg, jpeg, bmp).")
57
-
58
  # Run the image_to_animation.py script with required arguments
59
  subprocess.run([
60
  'python', 'examples/image_to_animation.py',
61
  input_path, char_anno_dir
62
  ], check=True)
63
-
64
  # Path to the generated GIF
65
  gif_path = os.path.join(char_anno_dir, "video.gif")
66
-
67
  if os.path.exists(gif_path):
68
  return gif_path
69
  else:
70
  raise FileNotFoundError("Animation failed to generate. Please ensure the input image contains clear humanoid drawings.")
71
-
72
  except subprocess.CalledProcessError as e:
73
  raise RuntimeError(f"Error during processing: {e}")
74
  except Exception as e:
75
  raise RuntimeError(f"Unexpected error: {e}")
76
 
77
- @app.post("/animate", summary="Generate Animated GIF from Image")
78
- async def generate_gif(image: UploadFile = File(...)):
79
- """
80
- Endpoint to upload an image and receive an animated GIF.
81
 
82
- Args:
83
- image (UploadFile): The image file to be animated.
84
-
85
- Returns:
86
- FileResponse: The generated animated GIF.
87
- """
88
- # Validate the uploaded file
89
- if not image:
90
- raise HTTPException(status_code=400, detail="No file uploaded.")
91
-
92
- filename = image.filename
93
- base, ext = os.path.splitext(filename)
94
- allowed_extensions = ['.png', '.jpg', '.jpeg', '.bmp']
95
- if ext.lower() not in allowed_extensions:
96
- raise HTTPException(status_code=400, detail="Unsupported file type. Please upload an image file (png, jpg, jpeg, bmp).")
97
 
98
- # Save the uploaded file to the upload directory
99
- upload_path = os.path.join(UPLOAD_FOLDER, filename)
100
  try:
101
- with open(upload_path, "wb") as f:
102
- f.write(await image.read())
103
- except Exception as e:
104
- raise HTTPException(status_code=500, detail=f"Failed to save uploaded file: {e}")
105
-
106
- # Process the image to generate GIF
107
- try:
108
- gif_path = animate_image(upload_path)
 
 
 
109
  except ValueError as ve:
110
  raise HTTPException(status_code=400, detail=str(ve))
111
  except FileNotFoundError as fnfe:
112
- raise HTTPException(status_code=500, detail=str(fnfe))
113
  except RuntimeError as re:
114
  raise HTTPException(status_code=500, detail=str(re))
115
  except Exception as e:
116
- raise HTTPException(status_code=500, detail=f"An unexpected error occurred: {e}")
117
-
118
- # Return the generated GIF as a response
119
- if os.path.exists(gif_path):
120
- return FileResponse(path=gif_path, media_type="image/gif", filename="animated.gif")
121
- else:
122
- raise HTTPException(status_code=500, detail="Failed to generate GIF.")
123
 
124
- @app.get("/", summary="Root Endpoint")
125
- def read_root():
126
- return {"message": "Welcome to the Animated Drawings API. Use the /animate endpoint to upload images and receive animated GIFs."}
127
 
128
  if __name__ == "__main__":
129
- # Use the PORT environment variable provided by Hugging Face Spaces or default to 7860
130
  port = int(os.getenv("PORT", "7860"))
131
  uvicorn.run(app, host="0.0.0.0", port=port)
 
1
  import os
2
  import subprocess
3
  from fastapi import FastAPI, File, UploadFile, HTTPException
4
+ from fastapi.responses import JSONResponse
5
+ from fastapi.staticfiles import StaticFiles
6
  import uvicorn
7
 
8
  # Define directories for uploads and outputs
 
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
  """
 
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:
60
  raise RuntimeError(f"Unexpected error: {e}")
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))
83
  except FileNotFoundError as fnfe:
84
+ raise HTTPException(status_code=404, detail=str(fnfe))
85
  except RuntimeError as re:
86
  raise HTTPException(status_code=500, detail=str(re))
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"))
94
  uvicorn.run(app, host="0.0.0.0", port=port)