#!/usr/bin/env python3 """ Local camera CORS proxy for OCR app. Run this script on the computer that accesses the OCR app (same network as camera). Then paste http://localhost:8108/snapshot.cgi into the IP Camera URL field. """ import urllib.request, base64 from http.server import HTTPServer, BaseHTTPRequestHandler CAMERA_IP = '192.168.1.108' # camera IP (port 80 for HTTP snapshot/stream) CAMERA_USER = 'admin' CAMERA_PASS = 'admin123' PORT = 8108 _AUTH = base64.b64encode(f'{CAMERA_USER}:{CAMERA_PASS}'.encode()).decode() class Proxy(BaseHTTPRequestHandler): def _cors(self): self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Access-Control-Allow-Private-Network', 'true') self.send_header('Access-Control-Allow-Methods', 'GET, OPTIONS') self.send_header('Access-Control-Allow-Headers', '*') def do_OPTIONS(self): self.send_response(204) self._cors() self.end_headers() def do_GET(self): try: url = f'http://{CAMERA_IP}{self.path or "/"}' req = urllib.request.Request(url, headers={ 'User-Agent': 'Mozilla/5.0', 'Authorization': f'Basic {_AUTH}', }) r = urllib.request.urlopen(req, timeout=6) ct = r.headers.get('Content-Type', 'image/jpeg') if 'multipart' in ct: # MJPEG stream — extract first complete JPEG frame raw = b'' while len(raw) < 600_000: chunk = r.read(65536) if not chunk: break raw += chunk s = raw.find(b'\xff\xd8') if s == -1: continue e = raw.find(b'\xff\xd9', s + 2) if e == -1: continue data = raw[s:e + 2] ct = 'image/jpeg' self._send(ct, data) return self.send_response(502); self._cors(); self.end_headers() else: data = r.read(2_000_000) self._send(ct, data) except Exception as ex: self.send_response(502) self._cors() self.end_headers() print(f' Error: {ex}') def _send(self, ct, data): self.send_response(200) self._cors() self.send_header('Content-Type', ct) self.send_header('Content-Length', str(len(data))) self.end_headers() self.wfile.write(data) def log_message(self, fmt, *args): print(f' {self.address_string()} — {fmt % args}') print(f'\n Camera CORS proxy started') print(f' Camera : http://{CAMERA_IP} (user: {CAMERA_USER})') print(f' Proxy : http://localhost:{PORT}') print(f'\n Paste into OCR app IP Camera field:') print(f' http://localhost:{PORT}/snapshot.cgi') print(f' or try:') print(f' http://localhost:{PORT}/video\n') HTTPServer(('0.0.0.0', PORT), Proxy).serve_forever()