Files
douyin_guaji-main/operations/screenshot_service_new.py
T
CodexandClaude Opus 4.5 8fe7ff0585 refactor: 根目录核心模块迁移到 douyin/core/ 和 douyin/logging/
将 4 个根目录核心模块迁移到合理位置:
- path_config.py    -> douyin/core/path_config.py
- version.py        -> douyin/core/version.py
- Underlying_Operations.py -> douyin/core/underlying_operations.py
- unified_logger.py -> douyin/logging/unified_logger.py

配套更新所有 import:
- path_config: 41 处 import 改为 douyin.core.path_config
- version: 4 处改为 douyin.core.version
- unified_logger: 5 处改为 douyin.logging.unified_logger
- Underlying_Operations: 14 处改为 douyin.core.underlying_operations

修复 path_config.PROJECT_ROOT 计算(向上 2 级而非当前目录)。

验证:python -m compileall 全项目通过。

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-05-21 00:23:14 +08:00

135 lines
5.0 KiB
Python

"""简化版后台截图服务,避免文件中重复定义导致的 linter 错误。"""
from __future__ import annotations
import os
import threading
import time
from typing import Optional
from datetime import datetime
from douyin.core import path_config
from operations.screenshot_operations import ScreenshotOperations
class ScreenshotService:
"""后台截图服务(简化实现)。"""
_instance: Optional["ScreenshotService"] = None
_lock = threading.Lock()
def __init__(self):
self._running = False
self._thread: Optional[threading.Thread] = None
self._screenshot_ops = ScreenshotOperations()
self._current_device_id: Optional[str] = None
self._last_screenshot_time = time.time() - 10.0
self._screenshot_interval = 3.5
self._cache_valid_duration = 4.0
self._screenshot_path: Optional[str] = None
self._last_success = False
@classmethod
def get_instance(cls) -> "ScreenshotService":
if cls._instance is None:
with cls._lock:
if cls._instance is None:
cls._instance = cls()
assert cls._instance is not None
return cls._instance
def start(self, device_id: str, interval: float = 1.5):
with self._lock:
if self._running and self._current_device_id == device_id:
return
if self._running:
self.stop()
self._current_device_id = device_id
self._screenshot_interval = max(0.5, interval)
self._running = True
try:
self._screenshot_path = path_config.get_screenshot_path()
except Exception:
self._screenshot_path = os.path.join("pic", "screenshot.png")
self._thread = threading.Thread(target=self._screenshot_loop, daemon=True, name="ScreenshotService")
self._thread.start()
self._last_screenshot_time = time.time() - self._cache_valid_duration - 1.0
timetag = datetime.now().strftime("%H:%M:%S")
print(f"[{timetag}] [截图服务] 已启动后台截图服务,设备: {device_id}, 间隔: {interval}秒")
def stop(self):
with self._lock:
if not self._running:
return
self._running = False
if self._thread and self._thread.is_alive():
self._thread.join(timeout=2.0)
timetag = datetime.now().strftime("%H:%M:%S")
print(f"[{timetag}] [截图服务] 已停止后台截图服务")
def _screenshot_loop(self):
while self._running:
try:
if not self._current_device_id:
time.sleep(0.1)
continue
start = time.time()
success = self._screenshot_ops.get_screenshot(self._current_device_id, use_service=False)
elapsed = (time.time() - start) * 1000
timetag = datetime.now().strftime("%H:%M:%S")
if success:
self._last_screenshot_time = time.time()
self._last_success = True
print(f"[{timetag}] [截图服务] 后台截图成功,耗时: {elapsed:.0f}ms")
else:
self._last_success = False
print(f"[{timetag}] [截图服务] 后台截图失败,耗时: {elapsed:.0f}ms")
time.sleep(max(0.5, self._screenshot_interval - elapsed / 1000))
except Exception as e:
print(f"[截图服务] 异常: {e}")
time.sleep(1.0)
def get_screenshot(self, device_id: str, force: bool = False) -> bool:
# 优先使用缓存判断,简化版保留核心逻辑
if self._current_device_id != device_id:
self.start(device_id)
time.sleep(0.1)
now = time.time()
if not force and now - self._last_screenshot_time < self._cache_valid_duration:
if self._screenshot_path and os.path.exists(self._screenshot_path):
try:
if os.path.getsize(self._screenshot_path) >= 1024:
return True
except Exception:
pass
# 回退到直接截图
return self._screenshot_ops.get_screenshot(device_id, use_service=False)
def is_running(self) -> bool:
return self._running
def get_last_screenshot_time(self) -> float:
return self._last_screenshot_time
def get_cache_info(self) -> dict:
return {
"running": self._running,
"device_id": self._current_device_id,
"last_screenshot_time": self._last_screenshot_time,
"interval": self._screenshot_interval,
"cache_valid_duration": self._cache_valid_duration,
"last_success": self._last_success,
}
def get_optimal_workers() -> int:
cpu_count = os.cpu_count() or 4
if cpu_count >= 12:
return 10
if cpu_count >= 8:
return 8
if cpu_count >= 4:
return 6
if cpu_count >= 2:
return 3
return 2