Spaces:
Sleeping
Sleeping
| from flask import Flask, request, jsonify, send_file | |
| from flask_cors import CORS | |
| from audio_generator import generate_audio | |
| import os | |
| import logging | |
| from datetime import datetime | |
| app = Flask(__name__) | |
| CORS(app, resources={r"/tts": {"origins": "*"}}) | |
| # Configure logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| def health(): | |
| return jsonify({"status": "healthy", "time": datetime.utcnow().isoformat()}) | |
| def text_to_speech(): | |
| try: | |
| if not request.is_json: | |
| return jsonify({"error": "JSON body required"}), 400 | |
| data = request.get_json() | |
| text = data.get("text", "").strip() | |
| if not text: | |
| return jsonify({"error": "Text is required"}), 400 | |
| if len(text) > 3000: | |
| return jsonify({"error": "Text exceeds 3000 character limit"}), 400 | |
| audio_path = generate_audio(text) | |
| # Clean up old files (keep last 10) | |
| files = sorted([f for f in os.listdir(os.path.dirname(audio_path))], | |
| key=lambda f: os.path.getmtime(os.path.join(os.path.dirname(audio_path), f))) | |
| for old_file in files[:-10]: | |
| os.remove(os.path.join(os.path.dirname(audio_path), old_file)) | |
| return send_file( | |
| audio_path, | |
| mimetype="audio/mpeg", | |
| as_attachment=True, | |
| download_name="speech.mp3" | |
| ) | |
| except Exception as e: | |
| logger.error(f"Error: {str(e)}") | |
| return jsonify({"error": str(e)}), 500 | |
| if __name__ == "__main__": | |
| os.makedirs("tts_outputs", exist_ok=True) | |
| app.run(host="0.0.0.0", port=7860) |