Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-opus-4-20250514· AnthropicHugging Face LMArena Human Preference 140K

创建docker 直播源web管理系统 根据输入的直播源地址 扫描和下载 后汇总为test.txt 使用ffmpeg 测试连接的有效性和能否顺利播放…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with DeepSeekdeepseek-v3-0324’s answer.
  1. User

    创建docker 直播源web管理系统 根据输入的直播源地址 扫描和下载 后汇总为test.txt 使用ffmpeg 测试连接的有效性和能否顺利播放 将能播放的地址按照原格式写入tx.txt 无效的写入wx.txt

  2. Claude Assistant

    我来帮您创建一个Docker化的直播源Web管理系统。这个系统将包含以下功能:

    1. Web界面用于输入直播源地址
    2. 扫描和下载直播源
    3. 使用FFmpeg测试连接有效性
    4. 将结果分类保存到不同文件

    首先,让我创建项目结构:

    livestream-manager/
    ├── Dockerfile
    ├── docker-compose.yml
    ├── requirements.txt
    ├── app.py
    ├── templates/
    │   └── index.html
    └── static/
        └── style.css
    

    Dockerfile:

    FROM python:3.9-slim
    
    # 安装FFmpeg和其他依赖
    RUN apt-get update && apt-get install -y \
        ffmpeg \
        curl \
        wget \
        && rm -rf /var/lib/apt/lists/*
    
    WORKDIR /app
    
    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt
    
    COPY . .
    
    EXPOSE 5000
    
    CMD ["python", "app.py"]
    

    docker-compose.yml:

    version: '3.8'
    
    services:
      livestream-manager:
        build: .
        container_name: livestream-manager
        ports:
          - "5000:5000"
        volumes:
          - ./data:/app/data
        environment:
          - FLASK_ENV=production
        restart: unless-stopped
    

    requirements.txt:

    Flask==2.3.2
    requests==2.31.0
    validators==0.20.0
    concurrent-futures==3.1.1
    

    app.py:

    from flask import Flask, render_template, request, jsonify
    import os
    import subprocess
    import requests
    import validators
    import concurrent.futures
    from datetime import datetime
    import threading
    import time
    
    app = Flask(__name__)
    
    # 确保数据目录存在
    DATA_DIR = '/app/data'
    os.makedirs(DATA_DIR, exist_ok=True)
    
    class LivestreamManager:
        def __init__(self):
            self.test_results = []
            self.is_testing = False
            
        def download_m3u(self, url):
            """下载M3U文件"""
            try:
                response = requests.get(url, timeout=10)
                response.raise_for_status()
                return response.text
            except Exception as e:
                print(f"下载失败: {url} - {str(e)}")
                return None
        
        def parse_m3u(self, content):
            """解析M3U内容,提取直播源"""
            streams = []
            lines = content.strip().split('\n')
            
            for i in range(len(lines)):
                line = lines[i].strip()
                if line and not line.startswith('#'):
                    # 检查是否是有效的URL
                    if validators.url(line):
                        # 获取频道名称(如果有)
                        name = "未知频道"
                        if i > 0 and lines[i-1].startswith('#EXTINF:'):
                            name = lines[i-1].split(',')[-1].strip()
                        streams.append({
                            'name': name,
                            'url': line
                        })
            return streams
        
        def test_stream(self, stream):
            """使用FFmpeg测试单个直播源"""
            url = stream['url']
            name = stream['name']
            
            # FFmpeg命令,测试10秒
            cmd = [
                'ffmpeg',
                '-i', url,
                '-t', '10',
                '-f', 'null',
                '-'
            ]
            
            try:
                # 运行FFmpeg命令
                result = subprocess.run(
                    cmd,
                    capture_output=True,
                    text=True,
                    timeout=15
                )
                
                # 检查返回码
                is_valid = result.returncode == 0
                
                return {
                    'name': name,
                    'url': url,
                    'valid': is_valid,
                    'error': result.stderr if not is_valid else None
                }
            except subprocess.TimeoutExpired:
                return {
                    'name': name,
                    'url': url,
                    'valid': False,
                    'error': '测试超时'
                }
            except Exception as e:
                return {
                    'name': name,
                    'url': url,
                    'valid': False,
                    'error': str(e)
                }
        
        def save_results(self, results):
            """保存测试结果到文件"""
            valid_streams = []
            invalid_streams = []
            
            for result in results:
                if result['valid']:
                    valid_streams.append(f"{result['name']},{result['url']}\n")
                else:
                    invalid_streams.append(f"{result['name']},{result['url']} # 错误: {result['error']}\n")
            
            # 保存到文件
            with open(os.path.join(DATA_DIR, 'tx.txt'), 'w', encoding='utf-8') as f:
                f.writelines(valid_streams)
            
            with open(os.path.join(DATA_DIR, 'wx.txt'), 'w', encoding='utf-8') as f:
                f.writelines(invalid_streams)
            
            # 保存所有测试结果
            with open(os.path.join(DATA_DIR, 'test.txt'), 'w', encoding='utf-8') as f:
                for result in results:
                    status = "有效" if result['valid'] else "无效"
                    f.write(f"{result['name']},{result['url']},{status}\n")
        
        def process_streams(self, urls):
            """处理直播源列表"""
            self.is_testing = True
            self.test_results = []
            all_streams = []
            
            # 下载和解析所有M3U文件
            for url in urls:
                if url.strip():
                    if url.endswith('.m3u') or url.endswith('.m3u8'):
                        content = self.download_m3u(url)
                        if content:
                            streams = self.parse_m3u(content)
                            all_streams.extend(streams)
                    else:
                        # 直接添加单个流
                        all_streams.append({
                            'name': '直播流',
                            'url': url.strip()
                        })
            
            # 使用线程池并发测试
            with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
                futures = [executor.submit(self.test_stream, stream) for stream in all_streams]
                
                for future in concurrent.futures.as_completed(futures):
                    result = future.result()
                    self.test_results.append(result)
            
            # 保存结果
            self.save_results(self.test_results)
            self.is_testing = False
            
            return self.test_results
    
    manager = LivestreamManager()
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    @app.route('/test_streams', methods=['POST'])
    def test_streams():
        data = request.json
        urls = data.get('urls', '').split('\n')
        
        # 在后台线程中处理
        thread = threading.Thread(target=manager.process_streams, args=(urls,))
        thread.start()
        
        return jsonify({'status': 'started'})
    
    @app.route('/get_status')
    def get_status():
        return jsonify({
            'is_testing': manager.is_testing,
            'results': manager.test_results,
            'total': len(manager.test_results)
        })
    
    @app.route('/download/<filename>')
    def download_file(filename):
        if filename in ['test.txt', 'tx.txt', 'wx.txt']:
            filepath = os.path.join(DATA_DIR, filename)
            if os.path.exists(filepath):
                with open(filepath, 'r', encoding='utf-8') as f:
                    content = f.read()
                return content, 200, {'Content-Type': 'text/plain; charset=utf-8'}
        return "文件不存在", 404
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000, debug=False)
    

    templates/index.html:

    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>直播源管理系统</title>
        <link rel="stylesheet" href="/static/style.css">
    </head>
    <body>
        <div class="container">
            <h1>直播源管理系统</h1>
            
            <div class="input-section">
                <h2>输入直播源地址</h2>
                <textarea id="urls" placeholder="每行输入一个直播源地址或M3U文件URL..."></textarea>
                <button id="testBtn" onclick="testStreams()">开始测试</button>
            </div>
            
            <div class="status-section">
                <h2>测试状态</h2>
                <div id="status">等待开始...</div>
                <div class="progress-bar">
                    <div id="progress" class="progress"></div>
                </div>
            </div>
            
            <div class="results-section">
                <h2>测试结果</h2>
                <div class="stats">
                    <span>总数: <span id="total">0</span></span>
                    <span>有效: <span id="valid">0</span></span>
                    <span>无效: <span id="invalid">0</span></span>
                </div>
                <div id="results"></div>
            </div>
            
            <div class="download-section">
                <h2>下载结果文件</h2>
                <button onclick="downloadFile('test.txt')">下载 test.txt (所有)</button>
                <button onclick="downloadFile('tx.txt')">下载 tx.txt (有效)</button>
                <button onclick="downloadFile('wx.txt')">下载 wx.txt (无效)</button>
            </div>
        </div>
        
        <script>
            let statusInterval;
            
            function testStreams() {
                const urls = document.getElementById('urls').value;
                if (!urls.trim()) {
                    alert('请输入直播源地址');
                    return;
                }
                
                document.getElementById('testBtn').disabled = true;
                document.getElementById('status').textContent = '正在测试...';
                
                fetch('/test_streams', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ urls: urls })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'started') {
                        statusInterval = setInterval(checkStatus, 1000);
                    }
                });
            }
            
            function checkStatus() {
                fetch('/get_status')
                .then(response => response.json())
                .then(data => {
                    updateUI(data);
                    
                    if (!data.is_testing && data.total > 0) {
                        clearInterval(statusInterval);
                        document.getElementById('testBtn').disabled = false;
                        document.getElementById('status').textContent = '测试完成!';
                    }
                });
            }
            
            function updateUI(data) {
                const total = data.total;
                const valid = data.results.filter(r => r.valid).length;
                const invalid = total - valid;
                
                document.getElementById('total').textContent = total;
                document.getElementById('valid').textContent = valid;
                document.getElementById('invalid').textContent = invalid;
                
                // 更新进度条
                if (total > 0) {
                    const progress = (total / data.results.length) * 100;
                    document.getElementById('progress').style.width = progress + '%';
                }
                
                // 更新结果列表
                const resultsDiv = document.getElementById('results');
                resultsDiv.innerHTML = '';
                
                data.results.forEach(result => {
                    const div = document.createElement('div');
                    div.className = result.valid ? 'result valid' : 'result invalid';
                    div.innerHTML = `
                        <span class="name">${result.name}</span>
                        <span class="url">${result.url}</span>
                        <span class="status">${result.valid ? '✓' : '✗'}</span>
                    `;
                    resultsDiv.appendChild(div);
                });
            }
            
            function downloadFile(filename) {
                window.open('/download/' + filename, '_blank');
            }
        </script>
    </body>
    </html>
    

    static/style.css:

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    
    body {
        font-family: Arial, sans-serif;
        background-color: #f5f5f5;
        color: #333;
    }
    
    .container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
    }
    
    h1 {
        text-align: center;
        color: #2c3e50;
        margin-bottom: 30px;
    }
    
    h2 {
        color: #34495e;
        margin-bottom: 15px;
    }
    
    .input-section {
        background: white;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    #urls {
        width: 100%;
        height: 150px;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-family: monospace;
        resize: vertical;
    }
    
    #testBtn {
        margin-top: 10px;
        padding: 10px 30px;
        background-color: #3498db;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
    }
    
    #testBtn:hover {
        background-color: #2980b9;
    }
    
    #testBtn:disabled {
        background-color: #95a5a6;
        cursor: not-allowed;
    }
    
    .status-section {
        background: white;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .progress-bar {
        width: 100%;
        height: 20px;
        background-color: #ecf0f1;
        border-radius: 10px;
        overflow: hidden;
        margin-top: 10px;
    }
    
    .progress {
        height: 100%;
        background-color: #3498db;
        width: 0%;
        transition: width 0.3s ease;
    }
    
    .results-section {
        background: white;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    
    .stats {
        display: flex;
        gap: 20px;
        margin-bottom: 15px;
        font-size: 18
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.