Привет. Говори по русски. У меня есть сервер Flask - from flask import Flask, Response, render_template, request, jsonify
from threading import Condition
import logging
import requests

app = Flask(__name__)
logging.basicConfig(level=logging.INFO)

# Хранилище для подключенных камер
cameras = {}

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

@app.route('/register_camera', methods=['POST'])
def register_camera():
    """Регистрация новой камеры"""
    data = request.json
    camera_id = data.get('camera_id')
    camera_url = data.get('camera_url')
    
    # Заменяем localhost на IP адрес клиента
    if 'localhost' in camera_url:
        client_ip = request.remote_addr
        camera_url = camera_url.replace('localhost', client_ip)
    
    cameras[camera_id] = {'url': camera_url, 'frame': None}
    logging.info(f"Registered camera {camera_id} at {camera_url}")
    return jsonify({'status': 'success'})

@app.route('/stream/<camera_id>')
def stream(camera_id):
    """Получение потока с камеры"""
    def generate():
        while True:
            if camera_id in cameras:
                try:
                    # Получаем кадр от камеры Raspberry Pi
                    response = requests.get(f"{cameras[camera_id]['url']}/frame")
                    if response.status_code == 200:
                        yield (b'--frame\r\n'
                               b'Content-Type: image/jpeg\r\n\r\n' + response.content + b'\r\n')
                except Exception as e:
                    logging.error(f"Error getting frame from camera {camera_id}: {e}")
    
    return Response(generate(),
                   mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/control/<camera_id>/<setting>', methods=['POST'])
def control_camera(camera_id, setting):
    """Управление настройками камеры"""
    if camera_id not in cameras:
        return jsonify({'error': 'Camera not found'}), 404
    
    try:
        # Пересылаем команду управления на камеру
        response = requests.post(
            f"{cameras[camera_id]['url']}/control/{setting}",
            json=request.json
        ) - и скрипт для рассбери которая транслирует на сервер изображение from flask import Flask, Response, jsonify, request
from picamera2 import Picamera2
from picamera2.encoders import JpegEncoder
from picamera2.outputs import FileOutput
import io
import logging
import requests
import time
from threading import Condition, Thread

# Настройка логирования
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Конфигурация
MAIN_SERVER_URL = "http://10.8.0.10:8000"  # Адрес основного сервера
CAMERA_ID = "raspberry_pi_1"  # Уникальный ID для этой камеры
LOCAL_PORT = 5001  # Локальный порт для этой камеры

class StreamingOutput(io.BufferedIOBase):
    def __init__(self):
        self.frame = None
        self.condition = Condition()

    def write(self, buf):
        with self.condition:
            self.frame = buf
            self.condition.notify_all()

app = Flask(__name__)
output = StreamingOutput()
picam2 = Picamera2()
encoder = JpegEncoder()

def init_camera():
    # Создаем конфигурацию для видео стрима
    video_config = picam2.create_video_configuration(
        main={"size": (1920, 1080), "format": "RGB888"},
        encode="main"
    )
    picam2.configure(video_config)
    picam2.start()
    picam2.start_recording(encoder, FileOutput(output))
    logger.info("Camera initialized")

@app.route('/frame')
def serve_frame():
    """Отдает текущий кадр"""
    with output.condition:
        output.condition.wait()
        frame = output.frame
    return Response(frame, mimetype='image/jpeg')

@app.route('/control/<setting>', methods=['POST'])
def control_camera(setting):
    """Управление настройками камеры"""
    try:
        data = request.json
        value = data.get('value')
        logger.info(f"Получен запрос на изменение {setting} на значение {value}")

        if setting == 'hardware_brightness':
            brightness = 0.5 + (float(value) / 100) * 2
            picam2.set_controls({"ExposureValue": brightness})
            logger.info(f"Hardware brightness set to {brightness}")

        elif setting == 'exposure':
            if float(value) <= 50:
                exposure = int(1 + (float(value) * 200))
            else:
                exposure = int(10000 + ((float(value) - 50) * 600))
            picam2.set_controls({"ExposureTime": exposure})
            logger.info(f"Exposure set to {exposure}µs ({value}%)")

        elif setting == 'contrast':
            contrast = -1.0 + (float(value) / 100) * 2
            picam2.set_controls({"Contrast": float(contrast)})
            logger.info(f"Contrast set to {contrast}")

        elif setting == 'saturation':
            saturation = -1.0 + (float(value) / 100) * 2
            picam2.set_controls({"Saturation": float(saturation)})
            logger.info(f"Saturation set to {saturation}")

        elif setting == 'autofocus':
            # Преобразуем строку в булево значение
            enabled = str(value).lower() == 'true'
            if enabled:
                picam2.set_controls({"AfMode": 2})  # 2 = Continuous autofocus
                logger.info("Autofocus enabled")
            else:
                picam2.set_controls({"AfMode": 0})  # 0 = Manual focus
                logger.info("Autofocus disabled")

        elif setting == 'fps':
            fps = float(value)
            picam2.set_controls({"FrameRate": fps})
            logger.info(f"FPS set to {fps}")

        elif setting == 'resolution':
            try:
                width = int(data.get('width', 1920))
                height = int(data.get('height', 1080))
                logger.info(f"Changing resolution to {width}x{height}")

                picam2.stop_recording()
                video_config = picam2.create_video_configuration(
                    main={"size": (width, height), "format": "RGB888"},
                    encode="main"
                )
                picam2.configure(video_config)
                picam2.start()
                picam2.start_recording(encoder, FileOutput(output))
                logger.info(f"Resolution set to {width}x{height}")
            except Exception as e:
                logger.error(f"Failed to set resolution: {e}")
                try:
                    picam2.start_recording(encoder, FileOutput(output))
                except:
                    pass
                return jsonify({'error': str(e)}), 500

        return jsonify({'status': 'success'})
    except Exception as e:
        logger.error(f"Error setting {setting}: {e}")
        return jsonify({'error': str(e)}), 500

def register_with_main_server():
    """Регистрация камеры на основном сервере"""
    while True:
        try:
            local_url = f"http://localhost:{LOCAL_PORT}"
            response = requests.post(f"{MAIN_SERVER_URL}/register_camera", json={
                'camera_id': CAMERA_ID,
                'camera_url': local_url
            })
            if response.status_code == 200:
                logger.info("Successfully registered with main server")
                break
            else:
                logger.error("Failed to register with main server")
        except Exception as e:
            logger.error(f"Error registering with main server: {e}")
        time.sleep(5)  

if __name__ == '__main__':
    init_camera()
    Thread(target=register_with_main_server, daemon=True).start()
    app.run(host='0.0.0.0', port=LOCAL_PORT, threaded=True)

        return jsonify(response.json())
    except Exception as e:
        logging.error(f"Error controlling camera {camera_id}: {e}")
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000, threaded=True)
- я хочу чтобы моя рассбери могла определять какую игральную карту она сейчас видит, как мне обучить модель tenser flow и внедрить сюда? Распиши максимально подробный алгоритм