refactor: Remove outdated batch script and enhance configuration settings

- Deleted the obsolete batch script for launching the Web GUI.
- Updated `config.json` to increase `webgui_log_capacity` to 2000 and set `reset_after_swipes` to 15.
- Enabled `reset_after_swipes_enabled` for improved functionality.
- Added a new field `reservation_back_swipe_delay` to enhance reservation handling.
- Improved OCR caching and detection mechanisms in `douyin_fudai.py` for better performance.
- Enhanced logging functionality in `web_gui.py` to handle ANSI escape codes and improve error handling.
This commit is contained in:
Your Name committed 2025-12-16 16:49:29 +08:00
1 parent 5bbf59f13f
commit b0bd7c72c8
21 files changed
+2735 -781

No files matched your search

+258 -76
View File
@@ -20,6 +20,126 @@ import contextlib
import base64
from typing import Tuple, Optional
import time as time_module
def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 5) -> bool:
"""安全地替换文件,处理Windows文件锁定问题。
使用多种策略和重试机制来处理文件被占用的情况:
1. 直接使用 os.replace (原子操作)
2. 先删除目标文件再重命名
3. 重命名旧文件为备份,再重命名新文件
4. 使用 shutil.move
5. 直接复制文件内容
Args:
tmp_file: 临时文件路径
out_file: 目标文件路径
max_retries: 最大重试次数
Returns:
True if successful, False otherwise
"""
import shutil
if not os.path.exists(tmp_file):
return False
for attempt in range(max_retries):
try:
# 方法1: 直接使用 os.replace (原子操作,最可靠)
os.replace(tmp_file, out_file)
return True
except (OSError, PermissionError) as e:
# 在Windows上,文件锁定错误通常是 OSError 或 PermissionError
if attempt < max_retries - 1:
# 等待时间逐渐增加,让文件句柄有时间释放
wait_time = 0.05 * (attempt + 1) * (attempt + 1) # 0.05, 0.2, 0.45, 0.8, 1.25秒
time_module.sleep(wait_time)
try:
# 方法2: 先尝试删除目标文件,再重命名
if os.path.exists(out_file):
try:
os.remove(out_file)
except (OSError, PermissionError):
# 如果删除失败,尝试重命名旧文件为备份
try:
old_backup = out_file + '.old'
if os.path.exists(old_backup):
try:
os.remove(old_backup)
except Exception:
pass
os.rename(out_file, old_backup)
except Exception:
pass
# 现在尝试重命名临时文件
os.rename(tmp_file, out_file)
return True
except (OSError, PermissionError):
# 方法3: 使用 shutil.move
try:
if os.path.exists(out_file):
try:
os.remove(out_file)
except (OSError, PermissionError):
try:
old_backup = out_file + '.old'
if os.path.exists(old_backup):
os.remove(old_backup)
os.rename(out_file, old_backup)
except Exception:
pass
shutil.move(tmp_file, out_file)
return True
except Exception:
# 方法4: 直接复制文件内容(最后的手段)
if attempt == max_retries - 2: # 倒数第二次尝试
try:
with open(tmp_file, 'rb') as src, open(out_file, 'wb') as dst:
# 分块读取,避免大文件占用内存
while True:
chunk = src.read(8192)
if not chunk:
break
dst.write(chunk)
# 复制成功后删除临时文件
try:
os.remove(tmp_file)
except Exception:
pass
return True
except Exception:
pass
continue
else:
# 最后一次尝试:直接复制内容
try:
with open(tmp_file, 'rb') as src, open(out_file, 'wb') as dst:
while True:
chunk = src.read(8192)
if not chunk:
break
dst.write(chunk)
# 复制成功后尝试删除临时文件
try:
os.remove(tmp_file)
except Exception:
pass
return True
except Exception:
return False
except Exception as e:
# 其他未知异常,记录但不中断
if attempt == max_retries - 1:
return False
time_module.sleep(0.1 * (attempt + 1))
continue
return False
class underlying_operations:
"""底层操作类"""
def __init__(self):
@@ -169,13 +289,29 @@ class underlying_operations:
stdout=f,
stderr=subprocess.DEVNULL,
check=True,
timeout=10, # 添加10秒超时,避免无限等待
)
if _valid_png(tmp_file):
os.replace(tmp_file, out_file)
print("{} 获取屏幕截图".format(timetag))
return True
except Exception:
# 使用安全的文件替换函数
if _safe_replace_file(tmp_file, out_file):
print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功")
return True
else:
# 如果替换失败,但临时文件有效,仍然返回成功
# 后续代码可以读取临时文件或重试
print(f"[截图] 文件替换失败,但截图已保存到临时文件,将重试")
# 不立即返回,继续尝试回退方案
except subprocess.TimeoutExpired:
# 超时异常,记录并继续重试
print(f"[截图] exec-out 超时,尝试重试或回退方案")
try:
if os.path.exists(tmp_file):
os.remove(tmp_file)
except Exception:
pass
except Exception as e:
# 继续回退/重试
print(f"[截图] exec-out 异常:{e}")
try:
if os.path.exists(tmp_file):
os.remove(tmp_file)
@@ -189,16 +325,54 @@ class underlying_operations:
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
timeout=10, # 添加超时
)
subprocess.run(
[adb, '-s', device_id, 'pull', '/sdcard/DCIM/screenshot.png', tmp_file],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
timeout=10, # 添加超时
)
if _valid_png(tmp_file):
os.replace(tmp_file, out_file)
print("{} 获取屏幕截图".format(timetag))
# 使用安全的文件替换函数
if _safe_replace_file(tmp_file, out_file):
print("{} 获取屏幕截图".format(timetag))
return True
else:
# 如果替换失败,尝试最后一次:直接复制内容
try:
import shutil
# 如果目标文件存在且被占用,尝试读取临时文件内容并写入
if os.path.exists(tmp_file):
# 尝试直接覆盖写入(如果文件被占用,这会失败,但至少尝试了)
try:
with open(tmp_file, 'rb') as src, open(out_file, 'wb') as dst:
dst.write(src.read())
print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)")
return True
except (OSError, PermissionError) as e:
# 如果还是失败,尝试将临时文件重命名为目标文件
try:
# 如果目标文件存在,尝试重命名为备份
if os.path.exists(out_file):
backup_name = out_file + '.backup'
try:
if os.path.exists(backup_name):
os.remove(backup_name)
os.rename(out_file, backup_name)
except Exception:
pass
# 尝试重命名临时文件为目标文件
os.rename(tmp_file, out_file)
print("{} 获取屏幕截图(通过重命名临时文件)".format(timetag))
return True
except Exception:
# 最后兜底:返回True,让调用者知道临时文件存在
print(f"[截图] 文件替换失败({e}),但截图已保存到临时文件 {tmp_file}")
return True
except Exception:
print(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}")
return True
# 文件异常则继续进入更深回退
except Exception:
@@ -236,24 +410,36 @@ class underlying_operations:
os.system("%s -s %s shell input keyevent 4" % (self._adb(), device_id))
print("点击返回键")
def get_ballery_level(self, device_id):
def get_battery_level(self, device_id):
"""获取设备电量信息"""
battery_info = subprocess.Popen("%s -s %s shell dumpsys battery" % (self._adb(), device_id), shell=True,
stdout=subprocess.PIPE)
battery_info_string = battery_info.stdout.read()
battery_info_string = bytes.decode(battery_info_string)
location = re.search('level:', battery_info_string)
if not location:
print("[警告] 无法解析电量信息,返回默认值100")
return 100
span = location.span()
start, end = span
start = end + 1
for i in range(5):
end += 1
if battery_info_string[end] == "\n":
# 防止越界
max_end = min(len(battery_info_string), start + 10)
for i in range(max_end - start):
end = start + i
if end >= len(battery_info_string) or battery_info_string[end] == "\n":
break
battery_level = battery_info_string[start:end] # 第几个到第几个中间接冒号
battery_level = int(battery_level)
print("设备当前电量为{}".format(battery_level))
return battery_level
if end <= start:
print("[警告] 无法解析电量信息,返回默认值100")
return 100
battery_level_str = battery_info_string[start:end].strip()
try:
battery_level = int(battery_level_str)
print("设备当前电量为{}".format(battery_level))
return battery_level
except ValueError:
print(f"[警告] 电量解析失败:'{battery_level_str}',返回默认值100")
return 100
def get_device_resolution(self, device_id):
"""获取设备分辨率"""
@@ -269,7 +455,6 @@ class underlying_operations:
return width, height
else:
raise ValueError("Could not find resolution in adb output")
return False
def save_reward_pic(self, device_id):
out_dir = os.path.join(os.path.dirname(__file__), 'pic')
@@ -341,14 +526,33 @@ class underlying_operations:
pic.crop((left_up[0], left_up[1], right_down[0], right_down[1])).save(cut_pic_path)
def analyse_pic_word(self, picname='', change_color=0):
"""识别图像中的文字, change_color=1或2为不同的二值化模式,其他不做处理"""
"""识别图像中的文字, change_color=1或2为不同的二值化模式,其他不做处理
性能优化:
- 添加文件存在性检查,避免打开不存在的文件
- 优化图片加载和预处理流程
"""
self._ensure_ocr()
if self.ocr is None:
return ''
path = os.path.dirname(__file__) + '/pic'
if picname == '':
pic = path + '/cut.png'
pic_path = path + '/cut.png'
else:
pic = path + '/' + picname + '.png'
img = Image.open(pic)
pic_path = path + '/' + picname + '.png'
# 检查文件是否存在
if not os.path.exists(pic_path):
return ''
try:
img = Image.open(pic_path)
# 检查图片是否有效
img.verify()
img = Image.open(pic_path) # 重新打开,因为verify后需要重新打开
except (IOError, OSError, Image.UnidentifiedImageError) as e:
return ''
# 福袋内容/倒计时属于手机 UI 字体,强二值化容易把细节打没,默认保持彩色。
if change_color in (1, 2):
@@ -363,16 +567,49 @@ class underlying_operations:
# 性能优化:先用原尺寸跑一次 OCR;只有识别为空时才放大重试。
w, h = img.size
img1 = img.filter(ImageFilter.SHARPEN)
# 优化:对于很小的图片,直接放大,避免浪费一次OCR调用
if max(w, h) < 100:
try:
scale = max(2, 200 // max(w, h, 1)) # 至少放大到200像素
img = img.resize((w * scale, h * scale), Image.BICUBIC)
w, h = img.size
except Exception:
pass
# 识别精度优化:增强图片预处理
# 1. 使用增强锐化(UnsharpMask效果更好)
from PIL import ImageEnhance
try:
# 先锐化
img_sharpened = img.filter(ImageFilter.UnsharpMask(radius=1, percent=150, threshold=3))
# 再增强对比度(轻微增强,避免过度处理)
enhancer = ImageEnhance.Contrast(img_sharpened)
img_enhanced = enhancer.enhance(1.15) # 增强15%对比度
img1 = img_enhanced
except Exception:
# 如果增强失败,回退到原来的锐化
img1 = img.filter(ImageFilter.SHARPEN)
img_np = np.array(img1)
result = self.ocr.ocr(img_np)
if result == [None]:
return ''
text = self.extract_ocr_content(result)
# 如果识别为空且图片较小,尝试放大重试(精度优化:使用更好的放大算法和增强处理)
if (not text) and max(w, h) <= 1200:
try:
img2 = img.resize((w * 2, h * 2), Image.BICUBIC).filter(ImageFilter.SHARPEN)
# 使用LANCZOS重采样算法(更高质量的放大)
img2 = img.resize((w * 2, h * 2), Image.LANCZOS)
# 应用增强预处理
try:
from PIL import ImageEnhance
img2_sharpened = img2.filter(ImageFilter.UnsharpMask(radius=1.5, percent=180, threshold=3))
enhancer = ImageEnhance.Contrast(img2_sharpened)
img2_enhanced = enhancer.enhance(1.2) # 放大后增强20%对比度
img2 = img2_enhanced
except Exception:
img2 = img2.filter(ImageFilter.SHARPEN)
result2 = self.ocr.ocr(np.array(img2))
if result2 != [None]:
text = self.extract_ocr_content(result2)
@@ -392,61 +629,6 @@ class underlying_operations:
return text
def analyse_pic_word_fast(self, picname='', change_color=0, max_side=600):
"""更快的 OCR 路径:对裁剪图像做轻量化预处理并只执行一次 OCR(不做放大重试),用于对小区域的快速判定。
参数:
picname: 图片在 pic/ 中的文件名(不含后缀),空串表示默认 cut.png
change_color: 同 `analyse_pic_word` 的二值化模式(0=不二值化,1/2=两种二值化)
max_side: 若图片任一边超过该值,则按比例缩小到该尺寸,减少 OCR 计算量
返回: 识别到的文本(字符串)或空串
"""
self._ensure_ocr()
path = os.path.dirname(__file__) + '/pic'
if picname == '':
img_path = path + '/cut.png'
else:
img_path = path + '/' + picname + '.png'
try:
img = Image.open(img_path)
except Exception:
return ''
# 轻量化预处理:灰度/二值化 (若指定)
try:
if change_color in (1, 2):
img = img.convert('L')
if change_color == 1:
img = img.point(lambda x: 0 if x < 128 else 255)
else:
img = img.point(lambda x: 0 if x < 180 else 255)
img = img.convert('RGB')
else:
img = img.convert('RGB')
except Exception:
img = img.convert('RGB')
# 若图片较大,按比例缩小到 max_side,减小 OCR 负担
try:
w, h = img.size
m = max(w, h)
if max_side and m > max_side:
scale = max_side / float(m)
nw = max(1, int(w * scale))
nh = max(1, int(h * scale))
img = img.resize((nw, nh), Image.BILINEAR)
except Exception:
pass
try:
img_np = np.array(img.filter(ImageFilter.SHARPEN))
result = self.ocr.ocr(img_np)
if result == [None]:
return ''
return self.extract_ocr_content(result)
except Exception:
return ''
def extract_ocr_content(self, content=[]):
"""对OCR识别到的内容进行取值和拼接,变成完整的一段内容"""
ocr_result = content