Spaces:
Building
Building
Update app.py
Browse files
app.py
CHANGED
@@ -1,13 +1,9 @@
|
|
1 |
import os
|
2 |
import subprocess
|
3 |
-
import
|
4 |
-
from
|
5 |
-
from
|
6 |
-
|
7 |
-
|
8 |
-
# Configure logging
|
9 |
-
logging.basicConfig(level=logging.INFO)
|
10 |
-
logger = logging.getLogger(__name__)
|
11 |
|
12 |
# Define directories for uploads and outputs
|
13 |
UPLOAD_FOLDER = 'uploads_gradio'
|
@@ -17,22 +13,22 @@ OUTPUT_FOLDER = 'outputs_gradio'
|
|
17 |
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
18 |
os.makedirs(OUTPUT_FOLDER, exist_ok=True)
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
""
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
def animate_image(file_path):
|
36 |
"""
|
37 |
Process the uploaded image and generate an animated GIF.
|
38 |
|
@@ -53,12 +49,11 @@ def animate_image(file_path):
|
|
53 |
char_anno_dir = os.path.join(OUTPUT_FOLDER, f"{base}_out")
|
54 |
os.makedirs(char_anno_dir, exist_ok=True)
|
55 |
|
56 |
-
# Validate file extension
|
57 |
-
if ext.lower() not in ALLOWED_EXTENSIONS:
|
58 |
-
raise ValueError("Unsupported file type. Please upload an image file (png, jpg, jpeg, bmp).")
|
59 |
-
|
60 |
try:
|
61 |
-
|
|
|
|
|
|
|
62 |
|
63 |
# Run the image_to_animation.py script with required arguments
|
64 |
subprocess.run([
|
@@ -70,79 +65,67 @@ def animate_image(file_path):
|
|
70 |
gif_path = os.path.join(char_anno_dir, "video.gif")
|
71 |
|
72 |
if os.path.exists(gif_path):
|
73 |
-
logger.info(f"Animation successful: {gif_path}")
|
74 |
return gif_path
|
75 |
else:
|
76 |
raise FileNotFoundError("Animation failed to generate. Please ensure the input image contains clear humanoid drawings.")
|
77 |
|
78 |
except subprocess.CalledProcessError as e:
|
79 |
-
logger.error(f"Error during processing: {e}")
|
80 |
raise RuntimeError(f"Error during processing: {e}")
|
81 |
except Exception as e:
|
82 |
-
logger.error(f"Unexpected error: {e}")
|
83 |
raise RuntimeError(f"Unexpected error: {e}")
|
84 |
|
85 |
-
@app.
|
86 |
-
def
|
87 |
"""
|
88 |
-
Endpoint to
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
"""
|
90 |
-
|
91 |
-
if
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
if
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
|
|
|
|
|
|
|
|
119 |
else:
|
120 |
-
|
121 |
-
return jsonify({"error": "Allowed file types are png, jpg, jpeg, bmp."}), 400
|
122 |
|
123 |
-
@app.
|
124 |
-
def
|
125 |
-
"""
|
126 |
-
Root endpoint to provide basic information.
|
127 |
-
"""
|
128 |
-
logger.info("Received request to /")
|
129 |
-
return jsonify({
|
130 |
-
"message": "Animated Drawings API",
|
131 |
-
"endpoints": {
|
132 |
-
"/animate": "POST an image to receive an animated GIF."
|
133 |
-
}
|
134 |
-
})
|
135 |
-
|
136 |
-
@app.route('/health', methods=['GET'])
|
137 |
-
def health():
|
138 |
-
"""
|
139 |
-
Health check endpoint.
|
140 |
-
"""
|
141 |
-
logger.info("Received request to /health")
|
142 |
-
return jsonify({"status": "healthy"}), 200
|
143 |
|
144 |
-
if __name__ ==
|
145 |
# Use the PORT environment variable provided by Hugging Face Spaces or default to 7860
|
146 |
port = int(os.getenv("PORT", "7860"))
|
147 |
-
|
148 |
-
app.run(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 FileResponse
|
5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
6 |
+
import uvicorn
|
|
|
|
|
|
|
|
|
7 |
|
8 |
# Define directories for uploads and outputs
|
9 |
UPLOAD_FOLDER = 'uploads_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 |
|
|
|
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([
|
|
|
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)
|
|