ygauravyy commited on
Commit
ac59e76
1 Parent(s): b4a0d76

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -89
app.py CHANGED
@@ -1,13 +1,9 @@
1
  import os
2
  import subprocess
3
- import logging
4
- from flask import Flask, request, send_file, jsonify
5
- from werkzeug.utils import secure_filename
6
- from flask_cors import CORS
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
- # Initialize Flask app
21
- app = Flask(__name__)
22
- app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
23
-
24
- # Enable CORS for all routes (optional, adjust origins as needed)
25
- CORS(app)
26
-
27
- # Allowed file extensions
28
- ALLOWED_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.bmp'}
29
-
30
- def allowed_file(filename):
31
- """Check if the file has an allowed extension."""
32
- _, ext = os.path.splitext(filename)
33
- return ext.lower() in ALLOWED_EXTENSIONS
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
- logger.info(f"Starting animation for {input_path}")
 
 
 
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.route('/animate', methods=['POST'])
86
- def animate():
87
  """
88
- Endpoint to receive an image and return the animated GIF.
 
 
 
 
 
 
89
  """
90
- logger.info("Received request to /animate")
91
- if 'file' not in request.files:
92
- logger.warning("No file part in the request.")
93
- return jsonify({"error": "No file part in the request."}), 400
94
-
95
- file = request.files['file']
96
-
97
- if file.filename == '':
98
- logger.warning("No file selected for uploading.")
99
- return jsonify({"error": "No file selected for uploading."}), 400
100
-
101
- if file and allowed_file(file.filename):
102
- filename = secure_filename(file.filename)
103
- input_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
104
- file.save(input_path)
105
- logger.info(f"File saved to {input_path}")
106
-
107
- try:
108
- gif_path = animate_image(input_path)
109
- logger.info(f"Sending GIF: {gif_path}")
110
- return send_file(
111
- gif_path,
112
- mimetype='image/gif',
113
- as_attachment=True,
114
- download_name=f"{os.path.splitext(filename)[0]}.gif"
115
- )
116
- except Exception as e:
117
- logger.error(f"Error in /animate: {e}")
118
- return jsonify({"error": str(e)}), 500
 
 
 
 
119
  else:
120
- logger.warning("Allowed file types are png, jpg, jpeg, bmp.")
121
- return jsonify({"error": "Allowed file types are png, jpg, jpeg, bmp."}), 400
122
 
123
- @app.route('/', methods=['GET'])
124
- def index():
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__ == '__main__':
145
  # Use the PORT environment variable provided by Hugging Face Spaces or default to 7860
146
  port = int(os.getenv("PORT", "7860"))
147
- logger.info(f"Starting Flask app on port {port}")
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)