Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
181 changes: 181 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,187 @@ def bossing_delete_drop(identifier):
return jsonify(_bossing())


# Quanah: the seasonal event-equipment set solver. One global list, no character.
QUANAH_QUEUE = "quanah"


@app.get("/api/quanah")
def quanah():
from quanah import store

return jsonify(store.payload())


@app.put("/api/quanah/settings")
def quanah_settings():
from quanah import store

body = request.get_json(silent=True) or {}
store.configure(class_key=body.get("class"), build=body.get("build"))
return jsonify(store.payload())


@app.post("/api/quanah/items")
def quanah_add_item():
from quanah import store

body = request.get_json(silent=True) or {}
store.add_item(body.get("slot"), body.get("lines"))
return jsonify(store.payload())


@app.put("/api/quanah/items/<identifier>")
def quanah_update_item(identifier):
from quanah import store

body = request.get_json(silent=True) or {}
store.update_item(identifier, body.get("slot"), body.get("lines"))
return jsonify(store.payload())


@app.delete("/api/quanah/items/<identifier>")
def quanah_delete_item(identifier):
from quanah import store

store.delete_item(identifier)
return jsonify(store.payload())


@app.delete("/api/quanah/items")
def quanah_clear_items():
from quanah import store

store.clear_items()
return jsonify(store.payload())


@app.post("/api/quanah/scan")
def quanah_scan():
"""Watch the game and capture every event item hovered, until /api/scan/cancel."""
global generation, preview, job
import hover_queue
import ocr_worker
from quanah import store

body = request.get_json(silent=True) or {}
if not store.read()["class"]:
raise ValueError("Choose your class first")
if not isinstance(body.get("window"), int) or isinstance(body.get("window"), bool):
raise ValueError("Choose the game window")
with job_lock:
if job.get("active"):
raise ValueError("A capture is already running")
generation += 1
token = generation
preview = None
hover_queue.reset(QUANAH_QUEUE)
job = {"active": True, "status": "watching", "mode": "quanah", "captured": 0,
"message": "Hover an event item in your inventory or Equipment."}
scan_executor.submit(_quanah_perform, {"mode": "quanah", "window": body["window"]}, token)
state = dict(job)
ocr_worker.warm()
return jsonify(state)


def _quanah_perform(body, token):
global job
import scan_worker

try:
with scan_worker.session():
_quanah_watch(body, token)
except Exception as exc:
with job_lock:
if token == generation and job.get("active"):
job = {"active": False, "status": "error", "message": str(exc)}
raise


QUANAH_FAILED = Path("logs/quanah-failed")


def _keep_failed_capture(frame):
"""Save a capture that could not be read, keeping the 20 newest, so it can be diagnosed."""
from utils.image_files import encode_png

QUANAH_FAILED.mkdir(parents=True, exist_ok=True)
path = QUANAH_FAILED / f"{time.strftime('%Y%m%d-%H%M%S')}-{time.time_ns() % 1_000_000_000:09d}.png"
path.write_bytes(encode_png(frame))
for old in sorted(QUANAH_FAILED.glob("*.png"))[:-20]:
old.unlink(missing_ok=True)
return path


def _save_quanah_piece(frame, anchor):
from ocr_worker import read
from quanah import store
from quanah.lines import SKIPPED

try:
piece = read(frame, "quanah:%d:%d" % anchor)
except Exception as exc:
# Another item (a shoulder, a medal) is expected, not a failure worth keeping.
if not str(exc).startswith(SKIPPED):
try:
_keep_failed_capture(frame)
except Exception:
pass # The reading failed either way; only the copy for diagnosis is lost.
raise
store.add_item(piece["slot"], piece["lines"], raw=piece["raw"], name=piece["name"],
item_class=piece["item_class"], source="scan")


def _quanah_watch(body, token):
global job
import hover_queue
import scan_worker

previous, captured = None, 0

def update(message):
global job
with job_lock:
if token != generation:
return False
job = {"active": True, "status": "watching", "mode": "quanah", "captured": captured, "message": message}
return True

while True:
with job_lock:
if token != generation:
return
try:
frame, mark, anchor = scan_worker.call("quanah_step", body, previous)
except (ImportError, AttributeError, TypeError) as exc:
with job_lock:
if token == generation:
job = {"active": False, "status": "error", "fatal": True, "message": str(exc)}
return
except Exception as exc:
if not update(str(exc)):
return
time.sleep(0.12)
continue
if frame is None:
# Nothing hovered: the same item may be captured again next time.
previous = None
if not update("Captured " + str(captured) + ". Hover the next item." if captured
else "Hover an event item in your inventory or Equipment."):
return
time.sleep(0.12)
continue
previous = mark
captured += 1
with job_lock:
if token != generation:
return
hover_queue.submit_task(QUANAH_QUEUE, f"piece-{token}-{captured}",
lambda frame=frame, anchor=anchor: _save_quanah_piece(frame, anchor))
if not update(f"Captured {captured}. Reading in the background; hover the next item."):
return
time.sleep(0.12)


@app.get("/api/characters/<identifier>/equipment/<slot>/icon")
def icon(identifier, slot):
characters.load(identifier)
Expand Down
55 changes: 46 additions & 9 deletions src/equipment_scan.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,15 @@ def tooltip_bounds(frame, allow_clipped_footer=False, near=None):
x = ax - 155
if x < 0 or x + 323 > frame.shape[1] or ay < 105:
raise ReadError("Keep the item name, stars and full tooltip width on screen.")
return x, ay, tooltip_bottom(frame, x, ay, allow_clipped_footer)


def tooltip_bottom(frame, x, ay, allow_clipped_footer=False):
"""The y just below the tooltip starting at X, searching from AY + 65.

AY is where a "Currently Equipped" label sits (72 px above Required Level),
whether or not this tooltip shows one.
"""
strip = frame[ay + 65 :, x + 20 : x + 300].astype(int)
if strip.shape[1] != 280:
raise ReadError("Move the full tooltip on screen.")
Expand All @@ -125,9 +134,9 @@ def tooltip_bounds(frame, allow_clipped_footer=False, near=None):
candidates = _verified_bottom_candidates(frame, x, ay, soft.mean(axis=1), coverage_min=.94, corner_min=.85)
if not len(candidates):
if allow_clipped_footer and frame.shape[:2] == (768, 1366):
return x, ay, frame.shape[0]
return frame.shape[0]
raise ReadError("Show the entire item tooltip, including its bottom edge.")
return x, ay, ay + 65 + int(candidates[0]) + 3
return ay + 65 + int(candidates[0]) + 3


def hover_target(frame, pointer, slots):
Expand Down Expand Up @@ -167,12 +176,40 @@ def mono(image):
return cv2.cvtColor((image.max(axis=2) > 155).astype(np.uint8) * 255, cv2.COLOR_GRAY2BGR)


def row_regions(frame, x, top, bottom):
area = frame[top:bottom, x + 15 : x + 310]
mask = area.max(axis=2) > 155
ys = np.flatnonzero(mask.sum(axis=1) >= 3)
# Tooltip text spans these columns from the tooltip's left edge; rows are 6 to 19 px tall.
TEXT_LEFT, TEXT_RIGHT = 15, 310
ROW_MIN, ROW_MAX = 6, 19


def row_crop(frame, x, row):
"""A text row of the tooltip at X, as the reader sees it."""
a, b = row
return mono(frame[a:b, x + TEXT_LEFT : x + TEXT_RIGHT])


def row_regions(frame, x, top, bottom, split=False):
"""Text rows as (top, bottom). Blocks taller than a row are dropped, or with SPLIT,
cut at their emptiest row: the mouse cursor on a tooltip's edge joins neighbouring
rows (e.g. the stars and the name) into one such block."""
counts = (frame[top:bottom, x + TEXT_LEFT : x + TEXT_RIGHT].max(axis=2) > 155).sum(axis=1)
ys = np.flatnonzero(counts >= 3)
groups = [g for g in np.split(ys, np.flatnonzero(np.diff(ys) > 2) + 1) if len(g)]
return [(top + int(g[0]) - 2, top + int(g[-1]) + 3) for g in groups if 6 <= g[-1] - g[0] + 1 <= 19]
rows = []

def add(first, last):
height = last - first + 1
if ROW_MIN <= height <= ROW_MAX:
rows.append((top + first - 2, top + last + 3))
elif split and height > ROW_MAX:
inner = np.arange(first + ROW_MIN, last - ROW_MIN + 1)
cut = int(inner[np.argmin(counts[inner])])
add(first, cut - 1)
add(cut + 1, last)

for group in groups:
add(int(group[0]), int(group[-1]))
# With SPLIT, also keep the padded top inside the frame; without it, rows are exactly as before.
return [(max(0, a), b) for a, b in rows] if split else rows


def capabilities(slot, name, potential, stats, text):
Expand Down Expand Up @@ -236,7 +273,7 @@ def level_values(value):
return tuple(map(int, re.findall(r"\d+", found[1])))

(text, confidence), accepted = verify(
reader, mono(frame[a:b, x + 15:x + 310]), (text, confidence), level_values,
reader, row_crop(frame, x, (a, b)), (text, confidence), level_values,
)
if not accepted:
raise ReadError("Required level is unclear; scan again")
Expand Down Expand Up @@ -408,7 +445,7 @@ def hover(frame, reader, slot=None):
clipped_footer = bottom == frame.shape[0]
name_row = mono(frame[ay - 70 : ay - 48, x + 15 : x + 310])
rows = row_regions(frame, x, ay + 53, bottom - (4 if clipped_footer else 12))
crops = [name_row] + [mono(frame[a:b, x + 15 : x + 310]) for a, b in rows]
crops = [name_row] + [row_crop(frame, x, row) for row in rows]
readings = reader(crops)
name, confidence = _resolve_item_name(reader, frame, x, ay, name_row, *readings[0])
result = {"kind": "hover", "item": name.strip(), "source": "equipped_tooltip", "errors": []}
Expand Down
21 changes: 19 additions & 2 deletions src/flaming/item_tooltip.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from utils.payload_data import read_payload_bytes


def level_anchor(frame):
def _level_scores(frame):
# Threshold the translucent background away, retaining the native glyphs.
def mask(image):
return (image.min(axis=2) > 105).astype(np.uint8) * 255
Expand All @@ -25,7 +25,24 @@ def mask(image):
if anchor is None:
raise ReadError("Could not decode the Required Level reference image")
results.append(cv2.matchTemplate(mask(frame), mask(anchor), cv2.TM_CCOEFF_NORMED))
result = np.maximum.reduce(results)
return np.maximum.reduce(results), anchor


def level_anchors(frame, threshold=0.95, limit=4):
"""Every visible Required Level label, best first: [(x, y)]. A comparison shows two."""
scores, _ = _level_scores(frame)
found = []
while len(found) < limit:
_, quality, _, (x, y) = cv2.minMaxLoc(scores)
if quality < threshold:
break
found.append((x, y))
scores[max(0, y - 3) : y + 4, max(0, x - 3) : x + 4] = 0
return found


def level_anchor(frame):
result, anchor = _level_scores(frame)
_, quality, _, (x, y) = cv2.minMaxLoc(result)
if quality < 0.95:
raise ReadError("Required Level tooltip label is not visible")
Expand Down
3 changes: 3 additions & 0 deletions src/game_resolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ def normalize_scan(image, mode):
path = "images/window/scouter/erda_banner.png"
elif mode == "equipment" or mode.startswith("hover:"):
path = "images/window/equipment/windows_title.png"
elif mode == "quanah":
# Inventory hovers have no Equipment window; every item tooltip has this label.
path = "images/window/equipment/required_level.png"
elif mode == "weapon":
path = "images/window/equipment/currently_equipped.png"
elif mode == "links":
Expand Down
1 change: 1 addition & 0 deletions src/quanah/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Quanah: the seasonal event-equipment skill-line set solver."""
43 changes: 43 additions & 0 deletions src/quanah/data/lines.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
{
"slots": [
{"key": "hat", "name": "Hat", "keywords": ["Hat"]},
{"key": "top", "name": "Top", "keywords": ["Top", "Overall"]},
{"key": "bottom", "name": "Bottom", "keywords": ["Bottom", "Pants"]},
{"key": "cape", "name": "Cape", "keywords": ["Cape"]},
{"key": "gloves", "name": "Gloves", "keywords": ["Gloves", "Glove"]},
{"key": "shoes", "name": "Shoes", "keywords": ["Shoes", "Shoe"]}
],
"classes": [
{"key": "warrior", "name": "Warrior"},
{"key": "magician", "name": "Magician"},
{"key": "bowman", "name": "Bowman"},
{"key": "thief", "name": "Thief"},
{"key": "pirate", "name": "Pirate"}
],
"lines": [
{"key": "dl", "name": "Dimensional Leap", "text": "Dimensional Leap Lv. +1"},
{"key": "wh", "name": "White Hole", "text": "White Hole Lv. +1"},
{"key": "reg", "name": "Registry", "text": "[Hologram] Registry Lv. +1"},
{"key": "atk", "name": "ATK", "text": "[Hologram] Attack Power & Magic ATT Enhancement Skill Lv. +1"},
{"key": "crit", "name": "Crit DMG", "text": "Critical Damage Enhancement Skill Lv. +1"},
{"key": "dmg", "name": "DMG", "text": "[Hologram] Damage Enhancement Skill Lv. +1"},
{"key": "warrior", "name": "Warrior", "text": "[Hologram] Warrior Attack Skill Lv. +1", "job": true},
{"key": "magician", "name": "Magician", "text": "[Hologram] Magician Attack Skill Lv. +1", "job": true},
{"key": "bowman", "name": "Bowman", "text": "[Hologram] Bowman Attack Skill Lv. +1", "job": true},
{"key": "thief", "name": "Thief", "text": "[Hologram] Thief Attack Skill Lv. +1", "job": true},
{"key": "pirate", "name": "Pirate", "text": "[Hologram] Pirate Attack Skill Lv. +1", "job": true}
],
"builds": [
{"key": "skill", "name": "Skill",
"targets": {"dl": 3, "wh": 3, "reg": 3, "atk": 3, "warrior": 1, "magician": 1, "bowman": 1, "thief": 1, "pirate": 1, "crit": 1}},
{"key": "gandi", "name": "GanDi",
"targets": {"dl": 3, "wh": 3, "reg": 3, "atk": 3, "crit": 3},
"jobs": {"count": 3, "default": ["magician", "thief", "bowman"]}},
{"key": "eu", "name": "EU",
"targets": {"dl": 3, "wh": 3, "reg": 3, "atk": 3, "crit": 3, "dmg": 3}},
{"key": "custom", "name": "Custom", "targets": {}}
],
"goal": 18,
"max_per_line": 3,
"max_lines": 3
}
Loading
Loading