File size: 5,612 Bytes
83e35a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Simple Comic Generator App
- NO comic styling (preserves colors)
- ONLY 12 meaningful story panels
- Clean grid layout
"""

import os
import time
from flask import Flask, request, render_template, send_from_directory
from backend.subtitles.subs_real import get_real_subtitles
from backend.simple_comic_generator import SimpleComicGenerator
from backend.advanced_image_enhancer import AdvancedImageEnhancer

app = Flask(__name__)

# Ensure directories exist
os.makedirs('video', exist_ok=True)
os.makedirs('frames/final', exist_ok=True)
os.makedirs('output', exist_ok=True)

class CleanComicGenerator:
    def __init__(self):
        self.video_path = 'video/uploaded.mp4'
        self.simple_generator = SimpleComicGenerator()
        self.enhancer = AdvancedImageEnhancer()
        
    def generate(self):
        """Generate clean comic with meaningful panels only"""
        start_time = time.time()
        
        try:
            print("🎬 Starting Clean Comic Generation...")
            print("πŸ“‹ Settings:")
            print("  - Target: 12 meaningful panels")
            print("  - No comic styling (preserve colors)")
            print("  - Grid layout: 3x4")
            
            # 1. Extract subtitles
            print("\nπŸ“ Extracting subtitles...")
            get_real_subtitles(self.video_path)
            
            # 2. Generate comic with meaningful panels
            print("\nπŸ“– Selecting meaningful story moments...")
            success = self.simple_generator.generate_meaningful_comic(self.video_path)
            
            if success:
                # 3. Enhance images (optional, preserves colors)
                print("\n✨ Enhancing image quality...")
                self._enhance_frames()
                
                print(f"\nβœ… Comic generated in {time.time() - start_time:.1f} seconds!")
                print("πŸ“ View at: output/comic_simple.html")
                return True
            else:
                print("❌ Comic generation failed")
                return False
                
        except Exception as e:
            print(f"❌ Error: {e}")
            return False
    
    def _enhance_frames(self):
        """Enhance frames with color preservation"""
        frames_dir = 'frames/final'
        frames = [f for f in os.listdir(frames_dir) if f.endswith('.png')]
        
        # Configure enhancer for color preservation
        self.enhancer.use_ai_models = False  # Disable AI models that might change colors
        
        for i, frame in enumerate(frames):
            try:
                frame_path = os.path.join(frames_dir, frame)
                print(f"  Enhancing {frame} ({i+1}/{len(frames)})...")
                
                # Basic enhancement only (sharpness, brightness)
                import cv2
                img = cv2.imread(frame_path)
                
                # Slight sharpening
                kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]]) / 1
                sharpened = cv2.filter2D(img, -1, kernel)
                
                # Blend with original (preserve colors)
                enhanced = cv2.addWeighted(img, 0.7, sharpened, 0.3, 0)
                
                # Save with high quality
                cv2.imwrite(frame_path, enhanced, [cv2.IMWRITE_PNG_COMPRESSION, 0])
                
            except Exception as e:
                print(f"  ⚠️ Enhancement failed for {frame}: {e}")

# Global generator instance
comic_generator = CleanComicGenerator()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/uploader', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        try:
            if 'file' not in request.files:
                return "❌ No file uploaded"
            
            f = request.files['file']
            if f.filename == '':
                return "❌ No file selected"
            
            # Save video
            f.save("video/uploaded.mp4")
            print(f"βœ… Video saved: {f.filename}")
            
            # Generate comic
            success = comic_generator.generate()
            
            if success:
                return '''
                <html>
                <body style="font-family: Arial; padding: 20px;">
                    <h2>βœ… Comic Generated Successfully!</h2>
                    <p>Created 12 meaningful story panels with preserved colors.</p>
                    <a href="/comic" style="display: inline-block; padding: 10px 20px; background: #4CAF50; color: white; text-decoration: none; border-radius: 5px;">View Comic</a>
                </body>
                </html>
                '''
            else:
                return "❌ Comic generation failed"
                
        except Exception as e:
            return f"❌ Error: {str(e)}"

@app.route('/comic')
def view_comic():
    """Serve the generated comic"""
    return send_from_directory('output', 'comic_simple.html')

@app.route('/frames/final/<path:filename>')
def serve_frame(filename):
    """Serve frame images"""
    return send_from_directory('frames/final', filename)

if __name__ == '__main__':
    import numpy as np  # Import for enhancement
    
    print("πŸš€ Starting Simple Comic Generator...")
    print("✨ Features:")
    print("   - 12 meaningful story panels")
    print("   - Original colors preserved")
    print("   - Clean grid layout")
    print("   - No unnecessary processing")
    print("\n🌐 Open browser to: http://localhost:5000")
    
    app.run(debug=True, host='0.0.0.0', port=5000)