File size: 4,619 Bytes
54ed165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Flask, request, jsonify
from flask_cors import CORS
import replicate
import os
from dotenv import load_dotenv
from datetime import datetime
import logging

load_dotenv()

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

app = Flask(__name__)
CORS(app)

# Set your Replicate API token
REPLICATE_API_TOKEN = os.getenv('REPLICATE_API_TOKEN')
if REPLICATE_API_TOKEN:
    os.environ['REPLICATE_API_TOKEN'] = REPLICATE_API_TOKEN

@app.route('/health', methods=['GET'])
def health():
    has_token = bool(REPLICATE_API_TOKEN)
    return jsonify({
        'status': 'healthy',
        'service': 'Replicate API',
        'token_configured': has_token
    })

@app.route('/models', methods=['GET'])
def list_models():
    """Return available models"""
    return jsonify({
        'models': {
            'hailuo': {
                'name': 'Hailuo Video-01 (MiniMax) - 6s',
                'description': 'Real Hailuo model - High quality, 6 seconds',
                'type': 'text-to-video',
                'duration': '6s'
            },
            'cogvideox': {
                'name': 'CogVideoX-5B - 6s',
                'description': 'High quality text-to-video, 6 seconds',
                'type': 'text-to-video',
                'duration': '6s'
            },
            'hunyuan': {
                'name': 'HunyuanVideo (Tencent) - 5s+',
                'description': 'State-of-the-art by Tencent, 5+ seconds',
                'type': 'text-to-video',
                'duration': '5s+'
            },
            'luma': {
                'name': 'Luma Dream Machine - 5s',
                'description': 'Cinematic quality, 5 seconds',
                'type': 'text-to-video',
                'duration': '5s'
            },
            'runway': {
                'name': 'Runway Gen-3 - 10s ⭐',
                'description': 'Professional quality, up to 10 seconds (longer!)',
                'type': 'text-to-video',
                'duration': '10s'
            }
        }
    })

@app.route('/generate-video', methods=['POST'])
def generate_video():
    try:
        if not REPLICATE_API_TOKEN:
            return jsonify({
                'error': 'Replicate API token not configured. Add REPLICATE_API_TOKEN to .env file'
            }), 500
        
        data = request.json
        prompt = data.get('prompt', '')
        model_id = data.get('model', 'hailuo')
        
        if not prompt:
            return jsonify({'error': 'Prompt is required'}), 400
        
        logger.info(f"Generating video with {model_id}: {prompt[:100]}")
        
        # Select model
        model_map = {
            'hailuo': "minimax/video-01",  # Real Hailuo model! (6s)
            'cogvideox': "lucataco/cogvideox-5b",  # CogVideoX-5B (6s)
            'hunyuan': "tencent/hunyuan-video",  # HunyuanVideo (5s+)
            'luma': "fofr/dream-machine",  # Luma Dream Machine (5s)
            'runway': "stability-ai/stable-video-diffusion-img2vid-xt",  # Runway (10s)
        }
        model_name = model_map.get(model_id, model_map['hailuo'])
        
        # Generate video
        output = replicate.run(
            model_name,
            input={"prompt": prompt}
        )
        
        # Output is a video URL
        video_url = output if isinstance(output, str) else (output[0] if isinstance(output, list) else str(output))
        
        logger.info(f"Video generated successfully: {video_url}")
        
        return jsonify({
            'video_url': video_url,
            'prompt': prompt,
            'model': model_id,
            'model_name': 'Hailuo Video-01 (MiniMax)' if model_id == 'hailuo' else 'CogVideoX-5B',
            'timestamp': datetime.now().isoformat(),
            'service': 'Replicate API'
        })
        
    except Exception as e:
        logger.error(f"Error: {str(e)}")
        return jsonify({'error': f'Video generation failed: {str(e)}'}), 500

if __name__ == '__main__':
    if not REPLICATE_API_TOKEN:
        print("=" * 60)
        print("⚠️  WARNING: REPLICATE_API_TOKEN not set!")
        print("=" * 60)
        print("1. Sign up at: https://replicate.com")
        print("2. Get token from: https://replicate.com/account/api-tokens")
        print("3. Add to .env file: REPLICATE_API_TOKEN=your_token_here")
        print("=" * 60)
    else:
        print("✅ Replicate API token configured!")
    
    logger.info("Starting Replicate backend on port 5000")
    app.run(host='0.0.0.0', port=5000, debug=False)