Download main_captcha.py from Ourking/DM: direct link, hf CLI and curl.
- Browser
- Download file 12 kB
-
https://huggingface.co/spaces/Ourking/DM/resolve/main/main_captcha.py
- Command line
-
hf download hf://spaces/Ourking/DM/main_captcha.py
-
curl -L -o main_captcha.py https://huggingface.co/spaces/Ourking/DM/resolve/main/main_captcha.py
12 kB
| import requests | |
| import json | |
| import cv2 | |
| import numpy as np | |
| import threading | |
| import time | |
| import hashlib | |
| import os | |
| from datetime import datetime | |
| from concurrent.futures import ThreadPoolExecutor, as_completed | |
| # ========== ① 唯一域名修改 ========== | |
| WORKER_DOMAIN = "https://ourking-tb.hf.space/" | |
| # ========== ② 严格对齐你挂载路径 ========== | |
| BASE_DATA = "/data" | |
| RESULT_FILE = os.path.join(BASE_DATA, "success_results.txt") | |
| JSON_RESULT_DIR = os.path.join(BASE_DATA, "results") | |
| THREADS_NUM = 8 | |
| TIMEOUT = 14 | |
| MIN_AREA = 200 | |
| MAX_AREA = 8000 | |
| DISTANCE_THRESHOLD = 150 | |
| SIFT_RATIO = 0.8 | |
| TDC_DATA_CHECK_INTERVAL = 5 | |
| TDC_GET_MAX_RETRY = 10 | |
| PROXY_API_URL = "https://service.ipzan.com/core-extract?num=1&no=20240218734684069784&minute=1&format=json&repeat=1&protocol=1&pool=quality&mode=auth&secret=dm08sn9s632kon8" | |
| PROXY_TYPE = "http" | |
| TARGET_SUBMIT_URL = "https://ca.turing.captcha.qcloud.com/cap_union_new_verify" | |
| SUCCESS_TARGET = 2 | |
| MAX_ATTEMPTS = 5 | |
| THREAD_MARKS = ["①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧"] | |
| class BalancedCaptchaSolver: | |
| def __init__(self): | |
| self.success_count = 0 | |
| self.success_lock = threading.Lock() # 成功计数器锁 | |
| self.stop_event = threading.Event() # 全局停止信号 | |
| self.result = None | |
| # 初始化SIFT和FLANN | |
| self.sift = cv2.SIFT_create(nfeatures=500) | |
| index_params = dict(algorithm=1, trees=5) | |
| search_params = dict(checks=50) | |
| self.flann = cv2.FlannBasedMatcher(index_params, search_params) | |
| # Worker URL | |
| self.worker_base_url = WORKER_DOMAIN.strip().rstrip('/') | |
| self.worker_init_url = f"{self.worker_base_url}/do" | |
| self.worker_get_url = f"{self.worker_base_url}/get" | |
| # 获取代理 | |
| self.proxy_config = self._get_proxy() | |
| if self.proxy_config: | |
| proxy_info = self.proxy_config['http'].split('@')[-1] | |
| print(f"✅ 代理已加载: {proxy_info}") | |
| # 初始化结果文件 | |
| self.init_file() | |
| def init_file(self): | |
| os.makedirs(os.path.dirname(RESULT_FILE), exist_ok=True) | |
| os.makedirs(JSON_RESULT_DIR, exist_ok=True) | |
| with open(RESULT_FILE, "w", encoding="utf-8") as f: | |
| f.write(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") | |
| def _get_proxy(self): | |
| try: | |
| resp = requests.get(PROXY_API_URL, timeout=TIMEOUT) | |
| resp_data = resp.json() | |
| if resp_data.get("code") != 0 or not resp_data.get("data") or not resp_data["data"].get("list"): | |
| return None | |
| proxy_info = resp_data["data"]["list"][0] | |
| required = ["ip", "port", "account", "password"] | |
| for k in required: | |
| if k not in proxy_info and k.upper() in proxy_info: | |
| proxy_info[k] = proxy_info[k.upper()] | |
| if k not in proxy_info: | |
| return None | |
| proxy_auth = f"{proxy_info['account']}:{proxy_info['password']}" | |
| proxy_url = f"{PROXY_TYPE}://{proxy_auth}@{proxy_info['ip']}:{proxy_info['port']}" | |
| return {"http": proxy_url, "https": proxy_url} | |
| except: | |
| return None | |
| def get_session(self): | |
| session = requests.Session() | |
| session.headers.update({ | |
| "User-Agent": "Mozilla/5.0 (Linux; Android 10; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36" | |
| }) | |
| return session | |
| def decode_img(self, content): | |
| return cv2.imdecode(np.frombuffer(content, np.uint8), cv2.IMREAD_COLOR) | |
| def fetch(self, session, thread_mark): | |
| if self.stop_event.is_set(): | |
| return None, None, None, None, None | |
| try: | |
| resp = session.get(self.worker_init_url, timeout=TIMEOUT) | |
| worker_data = resp.json() | |
| required = ["sess", "img_url", "sprite_url", "prefix", "md5"] | |
| if not all(k in worker_data for k in required): | |
| return None, None, None, None, None | |
| bg_resp = session.get(worker_data["img_url"], timeout=TIMEOUT) | |
| sprite_resp = session.get(worker_data["sprite_url"], timeout=TIMEOUT) | |
| bg = self.decode_img(bg_resp.content) | |
| sprite = self.decode_img(sprite_resp.content) | |
| print(f"{thread_mark} MD5: {worker_data['md5']}") | |
| return worker_data["sess"], bg, sprite, worker_data["prefix"], worker_data["md5"] | |
| except: | |
| return None, None, None, None, None | |
| def detect_symbols(self, img): | |
| hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) | |
| mask = cv2.inRange(hsv, (0, 0, 0), (180, 255, 40)) | |
| mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((2, 2), np.uint8), iterations=1) | |
| mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((4, 4), np.uint8), iterations=1) | |
| contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
| symbols = [] | |
| for cnt in contours: | |
| area = cv2.contourArea(cnt) | |
| if MIN_AREA < area < MAX_AREA: | |
| x, y, w, h = cv2.boundingRect(cnt) | |
| symbols.append((x, y, w, h)) | |
| return sorted(symbols, key=lambda s: s[0]) | |
| def match_sift(self, template, target): | |
| kp1, des1 = self.sift.detectAndCompute(template, None) | |
| kp2, des2 = self.sift.detectAndCompute(target, None) | |
| if des1 is None or des2 is None or len(kp1) < 3 or len(kp2) < 3: | |
| return None | |
| matches = self.flann.knnMatch(des1, des2, k=2) | |
| good = [m for m, n in matches if m.distance < SIFT_RATIO * n.distance] | |
| if len(good) < 3: | |
| return None | |
| src_pts = np.float32([kp1[m.queryIdx].pt for m in good]).reshape(-1, 1, 2) | |
| dst_pts = np.float32([kp2[m.trainIdx].pt for m in good]).reshape(-1, 1, 2) | |
| M, _ = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) | |
| if M is not None: | |
| h, w = template.shape | |
| pts = np.float32([[w/2, h/2]]).reshape(-1, 1, 2) | |
| dst = cv2.perspectiveTransform(pts, M) | |
| return (int(dst[0][0][0]), int(dst[0][0][1])) | |
| return None | |
| def solve(self, bg, sprite): | |
| symbols = self.detect_symbols(bg) | |
| if not symbols: | |
| return None | |
| target_gray = cv2.cvtColor(bg, cv2.COLOR_BGR2GRAY) | |
| template_gray = cv2.cvtColor(sprite, cv2.COLOR_BGR2GRAY) | |
| h, w = template_gray.shape | |
| part_w = w // 3 | |
| templates = [template_gray[:, i*part_w:(i+1)*part_w] for i in range(3)] | |
| centers = [] | |
| for tpl in templates: | |
| pos = self.match_sift(tpl, target_gray) | |
| if pos: | |
| centers.append(pos) | |
| else: | |
| if len(centers) < len(symbols): | |
| x, y, w, h = symbols[len(centers)] | |
| centers.append((x + w//2, y + h//2)) | |
| else: | |
| centers.append((0, 0)) | |
| matched = [] | |
| for cx, cy in centers: | |
| min_dist = float('inf') | |
| best_sym = None | |
| for sym in symbols: | |
| x, y, w, h = sym | |
| dist = (cx - (x + w//2))**2 + (cy - (y + h//2))**2 | |
| if dist < min_dist: | |
| min_dist = dist | |
| best_sym = sym | |
| if best_sym: | |
| matched.append(best_sym) | |
| if len(matched) != 3: | |
| return None | |
| return json.dumps([{"elem_id":i+1,"type":"DynAnswerType_POS","data":f"{x+w//2},{y+h//2}"} for i,(x,y,w,h) in enumerate(matched)]) | |
| def get_tdc_data(self, session, md5, thread_mark): | |
| if self.stop_event.is_set(): | |
| return None, None, 0, None | |
| for attempt in range(1, TDC_GET_MAX_RETRY + 1): | |
| if self.stop_event.is_set(): | |
| return None, None, 0, None | |
| time.sleep(TDC_DATA_CHECK_INTERVAL) | |
| try: | |
| # 严格用你挂载的数据集路径 | |
| file_path = os.path.join(JSON_RESULT_DIR, f"{md5}.json") | |
| with open(file_path, "r", encoding="utf-8") as ef: | |
| resp = ef.read() | |
| resp_data = json.loads(resp) | |
| if "collect" in resp_data and "eks" in resp_data and resp_data["collect"] and resp_data["eks"]: | |
| print(f"{thread_mark} ✅ 第{attempt}次轮询成功获取数据") | |
| return resp_data["collect"], resp_data["eks"], attempt, resp_data | |
| except Exception: | |
| continue | |
| return None, None, 0, None | |
| def generate_tdc_pow(self, nonce: str, target: str, timeout: int = 30000) -> dict: | |
| start_time = time.time() | |
| timeout_seconds = timeout / 1000.0 | |
| ans = 0 | |
| target_length = len(target) | |
| while True: | |
| hash_input = f"{nonce}{ans}".encode("utf-8") | |
| current_md5 = hashlib.md5(hash_input).hexdigest() | |
| if current_md5[:target_length] == target or (time.time() - start_time) > timeout_seconds: | |
| duration = int((time.time() - start_time) * 1000) | |
| return {"pow_answer": f"{nonce}{ans}", "pow_calc_time": duration} | |
| ans += 1 | |
| def worker(self, thread_mark): | |
| session = self.get_session() | |
| attempt_count = 0 | |
| while not self.stop_event.is_set() and attempt_count < MAX_ATTEMPTS: | |
| attempt_count += 1 | |
| sess, bg, sprite, prefix, md5 = self.fetch(session, thread_mark) | |
| if not all([sess, bg is not None, sprite is not None, prefix, md5]): | |
| continue | |
| answer = self.solve(bg, sprite) | |
| if not answer: | |
| continue | |
| collect, eks, success_attempt, resp_data = self.get_tdc_data(session, md5, thread_mark) | |
| if not all([collect, eks]): | |
| continue | |
| pow_result = self.generate_tdc_pow(nonce=prefix, target=md5) | |
| pow_answer = pow_result["pow_answer"] | |
| pow_calc_time = pow_result["pow_calc_time"] | |
| try: | |
| if self.stop_event.is_set(): | |
| break | |
| tlg = len(collect) | |
| post_data = f"collect={collect}&tlg={tlg}&eks={eks}&sess={sess}&ans={answer}&pow_answer={pow_answer}&pow_calc_time={pow_calc_time}" | |
| resp = session.post(TARGET_SUBMIT_URL, data=post_data, timeout=TIMEOUT, proxies=self.proxy_config) | |
| res = json.loads(resp.text) | |
| print(res) | |
| if res.get("errorCode") == "0": | |
| with self.success_lock: | |
| self.success_count += 1 | |
| current_success = self.success_count | |
| print(f"\n{thread_mark} 🎉 成功收集第 {current_success} 个") | |
| with open(RESULT_FILE, "a", encoding="utf-8") as f: | |
| f.write(f"\n{json.dumps(res, ensure_ascii=False)}") | |
| if self.success_count >= 1: | |
| print("✅ 达到目标!本地执行清理.py 代替青龙通知") | |
| try: | |
| import subprocess | |
| # 成功达标 → 直接本地跑清理脚本 = 你要的清理 | |
| subprocess.run(["python3", "clean.py"]) | |
| print("✅ 清理.py 执行完成") | |
| except Exception as e: | |
| print(f"❌ 执行清理失败: {e}") | |
| self.stop_event.set() | |
| break | |
| except: | |
| continue | |
| def run(self): | |
| start_time = time.time() | |
| with ThreadPoolExecutor(max_workers=THREADS_NUM) as executor: | |
| futures = [executor.submit(self.worker, THREAD_MARKS[i]) for i in range(THREADS_NUM)] | |
| total_time = time.time() - start_time | |
| print(f"\n总耗时:{total_time:.2f}s | 成功:{self.success_count}/{SUCCESS_TARGET}") | |
| if __name__ == "__main__": | |
| solver = BalancedCaptchaSolver() | |
| solver.run() | |