File size: 7,199 Bytes
be81231
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

FastAPI backend with WebSocket support for real-time video processing

"""

from fastapi import FastAPI, WebSocket, WebSocketDisconnect, UploadFile, File, HTTPException, BackgroundTasks
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import uvicorn
import os
import uuid
import json
import asyncio
from pathlib import Path
from typing import Dict, Optional
import tempfile
import shutil

from async_processor import async_processor

app = FastAPI(title="VR180 Converter API", version="2.0.0")

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Create necessary directories
os.makedirs("uploads", exist_ok=True)
os.makedirs("outputs", exist_ok=True)
os.makedirs("thumbnails", exist_ok=True)
os.makedirs("static", exist_ok=True)

# Mount static files
app.mount("/static", StaticFiles(directory="static"), name="static")

@app.get("/")
async def root():
    """Health check endpoint"""
    return {"message": "VR180 Converter API is running", "version": "2.0.0"}

@app.get("/api/health")
async def health_check():
    """Detailed health check"""
    return {
        "status": "healthy",
        "message": "VR180 Converter API is running",
        "version": "2.0.0",
        "active_jobs": len(async_processor.processing_jobs),
        "active_connections": len(async_processor.active_connections)
    }

@app.post("/api/upload")
async def upload_video(file: UploadFile = File(...)):
    """Upload video file and return metadata"""
    try:
        # Validate file type
        allowed_extensions = {'.mp4', '.avi', '.mov', '.mkv', '.webm'}
        file_extension = Path(file.filename).suffix.lower()
        
        if file_extension not in allowed_extensions:
            raise HTTPException(status_code=400, detail="Invalid file type")
        
        # Generate unique filename
        file_id = str(uuid.uuid4())
        filename = f"{file_id}_{file.filename}"
        filepath = os.path.join("uploads", filename)
        
        # Save file
        with open(filepath, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
        
        # Get video info
        video_info = async_processor.get_video_info(filepath)
        
        # Generate thumbnail
        thumbnail_path = async_processor.generate_thumbnail(filepath)
        
        return {
            "success": True,
            "file_id": file_id,
            "filename": filename,
            "original_name": file.filename,
            "video_info": video_info,
            "thumbnail": thumbnail_path,
            "file_size": os.path.getsize(filepath)
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/process/{file_id}")
async def start_processing(file_id: str, background_tasks: BackgroundTasks):
    """Start video processing job"""
    try:
        # Find the uploaded file
        upload_dir = Path("uploads")
        files = list(upload_dir.glob(f"{file_id}_*"))
        
        if not files:
            raise HTTPException(status_code=404, detail="File not found")
        
        input_path = str(files[0])
        
        # Generate output path
        output_filename = f"vr180_{Path(input_path).name}"
        output_path = os.path.join("outputs", output_filename)
        
        # Start processing in background
        job_id = str(uuid.uuid4())
        background_tasks.add_task(
            async_processor.process_video_async,
            input_path,
            output_path,
            job_id
        )
        
        return {
            "success": True,
            "job_id": job_id,
            "message": "Processing started",
            "websocket_url": f"/ws/{job_id}"
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.websocket("/ws/{job_id}")
async def websocket_endpoint(websocket: WebSocket, job_id: str):
    """WebSocket endpoint for real-time updates"""
    await async_processor.connect(websocket, job_id)
    
    try:
        while True:
            # Keep connection alive
            data = await websocket.receive_text()
            message = json.loads(data)
            
            if message.get("type") == "ping":
                await websocket.send_text(json.dumps({"type": "pong"}))
                
    except WebSocketDisconnect:
        async_processor.disconnect(job_id)

@app.get("/api/status/{job_id}")
async def get_job_status(job_id: str):
    """Get processing job status"""
    status = async_processor.get_job_status(job_id)
    
    if not status:
        raise HTTPException(status_code=404, detail="Job not found")
    
    return status

@app.get("/api/download/{filename}")
async def download_video(filename: str):
    """Download processed video"""
    filepath = os.path.join("outputs", filename)
    
    if not os.path.exists(filepath):
        raise HTTPException(status_code=404, detail="File not found")
    
    return FileResponse(
        filepath,
        media_type="video/mp4",
        filename=filename,
        headers={"Content-Disposition": f"attachment; filename={filename}"}
    )

@app.get("/api/thumbnail/{filename}")
async def get_thumbnail(filename: str):
    """Get video thumbnail"""
    thumb_path = os.path.join("thumbnails", filename)
    
    if not os.path.exists(thumb_path):
        raise HTTPException(status_code=404, detail="Thumbnail not found")
    
    return FileResponse(thumb_path, media_type="image/jpeg")

@app.delete("/api/cleanup/{file_id}")
async def cleanup_files(file_id: str):
    """Clean up uploaded and processed files"""
    try:
        # Remove uploaded file
        upload_dir = Path("uploads")
        upload_files = list(upload_dir.glob(f"{file_id}_*"))
        for file in upload_files:
            file.unlink()
        
        # Remove output file
        output_dir = Path("outputs")
        output_files = list(output_dir.glob(f"vr180_{file_id}_*"))
        for file in output_files:
            file.unlink()
        
        # Remove thumbnail
        thumb_dir = Path("thumbnails")
        thumb_files = list(thumb_dir.glob(f"{file_id}_*"))
        for file in thumb_files:
            file.unlink()
        
        return {"success": True, "message": "Files cleaned up"}
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/api/jobs")
async def list_jobs():
    """List all processing jobs"""
    return {
        "jobs": async_processor.processing_jobs,
        "active_connections": len(async_processor.active_connections)
    }

if __name__ == "__main__":
    uvicorn.run(
        "fastapi_app:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        workers=1  # Single worker for shared state
    )