Team Ai
Apppublic

alphanet06/processor

sourceHugging Faceupdated 11mo agoView on Hugging Face
0likes
script.py344 linesDownload Raw Back to root
1# Create an updated setup with FastAPI to serve the MKV files2fastapi_app_content = '''#!/usr/bin/env python33"""4N_m3u8DL-RE DRM Processor with FastAPI File Server5Serves processed MKV files to Stremio clients6"""7 8from fastapi import FastAPI, HTTPException9from fastapi.responses import FileResponse, StreamingResponse10from fastapi.staticfiles import StaticFiles11from fastapi.middleware.cors import CORSMiddleware12import os13from pathlib import Path14import subprocess15from datetime import datetime16import uvicorn17 18app = FastAPI(title="N_m3u8DL-RE DRM Processor")19 20# Enable CORS for Stremio clients21app.add_middleware(22    CORSMiddleware,23    allow_origins=["*"],24    allow_credentials=True,25    allow_methods=["*"],26    allow_headers=["*"],27)28 29# Paths30BASE_DIR = Path("/app")31STREAM_DIR = BASE_DIR / "stream"32STREAM_DIR.mkdir(parents=True, exist_ok=True)33 34# Mount static files directory for direct file access35app.mount("/stream", StaticFiles(directory=str(STREAM_DIR)), name="stream")36 37@app.get("/")38async def root():39    """Root endpoint with service information."""40    return {41        "service": "N_m3u8DL-RE DRM Processor",42        "version": "1.0",43        "status": "running",44        "endpoints": {45            "health": "/health",46            "list_files": "/files",47            "stream_file": "/stream/{filename}"48        }49    }50 51@app.get("/health")52async def health_check():53    """Health check endpoint."""54    tools_status = {}55    56    # Check N_m3u8DL-RE57    try:58        result = subprocess.run(["/usr/local/bin/N_m3u8DL-RE", "--version"], 59                              capture_output=True, text=True, timeout=5)60        tools_status["N_m3u8DL-RE"] = "available" if result.returncode == 0 else "error"61    except:62        tools_status["N_m3u8DL-RE"] = "unavailable"63    64    # Check FFmpeg65    try:66        result = subprocess.run(["/usr/bin/ffmpeg", "-version"], 67                              capture_output=True, text=True, timeout=5)68        tools_status["ffmpeg"] = "available" if result.returncode == 0 else "error"69    except:70        tools_status["ffmpeg"] = "unavailable"71    72    # Check mp4decrypt73    try:74        subprocess.run(["/usr/local/bin/mp4decrypt"], 75                      capture_output=True, text=True, timeout=5)76        tools_status["mp4decrypt"] = "available"77    except:78        tools_status["mp4decrypt"] = "unavailable"79    80    return {81        "status": "healthy",82        "timestamp": datetime.now().isoformat(),83        "tools": tools_status,84        "stream_directory": str(STREAM_DIR),85        "files_available": len(list(STREAM_DIR.glob("*.mkv")))86    }87 88@app.get("/files")89async def list_files():90    """List all available MKV files in the stream directory."""91    try:92        files = []93        for file_path in STREAM_DIR.glob("*.mkv"):94            stat = file_path.stat()95            files.append({96                "filename": file_path.name,97                "size_mb": round(stat.st_size / (1024 * 1024), 2),98                "modified": datetime.fromtimestamp(stat.st_mtime).isoformat(),99                "url": f"/stream/{file_path.name}"100            })101        102        return {103            "count": len(files),104            "files": sorted(files, key=lambda x: x["modified"], reverse=True)105        }106    except Exception as e:107        raise HTTPException(status_code=500, detail=f"Error listing files: {str(e)}")108 109 110@app.get("/info")111async def system_info():112    """Get system and directory information."""113    return {114        "base_directory": str(BASE_DIR),115        "stream_directory": str(STREAM_DIR),116        "disk_usage": {117            "total_files": len(list(STREAM_DIR.glob("*"))),118            "mkv_files": len(list(STREAM_DIR.glob("*.mkv")))119        },120        "tools": {121            "N_m3u8DL-RE": "/usr/local/bin/N_m3u8DL-RE",122            "ffmpeg": "/usr/bin/ffmpeg",123            "mp4decrypt": "/usr/local/bin/mp4decrypt"124        }125    }126 127if __name__ == "__main__":128    print("🎥 N_m3u8DL-RE DRM Processor - FastAPI Server")129    print("=" * 50)130    print(f"Stream directory: {STREAM_DIR}")131    print("Server starting on port 7860...")132    print()133    print("Available endpoints:")134    print("  • GET /              - Service information")135    print("  • GET /health        - Health check")136    print("  • GET /files         - List all MKV files")137    print("  • GET /stream/{filename} - Stream/access file directly")138    print()139    140    uvicorn.run(app, host="0.0.0.0", port=7860, log_level="info")141'''142 143# Update requirements.txt with FastAPI dependencies144requirements_updated = '''fastapi==0.115.0145uvicorn[standard]==0.30.6146python-multipart==0.0.9147'''148 149# Update Dockerfile to install FastAPI requirements150dockerfile_with_fastapi = '''# Optimized Dockerfile for N_m3u8DL-RE with FastAPI file server151FROM mcr.microsoft.com/dotnet/runtime:8.0-bookworm-slim152 153# Set environment variables154ENV DEBIAN_FRONTEND=noninteractive \\155    TZ=UTC \\156    DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1157 158# Create user as required by Hugging Face Spaces  159RUN useradd -m -u 1000 user160 161# Install system dependencies in a single layer162RUN apt-get update && apt-get install -y --no-install-recommends \\163    wget \\164    curl \\165    unzip \\166    ca-certificates \\167    ffmpeg \\168    python3 \\169    python3-pip \\170    && rm -rf /var/lib/apt/lists/* \\171    && apt-get clean172 173# Download and install Bento4 tools (mp4decrypt, mp4info)174RUN cd /tmp \\175    && wget -q "https://www.bok.net/Bento4/binaries/Bento4-SDK-1-6-0-641.x86_64-unknown-linux.zip" \\176    && unzip -j "Bento4-SDK-1-6-0-641.x86_64-unknown-linux.zip" \\177       'Bento4-SDK-1-6-0-641.x86_64-unknown-linux/bin/mp4decrypt' \\178       'Bento4-SDK-1-6-0-641.x86_64-unknown-linux/bin/mp4info' \\179       -d /usr/local/bin/ \\180    && chmod +x /usr/local/bin/mp4decrypt /usr/local/bin/mp4info \\181    && rm -f "Bento4-SDK-1-6-0-641.x86_64-unknown-linux.zip" \\182    && cd /183 184# Download and install N_m3u8DL-RE185RUN cd /tmp \\186    && wget -q "https://github.com/nilaoda/N_m3u8DL-RE/releases/download/v0.3.0-beta/N_m3u8DL-RE_v0.3.0-beta_linux-x64_20241203.tar.gz" \\187    && tar -xzf "N_m3u8DL-RE_v0.3.0-beta_linux-x64_20241203.tar.gz" \\188    && mv N_m3u8DL-RE /usr/local/bin/N_m3u8DL-RE \\189    && chmod +x /usr/local/bin/N_m3u8DL-RE \\190    && rm -f "N_m3u8DL-RE_v0.3.0-beta_linux-x64_20241203.tar.gz" \\191    && cd /192 193# Set working directory194WORKDIR /app195 196# Copy requirements and install Python dependencies197COPY requirements.txt .198RUN pip3 install --no-cache-dir -r requirements.txt199 200# Create directory structure for organized downloads201RUN mkdir -p stream \\202    && chown -R user:user /app203 204# Copy application files205COPY --chown=user app.py .206 207# Switch to non-root user208USER user209 210# Set user environment variables211ENV HOME=/home/user \\212    PATH=/home/user/.local/bin:$PATH213 214# Expose port for FastAPI server215EXPOSE 7860216 217# Start FastAPI server218CMD ["python3", "/app/app.py"]219'''220 221# Create an updated README222readme_updated = '''---223title: N_m3u8DL-RE DRM Processor224emoji: 📺225colorFrom: blue226colorTo: red227sdk: docker228app_port: 7860229pinned: false230---231 232# N_m3u8DL-RE DRM Content Processor with File Server233 234This Docker space provides N_m3u8DL-RE with all necessary dependencies for processing DRM-protected content and serving processed MKV files via HTTP to clients like Stremio.235 236## Features237 238- **N_m3u8DL-RE v0.3.0-beta**: Cross-platform DASH/HLS/MSS downloader239- **FFmpeg**: Complete multimedia framework240- **mp4decrypt (Bento4)**: DRM decryption utility241- **FastAPI Server**: HTTP server for streaming/downloading processed files242- **Direct URL Access**: Each processed file gets a direct HTTP URL243 244## API Endpoints245 246### Service Information247- `GET /` - Service information and available endpoints248- `GET /health` - Health check and tool status249- `GET /info` - System and directory information250 251### File Access252- `GET /files` - List all available MKV files with URLs253- `GET /stream/{filename}` - Direct access to MKV file (streamable)254 255## Direct URL Format256 257After processing a video with N_m3u8DL-RE, the file will be accessible at:258 259```260https://{your-username}-{space-name}.hf.space/stream/{filename}.mkv261```262 263For example, if your file is named `clip_13141002.mkv`, the URL would be:264```265https://your-username-your-space.hf.space/stream/clip_13141002.mkv266```267 268## Usage269 270### 1. Process DRM Content271 272Access the terminal/console and run:273 274```bash275cd /app/stream276 277N_m3u8DL-RE "https://your-stream-url.mpd" \\278  --save-name "clip_13141002" \\279  --select-video best \\280  --select-audio all \\281  --select-subtitle all \\282  -mt -M format=mkv \\283  --log-level Debug \\284  --key YOUR_DECRYPTION_KEY285```286 287### 2. Access Processed Files288 289Once processing completes:290 2911. **View all files**: Visit `https://your-space.hf.space/files`2922. **Stream directly**: Use `https://your-space.hf.space/stream/clip_13141002.mkv`293 294### 3. Use in Stremio295 296Point your Stremio addon to the direct stream URL:297```298https://your-space.hf.space/stream/{filename}.mkv299```300 301## File Storage302 303All processed files are stored in `/app/stream/` and are automatically served via the FastAPI server with proper CORS headers for client access.304 305## Notes306 307- Files are served with `Accept-Ranges: bytes` header for seeking support308- CORS is enabled for all origins (suitable for Stremio clients)309- The server runs on port 7860 (standard for Hugging Face Spaces)310- Terminal access is available for running N_m3u8DL-RE commands311'''312 313# Save all updated files314with open('Dockerfile', 'w') as f:315    f.write(dockerfile_with_fastapi)316    317with open('app.py', 'w') as f:318    f.write(fastapi_app_content)319    320with open('requirements.txt', 'w') as f:321    f.write(requirements_updated)322    323with open('README.md', 'w') as f:324    f.write(readme_updated)325 326print("✅ Updated files with FastAPI server for serving MKV files!")327print()328print("📁 Files updated:")329print("   • Dockerfile - Added Python and FastAPI dependencies")330print("   • app.py - FastAPI server with file streaming endpoints")331print("   • requirements.txt - FastAPI and uvicorn dependencies")332print("   • README.md - Updated with URL format and API documentation")333print()334print("🌐 Direct URL Format:")335print("   https://{username}-{spacename}.hf.space/stream/{filename}.mkv")336print()337print("📋 Example for your command:")338print("   After processing: clip_13141002.mkv")339print("   Direct URL: https://your-space.hf.space/stream/clip_13141002.mkv")340print()341print("🎯 API Endpoints:")342print("   • GET /files - List all available files")343print("   • GET /stream/{filename} - Stream/access file directly")344