Răsfoiți Sursa

Merge pull request #1848 from xylolit-mu/pr

对弈竞猜更新
huangrunheng 1 lună în urmă
părinte
comite
d1c1b85a9f

+ 3 - 0
.gitignore

@@ -272,3 +272,6 @@ console.bat
 .vscode/*
 tasks/AutoCheckinBigGod/frida-server-17.6.2-android-x86_64
 oas.bat
+
+# Per-instance FrogBoss prediction and result history
+data/frog_oas/

+ 19 - 17
tasks/FrogBoss/assets.py

@@ -12,48 +12,50 @@ class FrogBossAssets:
 
 	# Image Rule Assets
 	# 左边竞猜 
-	I_BET_LEFT = RuleImage(roi_front=(95,308,145,100), roi_back=(58,248,245,195), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_left.png")
+	I_BET_LEFT = RuleImage(roi_front=(271,303,145,100), roi_back=(222,251,245,195), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_left.png")
 	# 右边竞猜 
-	I_BET_RIGHT = RuleImage(roi_front=(1038,303,146,100), roi_back=(1012,268,187,208), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_right.png")
+	I_BET_RIGHT = RuleImage(roi_front=(1070,302,146,100), roi_back=(1048,248,187,208), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_right.png")
 	# description 
-	I_BET_SUCCESS_BOX = RuleImage(roi_front=(593,419,87,50), roi_back=(564,378,140,133), threshold=0.75, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_success_box.png")
+	I_BET_SUCCESS_BOX = RuleImage(roi_front=(708,394,87,50), roi_back=(661,331,193,182), threshold=0.75, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_success_box.png")
 	# 左边赢了 
-	I_SUCCESS_LEFT = RuleImage(roi_front=(123,316,100,100), roi_back=(91,254,202,221), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_success_left.png")
+	I_SUCCESS_LEFT = RuleImage(roi_front=(292,306,100,100), roi_back=(238,243,202,221), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_success_left.png")
 	# 右边输了 
-	I_FAILURE_RIGHT = RuleImage(roi_front=(1063,291,100,100), roi_back=(993,242,224,199), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_failure_right.png")
+	I_FAILURE_RIGHT = RuleImage(roi_front=(1097,303,100,100), roi_back=(1029,256,224,199), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_failure_right.png")
 	# description 
-	I_NEXT_COMPETITION = RuleImage(roi_front=(673,510,42,36), roi_back=(658,488,91,98), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_next_competition.png")
+	I_NEXT_COMPETITION = RuleImage(roi_front=(775,485,42,36), roi_back=(692,437,157,147), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_next_competition.png")
 	# 30万金币 
-	I_GOLD_30 = RuleImage(roi_front=(858,494,78,76), roi_back=(809,427,147,187), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_gold_30.png")
+	I_GOLD_30 = RuleImage(roi_front=(862,499,78,76), roi_back=(831,441,147,187), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_gold_30.png")
 	# 确认竞猜 
-	I_BET_SURE = RuleImage(roi_front=(1025,402,100,100), roi_back=(1000,297,200,226), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_sure.png")
+	I_BET_SURE = RuleImage(roi_front=(1025,402,100,100), roi_back=(972,340,200,226), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_sure.png")
 	# description 
 	I_GOLD_30_CHECK = RuleImage(roi_front=(513,196,58,53), roi_back=(402,141,459,489), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_gold_30_check.png")
 	# description 
-	I_BETTED = RuleImage(roi_front=(93,352,125,54), roi_back=(49,283,1192,161), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_betted.png")
+	I_BETTED = RuleImage(roi_front=(1093,313,125,54), roi_back=(207,240,1058,312), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_betted.png")
 	# description 
-	I_SUCCESS_RIGHT = RuleImage(roi_front=(1048,341,122,116), roi_back=(999,243,201,260), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_success_right.png")
+	I_SUCCESS_RIGHT = RuleImage(roi_front=(1098,289,122,116), roi_back=(1040,250,201,260), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_success_right.png")
 	# description 
-	I_FAILURE_LEFT = RuleImage(roi_front=(116,307,100,100), roi_back=(76,256,193,219), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_failure_left.png")
+	I_FAILURE_LEFT = RuleImage(roi_front=(296,303,100,100), roi_back=(243,245,212,259), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_failure_left.png")
 	# description 
-	I_BET_FAILURE = RuleImage(roi_front=(496,252,269,72), roi_back=(439,220,400,152), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_failure.png")
+	I_BET_FAILURE = RuleImage(roi_front=(591,290,269,72), roi_back=(496,222,447,211), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_failure.png")
 	# description 
-	I_BET_SUCCESS = RuleImage(roi_front=(512,264,260,73), roi_back=(433,214,418,151), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_success.png")
+	I_BET_SUCCESS = RuleImage(roi_front=(625,278,260,73), roi_back=(482,243,521,225), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_bet_success.png")
 
 
 	# Image Rule Assets
 	# description 
-	I_FROG_BOSS_ENTER = RuleImage(roi_front=(1191,391,36,38), roi_back=(1174,135,78,320), threshold=0.7, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_boss_enter.png")
+	I_FROG_BOSS_ENTER = RuleImage(roi_front=(1188,303,36,38), roi_back=(1169,203,78,320), threshold=0.7, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_boss_enter.png")
 	# 休息中 
 	I_FROG_BOSS_REST = RuleImage(roi_front=(510,274,169,64), roi_back=(492,260,220,113), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_boss_rest.png")
+	# 竞猜主页面
+	I_FROG_CHECK = RuleImage(roi_front=(664,31,148,65), roi_back=(551,4,371,145), threshold=0.8, method="Template matching", file="./tasks/FrogBoss/fb/fb_frog_check.png")
 
 
 	# Ocr Rule Assets
 	# Ocr-description 
-	O_LEFT_COUNT = RuleOcr(roi=(143,496,69,31), area=(143,496,69,31), mode="Digit", method="Default", keyword="", name="left_count")
+	O_LEFT_COUNT = RuleOcr(roi=(326,469,69,31), area=(326,469,69,31), mode="Digit", method="Default", keyword="", name="left_count")
 	# Ocr-description 
-	O_RIGHT_COUNT = RuleOcr(roi=(1105,497,77,32), area=(1105,497,77,32), mode="Digit", method="Default", keyword="", name="right_count")
+	O_RIGHT_COUNT = RuleOcr(roi=(1139,472,77,32), area=(1139,472,77,32), mode="Digit", method="Default", keyword="", name="right_count")
 	# Ocr-description 
-	O_TIME_REMAIN = RuleOcr(roi=(594,564,91,35), area=(594,564,91,35), mode="Duration", method="Default", keyword="", name="time_remain")
+	O_TIME_REMAIN = RuleOcr(roi=(705,533,91,35), area=(705,533,91,35), mode="Duration", method="Default", keyword="", name="time_remain")
 
 

+ 1 - 0
tasks/FrogBoss/config.py

@@ -14,6 +14,7 @@ class Strategy(str, Enum):
     Minority = 'frog_minority'
     Bilibili = 'frog_bilibili'
     Dashen = 'frog_dashen'
+    Oas = 'frog_oas'
     AlwaysRed = 'frog_always_red'
     AlwaysBlue = 'frog_always_blue'
 

BIN
tasks/FrogBoss/fb/fb_bet_left.png


BIN
tasks/FrogBoss/fb/fb_bet_right.png


BIN
tasks/FrogBoss/fb/fb_bet_success.png


BIN
tasks/FrogBoss/fb/fb_bet_success_box.png


BIN
tasks/FrogBoss/fb/fb_betted.png


BIN
tasks/FrogBoss/fb/fb_failure_left.png


BIN
tasks/FrogBoss/fb/fb_frog_boss_enter.png


BIN
tasks/FrogBoss/fb/fb_frog_check.png


BIN
tasks/FrogBoss/fb/fb_next_competition.png


BIN
tasks/FrogBoss/fb/fb_success_right.png


+ 39 - 25
tasks/FrogBoss/fb/image.json

@@ -2,73 +2,81 @@
   {
     "itemName": "bet_left",
     "imageName": "fb_bet_left.png",
-    "roiFront": "95,308,145,100",
-    "roiBack": "58,248,245,195",
+    "roiFront": "271,303,145,100",
+    "roiBack": "222,251,245,195",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "左边竞猜"
   },
   {
     "itemName": "bet_right",
     "imageName": "fb_bet_right.png",
-    "roiFront": "1038,303,146,100",
-    "roiBack": "1012,268,187,208",
+    "roiFront": "1070,302,146,100",
+    "roiBack": "1048,248,187,208",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "右边竞猜"
   },
   {
     "itemName": "bet_success_box",
     "imageName": "fb_bet_success_box.png",
-    "roiFront": "593,419,87,50",
-    "roiBack": "564,378,140,133",
+    "roiFront": "708,394,87,50",
+    "roiBack": "661,331,193,182",
     "method": "Template matching",
     "threshold": 0.75,
+    "profile": "Default",
     "description": "description"
   },
   {
     "itemName": "success_left",
     "imageName": "fb_success_left.png",
-    "roiFront": "123,316,100,100",
-    "roiBack": "91,254,202,221",
+    "roiFront": "292,306,100,100",
+    "roiBack": "238,243,202,221",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "左边赢了"
   },
   {
     "itemName": "failure_right",
     "imageName": "fb_failure_right.png",
-    "roiFront": "1063,291,100,100",
-    "roiBack": "993,242,224,199",
+    "roiFront": "1097,303,100,100",
+    "roiBack": "1029,256,224,199",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "右边输了"
   },
   {
     "itemName": "next_competition",
     "imageName": "fb_next_competition.png",
-    "roiFront": "673,510,42,36",
-    "roiBack": "658,488,91,98",
+    "roiFront": "775,485,42,36",
+    "roiBack": "692,437,157,147",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
   },
   {
     "itemName": "gold_30",
     "imageName": "fb_gold_30.png",
-    "roiFront": "858,494,78,76",
-    "roiBack": "809,427,147,187",
+    "roiFront": "862,499,78,76",
+    "roiBack": "831,441,147,187",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "30万金币"
   },
   {
     "itemName": "bet_sure",
     "imageName": "fb_bet_sure.png",
     "roiFront": "1025,402,100,100",
-    "roiBack": "1000,297,200,226",
+    "roiBack": "972,340,200,226",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "确认竞猜"
   },
   {
@@ -78,51 +86,57 @@
     "roiBack": "402,141,459,489",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
   },
   {
     "itemName": "betted",
     "imageName": "fb_betted.png",
-    "roiFront": "93,352,125,54",
-    "roiBack": "49,283,1192,161",
+    "roiFront": "1093,313,125,54",
+    "roiBack": "207,240,1058,312",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
   },
   {
     "itemName": "success_right",
     "imageName": "fb_success_right.png",
-    "roiFront": "1048,341,122,116",
-    "roiBack": "999,243,201,260",
+    "roiFront": "1098,289,122,116",
+    "roiBack": "1040,250,201,260",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
   },
   {
     "itemName": "failure_left",
     "imageName": "fb_failure_left.png",
-    "roiFront": "116,307,100,100",
-    "roiBack": "76,256,193,219",
+    "roiFront": "296,303,100,100",
+    "roiBack": "243,245,212,259",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
   },
   {
     "itemName": "bet_failure",
     "imageName": "fb_bet_failure.png",
-    "roiFront": "496,252,269,72",
-    "roiBack": "439,220,400,152",
+    "roiFront": "591,290,269,72",
+    "roiBack": "496,222,447,211",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
   },
   {
     "itemName": "bet_success",
     "imageName": "fb_bet_success.png",
-    "roiFront": "512,264,260,73",
-    "roiBack": "433,214,418,151",
+    "roiFront": "625,278,260,73",
+    "roiBack": "482,243,521,225",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "description"
   }
 ]

+ 14 - 2
tasks/FrogBoss/fb/image2.json

@@ -2,10 +2,11 @@
   {
     "itemName": "frog_boss_enter",
     "imageName": "fb_frog_boss_enter.png",
-    "roiFront": "1191,391,36,38",
-    "roiBack": "1174,135,78,320",
+    "roiFront": "1188,303,36,38",
+    "roiBack": "1169,203,78,320",
     "method": "Template matching",
     "threshold": 0.7,
+    "profile": "Default",
     "description": "description"
   },
   {
@@ -15,6 +16,17 @@
     "roiBack": "492,260,220,113",
     "method": "Template matching",
     "threshold": 0.8,
+    "profile": "Default",
     "description": "休息中"
+  },
+  {
+    "itemName": "frog_check",
+    "imageName": "fb_frog_check.png",
+    "roiFront": "664,31,148,65",
+    "roiBack": "551,4,371,145",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "profile": "Default",
+    "description": "竞猜主页面"
   }
 ]

+ 6 - 6
tasks/FrogBoss/fb/ocr.json

@@ -1,8 +1,8 @@
 [
   {
     "itemName": "left_count",
-    "roiFront": "143,496,69,31",
-    "roiBack": "143,496,69,31",
+    "roiFront": "326,469,69,31",
+    "roiBack": "326,469,69,31",
     "mode": "Digit",
     "method": "Default",
     "keyword": "",
@@ -10,8 +10,8 @@
   },
   {
     "itemName": "right_count",
-    "roiFront": "1105,497,77,32",
-    "roiBack": "1105,497,77,32",
+    "roiFront": "1139,472,77,32",
+    "roiBack": "1139,472,77,32",
     "mode": "Digit",
     "method": "Default",
     "keyword": "",
@@ -19,8 +19,8 @@
   },
   {
     "itemName": "time_remain",
-    "roiFront": "594,564,91,35",
-    "roiBack": "594,564,91,35",
+    "roiFront": "705,533,91,35",
+    "roiBack": "705,533,91,35",
     "mode": "Duration",
     "method": "Default",
     "keyword": "",

+ 171 - 0
tasks/FrogBoss/frog_oas.py

@@ -0,0 +1,171 @@
+"""Persistent, outcome-verified weighted voting. Scores are not win probabilities."""
+import json
+import re
+import random
+from datetime import datetime
+from pathlib import Path
+from uuid import uuid4
+
+import cv2
+import requests
+
+from tasks.FrogBoss.oas_sources import DASHEN_UIDS
+
+
+def fingerprint(image):
+    # Only the two lineups: excludes countdown, votes, chest and result text.
+    bits = []
+    for x in (300, 807):
+        crop = image[112:233, x:x + 398]
+        gray = cv2.cvtColor(crop, cv2.COLOR_RGB2GRAY)
+        small = cv2.resize(gray, (33, 8))
+        bits.extend((small[:, 1:] > small[:, :-1]).flatten())
+    return ''.join('1' if bit else '0' for bit in bits)
+
+
+def same_lineup(a, b):
+    return len(a) == len(b) == 512 and sum(x != y for x, y in zip(a, b)) <= 20
+
+
+def parse_side(text):
+    # Ambiguous text is deliberately excluded rather than guessed by word order.
+    red = bool(re.search(r'押红|押左|压红|压左|我红|我左|红优|红方胜|红色胜', text))
+    blue = bool(re.search(r'押蓝|押右|压蓝|压右|我蓝|我右|蓝优|蓝方胜|蓝色胜', text))
+    if re.search(r'不押|不压|别押|别压|不要押|不要压', text):
+        return None
+    return ('LEFT' if red else 'RIGHT') if red != blue else None
+
+
+class OasHistory:
+    def __init__(self, path):
+        self.path = Path(path)
+        self.events = []
+        if self.path.exists():
+            for line in self.path.read_text(encoding='utf-8').splitlines():
+                try:
+                    event = json.loads(line)
+                except ValueError:
+                    continue  # Ignore a truncated final record after interruption.
+                if isinstance(event, dict):
+                    self.events.append(event)
+
+    def append(self, kind, **data):
+        event = dict(version=1, kind=kind, recorded_at=datetime.now().isoformat(), **data)
+        self.path.parent.mkdir(parents=True, exist_ok=True)
+        # Leading newline separates a possible truncated tail from the new event.
+        with self.path.open('a', encoding='utf-8') as stream:
+            stream.write('\n' + json.dumps(event, ensure_ascii=False) + '\n')
+            stream.flush()
+        self.events.append(event)
+        return event
+
+    def reliability(self, source):
+        decisions = {e['id']: e for e in self.events if e.get('kind') == 'decision'}
+        correct = total = 0
+        seen = set()
+        for result in self.events:
+            if result.get('kind') != 'result' or result['id'] in seen:
+                continue
+            seen.add(result['id'])
+            vote = decisions.get(result['id'], {}).get('votes', {}).get(source)
+            if vote in ('LEFT', 'RIGHT'):
+                total += 1
+                correct += vote == result['winner']
+        # Unverified newcomers start neutral; verified sources use raw win rate.
+        return correct / total if total else 0.5
+
+    def settle(self, signature, winner):
+        if winner not in ('LEFT', 'RIGHT'):
+            return None
+        # Include already settled records when checking ambiguity: never transfer
+        # an old result to a newer decision with an identical lineup.
+        matches = [e for e in self.events if e.get('kind') == 'decision'
+                   and same_lineup(e['signature'], signature)]
+        if len(matches) != 1:
+            self.append('unverified_result', signature=signature, winner=winner,
+                        reason='missing_or_ambiguous_decision')
+            return None
+        decision = matches[0]
+        if any(e.get('kind') == 'result' and e['id'] == decision['id'] for e in self.events):
+            return None
+        return self.append('result', id=decision['id'], winner=winner,
+                           outcomes={s: v == winner for s, v in decision['votes'].items()})
+
+    def choose(self, signature, left, right, predictions):
+        now = datetime.now()
+        # Re-entry in the same slot reuses the original frozen decision.
+        slot = f'{now.date()}:{now.hour // 2}'
+        for e in reversed(self.events):
+            if e.get('kind') == 'decision' and e['slot'] == slot and same_lineup(e['signature'], signature):
+                return e
+        crowd = ('LEFT' if left > right else 'RIGHT') if left != right and left + right > 0 else None
+        votes = {p['uid']: p['side'] for p in predictions if p.get('side') in ('LEFT', 'RIGHT')}
+        expert_left = sum(v == 'LEFT' for v in votes.values())
+        expert_right = sum(v == 'RIGHT' for v in votes.values())
+        expert_side = ('LEFT' if expert_left > expert_right else 'RIGHT') if expert_left != expert_right else None
+        if crowd:
+            votes['crowd'] = crowd
+        cold_start = not any(e.get('kind') == 'result' for e in self.events)
+        weights = {} if cold_start else {uid: self.reliability(uid) for uid in votes}
+        scores = {'LEFT': 0.0, 'RIGHT': 0.0}
+        if cold_start:
+            # Two equal votes: the expert majority as a whole and the crowd.
+            for vote in (expert_side, crowd):
+                if vote:
+                    scores[vote] += 1
+        else:
+            for uid, vote in votes.items():
+                scores[vote] += weights[uid]
+        tied = abs(scores['LEFT'] - scores['RIGHT']) < 1e-12
+        side = random.choice(('LEFT', 'RIGHT')) if tied else max(scores, key=scores.get)
+        return self.append('decision', id=uuid4().hex, slot=slot, signature=signature,
+                           left=left, right=right, votes=votes, weights=weights,
+                           scores=scores, side=side, strategy_version=2,
+                           mode='cold_start' if cold_start else 'win_rate',
+                           expert_counts={'LEFT': expert_left, 'RIGHT': expert_right},
+                           expert_side=expert_side, crowd_side=crowd, random_tiebreak=tied)
+
+
+def fetch_predictions(history):
+    now = datetime.now()
+    used = {(e.get('uid'), e.get('feed_id')) for e in history.events
+            if e.get('kind') == 'fetch' and e.get('accepted')}
+    predictions = []
+    with requests.Session() as session:
+        for uid in DASHEN_UIDS:
+            feed_id = None
+            try:
+                response = session.get('https://inf.ds.163.com/v1/web/feed/basic/getSomeOneFeeds',
+                                       params={'feedTypes': '1,2,3,4,6,7,10,11', 'someOneUid': uid}, timeout=(3, 5))
+                response.raise_for_status()
+                feeds = response.json().get('result', {}).get('feeds', [])
+                if not feeds:
+                    history.append('fetch', uid=uid, accepted=False, reason='no_feed')
+                    continue
+                feed_id = feeds[0]['id']
+                response = session.get('https://inf.ds.163.com/v1/web/feed/basic/facade',
+                                       params={'feedId': feed_id}, timeout=(3, 5))
+                response.raise_for_status()
+                feed = response.json()['result']['feed']
+                content = feed['content']
+                if isinstance(content, str):
+                    content = json.loads(content)
+                body = content['body']['text']
+                raw_time = feed.get('createTime')
+                published = None
+                try:
+                    published = datetime.fromtimestamp(float(raw_time) / 1000)
+                except (TypeError, ValueError, OverflowError, OSError):
+                    pass
+                side = parse_side(body)
+                fresh = published is not None and published.date() == now.date() and published.hour // 2 == now.hour // 2 and published <= now
+                accepted = fresh and side is not None and (uid, feed_id) not in used
+                history.append('fetch', uid=uid, feed_id=feed_id, create_time=raw_time,
+                               body=body, side=side, accepted=accepted,
+                               reason='accepted' if accepted else 'stale_unknown_ambiguous_or_duplicate')
+                if accepted:
+                    predictions.append(dict(uid=uid, side=side, feed_id=feed_id))
+            except (requests.RequestException, ValueError, KeyError, IndexError, TypeError) as exc:
+                history.append('fetch', uid=uid, feed_id=feed_id, accepted=False,
+                               reason='request_or_parse_error', error=str(exc))
+    return predictions

+ 2 - 0
tasks/FrogBoss/oas_sources.py

@@ -0,0 +1,2 @@
+"""UIDs shared with the legacy Dashen strategy; deduplicated for frog_oas."""
+DASHEN_UIDS = ["462382f1127b46c5add1185d88f0ea40","54399446d5084a0e8878dac8f6ff56d0","840742d60e4a43208605ae68ca8c3f64","c3c989fae4074d04b478b8ba47ae4120","aaa923436aa440df9ac1ee3f47387b99","72584a679e2f45b6859566b5523400d5","3d4726d99f2642a485729695b798cb8c","1d2dcbbd7e3d481c8d0f27ba4ff0dc71","21657a558bdd4ddfb6501298350336e7","0e4e0c5a1e494a1fa9a58ac55de689c1","30e383c884f844a18a7a76fe3c1e888f","d9dc2a75497c4a91b2db1e909a36544d","e7107cd3010e418da26672669d8eeb5e","74adeb1bfb2b4cf382edbbb430da2149","e87f855f36f24b34b9d8f8a4fb2d62b2","82de68c7672e4b6da65493fb829b57b6","f6d6bb15d6024200a985752e2ab4c373","06e2bba14a914012bc8064601cfa19ea","8982241de1844638b4bb455139b8dcc0","a9724e98c1cb4a4e931ebc3f467ea73d","e9b0a16325af46628e8dfb9e7942cf1d","b6b5bc8277e34f69aeca018db0081397","74db771d92a54c28ae3e98d19aa565a3","e498e524252041e29999b38e57c4df1d","30b0c2923faa483f95572c324a5bc910","e32aedbdd8da46a5b5b497a16c4b7658"]

+ 45 - 3
tasks/FrogBoss/script_task.py

@@ -6,8 +6,9 @@ from datetime import datetime
 import requests
 import re
 import json
+from pathlib import Path
 
-from module.exception import TaskEnd
+from module.exception import GameStuckError, TaskEnd
 from module.logger import logger
 from module.atom.image import RuleImage
 from module.base.timer import Timer
@@ -19,11 +20,34 @@ from tasks.Component.GeneralBattle.assets import GeneralBattleAssets
 from tasks.Component.config_base import TimeDelta
 from tasks.FrogBoss.assets import FrogBossAssets
 from tasks.FrogBoss.config import Strategy
+from tasks.FrogBoss.frog_oas import OasHistory, fetch_predictions, fingerprint
 
 
 class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
-    def run(self):
+    @cached_property
+    def oas_history(self):
+        instance = re.sub(r'[^\w.-]', '_', self.config.config_name)
+        return OasHistory(Path('data/frog_oas') / f'{instance}.jsonl')
+
+    def record_oas_result(self):
+        if self.config.model.frog_boss.frog_boss_config.strategy_frog != Strategy.Oas:
+            return
+        winner = self.detect()
+        if winner is not None:
+            result = self.oas_history.settle(
+                fingerprint(self.device.image), 'LEFT' if winner else 'RIGHT')
+            logger.info(f'frog_oas result: {result}')
+
+    def enter_frog_boss(self):
+        self.screenshot()
+        if self.appear(self.I_FROG_CHECK):
+            return
         self.enter(self.I_FROG_BOSS_ENTER)
+        if not self.wait_until_appear(self.I_FROG_CHECK, wait_time=10):
+            raise GameStuckError('FrogBoss page not detected after entering activity')
+
+    def run(self):
+        self.enter_frog_boss()
         # 进入主界面
         while 1:
             self.screenshot()
@@ -39,6 +63,7 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
             # 竞猜成功
             if self.appear(self.I_BET_SUCCESS):
                 logger.info('You bet win')
+                self.record_oas_result()
                 self.detect()
                 while 1:
                     self.screenshot()
@@ -54,6 +79,7 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
             # 竞猜失败
             if self.appear(self.I_BET_FAILURE):
                 logger.info('You bet lose')
+                self.record_oas_result()
                 self.ui_click_until_disappear(self.I_NEXT_COMPETITION)
                 self.detect()
                 continue
@@ -105,6 +131,22 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
                 click_image = self.I_BET_LEFT if count_left > count_right else self.I_BET_RIGHT
             case Strategy.Dashen:
                 click_image = self.get_dashen(count_left, count_right)
+            case Strategy.Oas:
+                signature = fingerprint(self.device.image)
+                predictions = fetch_predictions(self.oas_history)
+                try:
+                    decision = self.oas_history.choose(signature, count_left, count_right, predictions)
+                except ValueError as exc:
+                    raise GameStuckError(str(exc)) from exc
+                logger.info(f'frog_oas decision: {decision}')
+                # Fetching may span a round transition; never click a stale frame.
+                self.screenshot()
+                from tasks.FrogBoss.frog_oas import same_lineup
+                if not same_lineup(signature, fingerprint(self.device.image)):
+                    raise GameStuckError('FrogBoss lineup changed while fetching predictions')
+                if not (self.appear(self.I_BET_LEFT) and self.appear(self.I_BET_RIGHT)):
+                    raise GameStuckError('FrogBoss betting closed while fetching predictions')
+                click_image = self.I_BET_LEFT if decision['side'] == 'LEFT' else self.I_BET_RIGHT
             case Strategy.AlwaysRed:
                 click_image = self.I_BET_LEFT
             case Strategy.AlwaysBlue:
@@ -152,7 +194,7 @@ class ScriptTask(RightActivity, FrogBossAssets, GeneralBattleAssets):
             result = False
             logger.info('Right win')
         else:
-            result = True
+            result = None
         return result
 
     def get_bilibili(self) -> RuleImage:

+ 64 - 0
tasks/FrogBoss/test_frog_oas.py

@@ -0,0 +1,64 @@
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from tasks.FrogBoss.frog_oas import OasHistory, parse_side, same_lineup
+
+
+class OasTests(unittest.TestCase):
+    def test_persistence_rewards_and_dedup(self):
+        with tempfile.TemporaryDirectory() as directory:
+            path = Path(directory) / 'history.jsonl'
+            store = OasHistory(path)
+            decision = store.choose('0' * 512, 20, 10, [
+                {'uid': 'a', 'side': 'LEFT'}, {'uid': 'b', 'side': 'RIGHT'}])
+            self.assertEqual(store.reliability('a'), .5)
+            self.assertEqual(store.choose('0' * 512, 10, 20, [])['id'], decision['id'])
+            self.assertIsNone(store.settle('1' * 512, 'LEFT'))
+            store.settle('0' * 512, 'LEFT')
+            self.assertIsNone(store.settle('0' * 512, 'LEFT'))
+            reloaded = OasHistory(path)
+            self.assertEqual(reloaded.reliability('a'), 1)
+            self.assertEqual(reloaded.reliability('b'), 0)
+            self.assertEqual(reloaded.reliability('crowd'), 1)
+            second = reloaded.choose('1' * 512, 10, 20, [
+                {'uid': 'a', 'side': 'LEFT'}, {'uid': 'b', 'side': 'LEFT'}])
+            self.assertEqual(second['scores'], {'LEFT': 1, 'RIGHT': 1})
+            self.assertEqual(second['mode'], 'win_rate')
+            reloaded.settle('1' * 512, 'RIGHT')
+            self.assertEqual(reloaded.reliability('a'), .5)
+            self.assertEqual(reloaded.reliability('b'), 0)
+            self.assertEqual(reloaded.reliability('crowd'), 1)
+
+    def test_fallback_and_missing_data(self):
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            self.assertEqual(store.choose('0' * 512, 1, 2, [])['side'], 'RIGHT')
+            self.assertEqual(store.reliability('crowd'), .5)
+            with patch('tasks.FrogBoss.frog_oas.random.choice', return_value='LEFT'):
+                self.assertEqual(store.choose('1' * 512, 0, 0, [])['side'], 'LEFT')
+
+    def test_cold_start_two_equal_groups(self):
+        predictions = [{'uid': str(i), 'side': 'LEFT' if i < 6 else 'RIGHT'} for i in range(9)]
+        with tempfile.TemporaryDirectory() as directory:
+            store = OasHistory(Path(directory) / 'history.jsonl')
+            agreed = store.choose('0' * 512, 20, 10, predictions)
+            self.assertEqual(agreed['side'], 'LEFT')
+            self.assertEqual(agreed['scores'], {'LEFT': 2, 'RIGHT': 0})
+            with patch('tasks.FrogBoss.frog_oas.random.choice', return_value='RIGHT') as choose:
+                opposed = store.choose('1' * 512, 10, 20, predictions)
+                self.assertEqual(opposed['scores'], {'LEFT': 1, 'RIGHT': 1})
+                self.assertEqual(opposed['side'], 'RIGHT')
+                choose.assert_called_once_with(('LEFT', 'RIGHT'))
+
+    def test_ambiguous_text_and_signature(self):
+        self.assertEqual(parse_side('本场押红'), 'LEFT')
+        self.assertIsNone(parse_side('不押红,押蓝'))
+        self.assertIsNone(parse_side('押红还是押蓝'))
+        self.assertTrue(same_lineup('0' * 512, '1' * 10 + '0' * 502))
+        self.assertFalse(same_lineup('0' * 512, '1' * 512))
+
+
+if __name__ == '__main__':
+    unittest.main()