-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
256 lines (216 loc) · 8.73 KB
/
app.py
File metadata and controls
256 lines (216 loc) · 8.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
from flask import Flask, jsonify, request, render_template, send_file, send_from_directory
from services.video_generator import VideoGenerator
from coverr.analyzer import CoverrAnalyzer
from pexels.analyzer import PexelsAnalyzer
from pixabay.analyzer import PixabayAnalyzer
from api.quotes import QuoteAPI
import logging
import os
from api.tts_client import TTSClient
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = Flask(__name__)
# Initialize services
generator = VideoGenerator()
coverr_analyzer = CoverrAnalyzer()
pexels_analyzer = PexelsAnalyzer()
pixabay_analyzer = PixabayAnalyzer()
quotes_api = QuoteAPI()
# Define the output directory path
OUTPUT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'output')
# Ensure the output directory exists
os.makedirs(OUTPUT_DIR, exist_ok=True)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/download/<path:filename>')
def download_file(filename):
try:
# Check if the filename is already an absolute path
if not os.path.isabs(filename):
# If it's not absolute, assume it's relative to the output directory
filename = os.path.join(OUTPUT_DIR, filename)
# Handle the case where only the filename is passed (without the path)
if os.path.basename(filename) == filename:
filename = os.path.join(OUTPUT_DIR, filename)
if not os.path.exists(filename):
logger.error(f"File not found: {filename}")
return jsonify({"error": "File not found"}), 404
return send_file(filename, as_attachment=True)
except Exception as e:
logger.error(f"Error downloading file: {e}")
return jsonify({"error": "File not found"}), 404
@app.route('/video/<path:filename>')
def serve_video(filename):
"""Serve the video file for preview"""
try:
return send_from_directory(OUTPUT_DIR, filename, mimetype='video/mp4')
except Exception as e:
logger.error(f"Error serving video file: {e}")
return jsonify({"success": False, "error": "Video file not found"}), 404
@app.route('/get-random-quote', methods=['GET'])
def get_random_quote():
"""Get a random quote without generating video"""
try:
quote_data = quotes_api.get_random_quote()
if not quote_data:
return jsonify({"error": "Failed to fetch quote", "success": False}), 500
return jsonify({
"success": True,
"quote": quote_data["quote"],
"author": quote_data["author"],
"category": quote_data["type"]
}), 200
except Exception as e:
logger.error(f"Error fetching quote: {e}")
return jsonify({"error": str(e), "success": False}), 500
@app.route('/generate-video', methods=['POST'])
def generate_video():
"""
Generate a video with a random quote and matching background
Expects: {
"quote": "quote text",
"author": "author name"
}
"""
try:
data = request.get_json()
if not data or "quote" not in data or "author" not in data:
return jsonify({"error": "Missing quote or author", "success": False}), 400
quote = data["quote"]
author = data["author"]
analyzer_request = data["analyzer"]
if analyzer_request == "coverr":
analyzer = coverr_analyzer
elif analyzer_request == "pexels":
analyzer = pexels_analyzer
elif analyzer_request == "pixabay":
analyzer = pixabay_analyzer
else:
return jsonify({"error": "Invalid analyzer specified", "success": False}), 400
tts_voice = data.get("voice", "en-US-Wavenet-D")
# Get matching video URL
video_urls = analyzer.get_video_url(quote)
if not video_urls or not video_urls.get("high_quality"):
return jsonify({"error": "Failed to find matching video", "success": False}), 500
# Generate video
output_path = generator.generate_video(quote, author, video_urls["high_quality"], tts_voice=tts_voice)
if not output_path:
return jsonify({"success": False, "error": "Failed to generate video"}), 500
# Extract just the filename for client use
video_filename = os.path.basename(output_path)
return jsonify({
"success": True,
"video_path": video_filename,
"quote": quote,
"author": author
}), 200
except Exception as e:
logger.error(f"Error generating video: {e}")
return jsonify({"error": str(e), "success": False}), 500
@app.route('/generate-video-custom', methods=['POST'])
def generate_video_custom():
"""
Generate a video with a custom quote
Expects JSON body with: {
"quote": "your quote",
"author": "quote author"
}
"""
try:
data = request.get_json()
if not data or "quote" not in data or "author" not in data:
return jsonify({"error": "Missing quote or author", "success": False}), 400
analyzer = data.get("analyzer")
if analyzer == "coverr":
analyzer = coverr_analyzer
elif analyzer == "pexels":
analyzer = pexels_analyzer
elif analyzer == "pixabay":
analyzer = pixabay_analyzer
# Get matching video URL
video_urls = analyzer.get_video_url(data["quote"])
if not video_urls or not video_urls.get("high_quality"):
return jsonify({"error": "Failed to find matching video", "success": False}), 500
# Generate video
output_path = generator.generate_video(
quote=data["quote"],
author=data["author"],
video_url=video_urls["high_quality"],
tts_voice=data.get("voice", "en-US-Wavenet-D")
)
if not output_path:
return jsonify({"error": "Failed to generate video", "success": False}), 500
# Return just the filename, not the full path
video_filename = os.path.basename(output_path)
return jsonify({
"success": True,
"video_path": video_filename,
"quote": data["quote"],
"author": data["author"]
}), 200
except Exception as e:
logger.error(f"Error generating custom video: {e}")
return jsonify({"error": str(e), "success": False}), 500
# Route to list available videos
@app.route('/api/videos', methods=['GET'])
def list_videos():
try:
videos = []
for file in os.listdir(OUTPUT_DIR):
if file.endswith('.mp4'):
file_path = os.path.join(OUTPUT_DIR, file)
file_size = os.path.getsize(file_path)
videos.append({
'filename': file,
'size': file_size,
'created': os.path.getctime(file_path)
})
return jsonify({"success": True, "videos": videos})
except Exception as e:
logger.error(f"Error listing videos: {e}")
return jsonify({"success": False, "error": str(e)}), 500
# Route to download video files
@app.route('/api/download/<filename>')
def api_download_video(filename):
"""API endpoint to download a video file"""
try:
file_path = os.path.join(OUTPUT_DIR, filename)
if not os.path.exists(file_path):
app.logger.error(f"File not found: {file_path}")
return jsonify({"error": "File not found"}), 404
# Send the file as an attachment (triggers download)
return send_from_directory(
OUTPUT_DIR,
filename,
as_attachment=True,
download_name=filename # For Flask >= 2.0
)
except Exception as e:
app.logger.error(f"Error downloading file: {e}")
return jsonify({"error": "Unable to download file"}), 500
@app.route('/api/videos/<filename>')
def api_serve_video(filename):
try:
return send_from_directory(OUTPUT_DIR, filename, mimetype='video/mp4')
except Exception as e:
app.logger.error(f"Error serving video: {e}")
return jsonify({"error": "Video not found"}), 404
@app.route('/list/voices', methods=['GET'])
def list_voices():
"""List available voices"""
try:
tts = TTSClient()
voices = tts.list_voices()
if not voices:
return jsonify({"error": "Failed to fetch voices", "success": False}), 500
return jsonify({
"success": True,
"voices": voices
}), 200
except Exception as e:
logger.error(f"Error fetching voices: {e}")
return jsonify({"error": str(e), "success": False}), 500
if __name__ == "__main__":
app.run(debug=True, host='0.0.0.0', port=5000)