2753 lines
120 KiB
Python
2753 lines
120 KiB
Python
#!/usr/bin/env python3
|
||
"""Parse messy, manually copied Discord trading messages into a deduplicated CSV.
|
||
|
||
No Discord API, account automation, or scraping is used. Requires Python 3.10+.
|
||
|
||
Windows PowerShell:
|
||
Get-Clipboard -Raw | py discord_trade_parser.py
|
||
py discord_trade_parser.py trades.txt
|
||
py discord_trade_parser.py pastes --detailed
|
||
|
||
Recognized message boundaries:
|
||
[\n11:46\n]\nUsername (@handle) [Role],\n:\nTrading ...
|
||
[11:46]\nUsername\n:\nTrading ...
|
||
### 11:33Username (@handle)*:*\nTrading ...
|
||
|
||
Default CSV has the original two columns: offer, looking_for.
|
||
Use --detailed to additionally export LF / MLF / NLF, hashed authors,
|
||
repost counts, and update counts. An SQLite database preserves the latest
|
||
observed listing across multiple processing runs. Process older files first.
|
||
Reported scam warnings with named accounts go to scammer_warnings.csv.
|
||
Offer cleanup removes copied channel labels, timestamps, and chat instructions.
|
||
Standalone SSS stat listings and broad offered options such as "All Gamepasses"
|
||
remain in the CSV. A broad option does not mean every item will be exchanged.
|
||
Dyno bot notices are ignored before trade extraction.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
from collections import Counter
|
||
import csv
|
||
from dataclasses import dataclass
|
||
from difflib import SequenceMatcher
|
||
from functools import lru_cache
|
||
import glob
|
||
import hashlib
|
||
import html
|
||
import json
|
||
from pathlib import Path
|
||
import re
|
||
import sqlite3
|
||
import sys
|
||
import unicodedata
|
||
import uuid
|
||
from typing import Iterable, Iterator
|
||
|
||
TIME = re.compile(r"(?:[01]?\d|2[0-3]):[0-5]\d")
|
||
BRACKETED_TIME = re.compile(r"\[\s*((?:[01]?\d|2[0-3]):[0-5]\d)\s*\]")
|
||
INLINE_HEADER = re.compile(r"^(?P<time>(?:[01]?\d|2[0-3]):[0-5]\d)\s*(?P<rest>\S.*)$")
|
||
HANDLE = re.compile(r"\(@([^\)]+)\)")
|
||
WORD = re.compile(r"[\w]+", re.UNICODE)
|
||
EMOJI_CODE = re.compile(r"<a?:[A-Za-z0-9_~+-]+:\d+>|:[A-Za-z][A-Za-z0-9_~+-]*:")
|
||
KEYCAP_EMOJI = re.compile(r"[#*0-9]\ufe0f?\u20e3")
|
||
EMOJI_PUNCTUATION = {"\u203c", "\u2049"}
|
||
# Earlier parsing stripped the colons from these decorative server emoji names.
|
||
LEGACY_BARE_EMOJI = re.compile(r"(?<!\w)(?:CH_[A-Za-z0-9_]+|tlw[A-Z][A-Za-z0-9_]*)(?!\w)")
|
||
DECORATIVE_MARKS = re.compile(r"-+>+|<{2,}|>{2,}")
|
||
FODDER_NAME = re.compile(
|
||
r"\b(?:FODDERS?|FOODDERS?|FOODERS?|FODERS?)(?:\s+UNITS?)?\b|"
|
||
r"\bFOLDER\s+UNITS?\b", re.I,
|
||
)
|
||
FODDER_MYTHICS = re.compile(
|
||
r"\b(?:FODDERS?|FOODDERS?|FOODERS?|FODERS?)\s+MYTHICS?\b", re.I,
|
||
)
|
||
FODDER_ALIAS_NAMES = re.compile(
|
||
r"\b(?:TRASH\s+(?:MYTHICS?|UNITS?)|BUM\s+UNITS?)\b", re.I,
|
||
)
|
||
FODDER_ALIAS_PAIR = re.compile(
|
||
r"(?<!\w)(?P<left>Fodder Units|Trash (?:Mythics?|Units?)|Bum Units?)"
|
||
r"(?P<status1>\s+(?:Evo|Unevo))?\s*/\s*"
|
||
r"(?P<right>Fodder Units|Trash (?:Mythics?|Units?)|Bum Units?)"
|
||
r"(?P<status2>\s+(?:Evo|Unevo))?(?!\w)", re.I,
|
||
)
|
||
UNIT_NAME_RULES = tuple(
|
||
(re.compile(pattern, re.I), canonical)
|
||
for pattern, canonical in (
|
||
(r"\bSHINNY\b", "Shiny"),
|
||
(r"\bFRIREN\b", "Frieren"),
|
||
(r"\bFREIREN\b", "Elf Mage"),
|
||
(r"\bUMBRA\b", "Cid"),
|
||
(r"\bZABUZA\b", "Mist Ninja"),
|
||
(r"\bDAZAI\b", "Inhuman"),
|
||
(r"\bILLUSIONIST\b", "Aizen"),
|
||
(r"\bILLUSIONST\b", "Aizen"),
|
||
(r"\bFRIEREN\b", "Elf Mage"),
|
||
(r"\bLORD\s+ALIEN\s+(?:EVO\s+)?KING\b", "Boros"),
|
||
(r"\bLORD\s+ALIEN\b", "Boros"),
|
||
(r"\bALIEN\s+KING\b", "Boros"),
|
||
(r"\bLORD\s+BOROS\b", "Boros"),
|
||
(r"\bBORON\b", "Boros"),
|
||
(r"\bBOROS\b", "Boros"),
|
||
(r"\bSHISUI\b", "Shizo"),
|
||
(r"\bDOFFY\b", "Doflamingo"),
|
||
(r"\bDOFLAMINGO\b", "Doflamingo"),
|
||
(r"\bRIONY\b", "Rias"),
|
||
(r"\bRIAS\b", "Rias"),
|
||
(r"\bMILLIE\b", "Mamy"),
|
||
(r"\bMAMI\b", "Mamy"),
|
||
(r"\bMAMY\b", "Mamy"),
|
||
(r"\bJUDAR\b", "Dark Mage"),
|
||
(r"\bCHIHIRO\b", "Vengeful Swordsman"),
|
||
(r"\bHAMMER\s*HEAD\b", "Harribel"),
|
||
(r"\bHARRIBEL\b", "Harribel"),
|
||
(r"\bHARIBELL\b", "Harribel"),
|
||
(r"\bMITSUKAI\b", "Violentine"),
|
||
(r"\bINUYASHU\b", "Dog Demon"),
|
||
(r"\bDOG\s+DEMON\b", "Dog Demon"),
|
||
(r"\bCRUSADER\b", "Heathcliff"),
|
||
(r"\bHEATHCLIFF\b", "Heathcliff"),
|
||
(r"\bBLACK\s*DOG\b", "Black Dog"),
|
||
(r"\bSEA\s+GOD\b", "Poseidon"),
|
||
(r"\bSEAGOD\b", "Poseidon"),
|
||
(r"\b(?:ENLIGHTENED|ENLIGTHENED|ELIGHTEND)\b", "Buddha"),
|
||
(r"\bENLIGHTENET\b", "Buddha"),
|
||
(r"\bGOLDEN\s+KING\b", "Gilgamesh"),
|
||
(r"\bDRACULA\b", "Alucard"),
|
||
(r"\bVIKING\b", "Thorfinn"),
|
||
(r"\bSHADOWGIRL\b", "Homura"),
|
||
(r"\bLEGENDARY\s+ASSASSIN\b", "Sakamoto"),
|
||
(r"\bLEGENDARY\s+ASSASIN\b", "Sakamoto"),
|
||
(r"\bPRIME\s+ASSASSIN\b", "Sakamoto"),
|
||
(r"\bSK\s*/\s*SKULL\s*/\s*SKELETON\s+KNIGHT\b", "Skull Knight"),
|
||
(r"\bSHINY\s+SK\b", "Shiny Skull Knight"),
|
||
(r"\bSK\b", "Skull Knight"),
|
||
(r"\bDM\b(?!\s+(?:ME|US|YOUR|IF|FOR|OFFERS?|PLEASE|PLS|TO)\b)", "Dark Mage"),
|
||
(r"\bBPS\b", "Battlepasses"),
|
||
(r"\bBP\b", "Battlepass"),
|
||
(r"\bOPS\b", "Overpays"),
|
||
(r"\bOP\b", "Overpay"),
|
||
(r"\b(?:BATLLEPASS|BATTLE\s*PASS|BATTLEPASS)\b", "Battlepass"),
|
||
(r"\bVENG(?:E)?FULL?\s+SWORD\s*S?MAN\b", "Vengeful Swordsman"),
|
||
(r"\bVENG(?:E)?FULL?\s+SWORD\b", "Vengeful Swordsman"),
|
||
(r"\bVENG(?:E)?FULL?\b(?!\s+SWORD)", "Vengeful Swordsman"),
|
||
(r"\b(?:FRIEND|FIEND)\s+GIRL\b", "Fiend Girl"),
|
||
(r"\bSKULL\s*(?:NIGHT|KNIGHT)\b", "Skull Knight"),
|
||
(r"\bSKELETON\s+KNIGHT\b", "Skull Knight"),
|
||
(r"\bSWITCH\s*BLADES?\b", "Nagumo"),
|
||
(r"\bSWITH\s*BLADES?\b", "Nagumo"),
|
||
(r"\bSWICTH\s*BLADES?\b", "Nagumo"),
|
||
(r"\bNAGOMO\b", "Nagumo"),
|
||
(r"\bNAGOMU\b", "Nagumo"),
|
||
(r"\bNAGUMO\b", "Nagumo"),
|
||
(r"\bDARK\s*(?:MAGES?|MAE)\b", "Dark Mage"),
|
||
(r"\bELF\s+MAGE\b", "Elf Mage"),
|
||
(r"\bELF\s+MAGES\b", "Elf Mage"),
|
||
(r"\bSLIVER\s+KING\b", "Silver King"),
|
||
(r"\bERZA\s+LIGHTING\b", "Erza Lightning"),
|
||
(r"\bMIST\s+NINJA\b", "Mist Ninja"),
|
||
(r"\b(?:HOMURU|HOMURA|HOMURUS)\b", "Homura"),
|
||
(r"\b(?:VIOLETINE|VIOLENTINE|VIOLENTIN|VIOLTINE|VIOLANTINE|VIOLENTE)\b", "Violentine"),
|
||
(r"\b(?:SOMBRE|SOMBER)\b", "Somber"),
|
||
(r"\b(?:POSIDON|POSIEDON|POSSEIDON|POSEIDON|POSIDEN|POSAIDON|POSIDEON|POSEDION)\b", "Poseidon"),
|
||
(r"\b(?:CHUNI|CHUNNI|CHUNII|CHUUNI|CHUUNII|CHUUNIS|CHUNNIS|SHUUNI)\b", "Chuuni"),
|
||
(r"\bBUDDHAS\b", "Buddha"),
|
||
(r"\bNAGUMOS\b", "Nagumo"),
|
||
(r"\bDAKR\s+MAGE\b", "Dark Mage"),
|
||
(r"\bDRAK\s+MAGE\b", "Dark Mage"),
|
||
(r"\bGLIGAMESH\b", "Gilgamesh"),
|
||
(r"\b(?:KILL\s*STREAK|KILLSTEAK|KILSTREAK|KILLSTRIKE)\b", "Killstreak"),
|
||
(r"\bMAMMY\b", "Mamy"),
|
||
(r"\bAIZENS\b", "Aizen"),
|
||
(r"\bALUCARDS\b", "Alucard"),
|
||
(r"\bBUDDA\b", "Buddha"),
|
||
(r"\b(?:BUDDAH|BUDHA|BUDA)\b", "Buddha"),
|
||
(r"\bRAUKAI\b", "Rukia"),
|
||
(r"\bANGLE\b", "Angel"),
|
||
(r"\bANGEL\b", "Angel"),
|
||
(r"\bMERLYN\b", "Merlin"),
|
||
(r"\bSAKAMUTO\b", "Sakamoto"),
|
||
(r"\bDAKY\b", "Daki"),
|
||
(r"\bDOFAMINGO\b", "Doflamingo"),
|
||
(r"\bISSAI\b", "Issei"),
|
||
(r"\bKILLSREAK\b", "Killstreak"),
|
||
(r"\bAVDO\b", "Avdol"),
|
||
(r"\bKOBENO\b", "Kobeni"),
|
||
(r"\bHIDON\b", "Hidan"),
|
||
(r"\bYAMOMOTO\b", "Yamamoto"),
|
||
(r"\bWEATHERGIRL\b", "Weather Girl"),
|
||
(r"\bSCARLED\s+SLAYER\b", "Scarlet Slayer"),
|
||
(r"\bSHARK\s+FIN\b", "Sharkfin"),
|
||
(r"\bIN\s+HUMAN\b", "Inhuman"),
|
||
(r"\bFLAME\s+FEATHER\b", "Flamefeather"),
|
||
(r"\bVENGEFULSWORDMAN\b", "Vengeful Swordsman"),
|
||
(r"\bVENGEFULSWORDSMAN\b", "Vengeful Swordsman"),
|
||
(r"\bVEGENFUL\s+SWORDSMAN\b", "Vengeful Swordsman"),
|
||
(r"\bVANDERFUL\s+SWORDSMAN\b", "Vengeful Swordsman"),
|
||
(r"\bVENGEFUL\s+SWORDSTMAN\b", "Vengeful Swordsman"),
|
||
(r"\bVENGEFUL\s+SWORDSMEN\b", "Vengeful Swordsman"),
|
||
(r"\bVIOLENTINR\b", "Violentine"),
|
||
(r"\bSHIZU\b", "Shizo"),
|
||
(r"\bHIDEN\b", "Hidan"),
|
||
(r"\bSOMBR\b", "Somber"),
|
||
(r"\bKAGURABACHI\b", "Kagura Bachi"),
|
||
(r"\bYOSHINO\b", "Yoshina"),
|
||
(r"\bMAGIC\s+GIRL\b", "Madoka"),
|
||
(r"\bINFINITY\s+MAGE\b", "Merlin"),
|
||
(r"\bVALENTINE\b(?!\s+BUNDLE)", "Violentine"),
|
||
(r"\bSAKA\b", "Sakamoto"),
|
||
(r"\bNAVI\b", "Nami"),
|
||
(r"\bHIME\b", "Himeno"),
|
||
(r"\bAKU\b", "Gaku"),
|
||
(r"\bOSARAGI\b", "Somber"),
|
||
(r"\bGOWTHER\b", "Doll"),
|
||
(r"\b(?:GILGA|GILG)\b", "Gilgamesh"),
|
||
(r"\bJIRAYA\b", "Jiraiya"),
|
||
(r"\bHEALTCLIFF\b", "Heathcliff"),
|
||
(r"\bHEATCLIFF\b", "Heathcliff"),
|
||
(r"\bDEER[- ]?TAN\b", "Deer Tan"),
|
||
(r"\b(?:ANDROID\s+21|A21)\b", "Android 21"),
|
||
(r"\bSHINY\b", "Shiny"),
|
||
(r"\b(?:YNEVO|UN[- ]?EVO|UNEVOLV(?:E|ED))\b", "Unevo"),
|
||
(r"\bEHO\b", "Evo"),
|
||
(r"\bEVOLVED\b", "Evo"),
|
||
(r"\bEVO\b", "Evo"),
|
||
*((rf"\b{name}\b", name.title()) for name in (
|
||
"AIZEN", "ALUCARD", "CHUUNI", "GILGAMESH", "BUDDHA", "DAZAI",
|
||
"CID", "HIDAN", "KANSAI", "CREAM", "SAKAMOTO", "SHARKFIN",
|
||
"INHUMAN", "EMILIA", "NAMI", "KOBENI", "HIMENO", "TENGEN",
|
||
"JIRAIYA", "AKI", "BOROS", "MADOKA", "YOSHINA", "DIO",
|
||
)),
|
||
)
|
||
)
|
||
KNOWN_UNIT_NAMES = tuple(sorted(
|
||
{name for _, name in UNIT_NAME_RULES if isinstance(name, str)}
|
||
- {"Shiny", "Shiny Skull Knight", "Battlepass", "Battlepasses",
|
||
"Overpay", "Overpays", "Evo", "Unevo"}
|
||
| {
|
||
"Nagumo", "Siren", "Frieren", "Rias", "Roger", "Avdol", "Unohana",
|
||
"Thorfinn", "Heathcliff", "Deer Tan", "Black Dog", "Golden King",
|
||
"Toad Sensei", "Gravity Mage", "Puppet Girl", "Ghost Lady",
|
||
"Death Ninja", "Ice Lily", "Illusionist", "Doflamingo", "Doffy",
|
||
"Viking", "Gohan", "Issei", "Mami", "Mamy", "Millie", "Merlin",
|
||
"Yamamoto", "Scarlet Slayer", "Flash Ninja", "Heart Princess",
|
||
"Angel", "Angel Devil", "Esdeath", "Erza", "Lucy", "Zabuza", "Kagura Bachi",
|
||
"Saki", "Gaku", "Rukia", "Hinami", "Julias", "Umbra", "Rohan",
|
||
"Daki", "Caesar", "Lelouch", "Flamingo", "Veko", "Ichigo",
|
||
"Mangaka", "Oshy", "Akeno", "Akena", "Bomb Angel", "Kisame",
|
||
"Karma", "Kaori", "Stitches", "Ghosty", "Icy Dragon",
|
||
"Lord Alien", "Lord Boros", "Dio OH", "Harribel", "Perona", "Power",
|
||
"Pain", "Robot", "Gas", "Doll", "Lulu", "Shizo", "Denji",
|
||
"Sea God", "Snake Princess", "Turtle Master", "Hammerhead",
|
||
"Isagi", "Kisuke", "Ging", "Ace", "Saikiki", "Blue Devil",
|
||
"Shade Hunter", "Android AAA", "Scarlet", "Shidou", "Emily",
|
||
"Ice Queen", "Enlightened", "Time Savior", "Toshiro", "Idol",
|
||
"Tiger", "Gin", "Ippo", "Boxer", "Dracula", "Sombra",
|
||
"Harribu", "Jio", "Messi", "Buggy", "Bunny", "Psychic Princess",
|
||
"Piccolo", "Weather Girl", "Flamefeather", "Blade Beast",
|
||
"Bubblegum", "Jelly",
|
||
},
|
||
key=lambda name: (-len(name.split()), -len(name), name),
|
||
))
|
||
UNIT_MENTION = re.compile(
|
||
r"(?<!\w)(?:" + "|".join(re.escape(name).replace(r"\ ", r"\s+")
|
||
for name in KNOWN_UNIT_NAMES) + r")(?!\w)",
|
||
re.I,
|
||
)
|
||
AUTOCORRECT_NAMES = tuple(sorted(
|
||
{name for name in KNOWN_UNIT_NAMES if len(name.replace(" ", "")) >= 5},
|
||
key=str.casefold,
|
||
))
|
||
AUTOCORRECT_EXACT = frozenset(name.casefold() for name in KNOWN_UNIT_NAMES)
|
||
|
||
|
||
def one_typo_apart(left: str, right: str) -> bool:
|
||
"""Accept one insertion, deletion, replacement, or adjacent swap."""
|
||
left, right = left.casefold(), right.casefold()
|
||
if left == right:
|
||
return False
|
||
if abs(len(left) - len(right)) > 1:
|
||
return False
|
||
if len(left) == len(right):
|
||
different = [i for i, (a, b) in enumerate(zip(left, right)) if a != b]
|
||
return len(different) == 1 or (
|
||
len(different) == 2 and different[1] == different[0] + 1
|
||
and left[different[0]] == right[different[1]]
|
||
and left[different[1]] == right[different[0]]
|
||
)
|
||
short, long = sorted((left, right), key=len)
|
||
return any(short == long[:i] + long[i + 1:] for i in range(len(long)))
|
||
|
||
|
||
@lru_cache(maxsize=4096)
|
||
def correct_unit_typo(name: str) -> str:
|
||
if name.casefold() in AUTOCORRECT_EXACT:
|
||
return name
|
||
matches = [known for known in AUTOCORRECT_NAMES if one_typo_apart(name, known)]
|
||
return matches[0] if len(matches) == 1 else name
|
||
|
||
|
||
def autocorrect_unit_names(value: str) -> str:
|
||
"""Correct one clear typo beside a variant cue or in a bare item."""
|
||
|
||
def before_status(match: re.Match[str]) -> str:
|
||
words = match.group("phrase").split()
|
||
for width in range(min(3, len(words)), 0, -1):
|
||
candidate = " ".join(words[-width:])
|
||
fixed = correct_unit_typo(candidate)
|
||
if fixed != candidate:
|
||
return " ".join(words[:-width] + [fixed]) + " " + match.group("status")
|
||
return match.group()
|
||
|
||
value = re.sub(
|
||
r"(?<!\w)(?P<phrase>[A-Za-z]+(?:\s+[A-Za-z]+){0,2})\s+"
|
||
r"(?P<status>Evo|Unevo)\b",
|
||
before_status, value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
r"\bShiny\s+(?P<name>[A-Za-z]+)\b(?=\s*(?:[|,;/)]|$))",
|
||
lambda m: "Shiny " + correct_unit_typo(m.group("name")), value, flags=re.I,
|
||
)
|
||
parts = value.split("|")
|
||
for index, part in enumerate(parts):
|
||
bare = re.fullmatch(
|
||
r"(?P<prefix>\s*(?:(?:x?\d+x?)\s+)?(?:Shiny\s+)?)"
|
||
r"(?P<name>[A-Za-z]+(?:\s+[A-Za-z]+){0,2})(?P<trailing>\s*)",
|
||
part, flags=re.I,
|
||
)
|
||
if bare:
|
||
parts[index] = (bare.group("prefix") + correct_unit_typo(bare.group("name")) +
|
||
bare.group("trailing"))
|
||
return "|".join(parts)
|
||
ALIASED_UNITS = ("Cid", "Mist Ninja", "Inhuman", "Aizen", "Elf Mage",
|
||
"Boros", "Poseidon", "Buddha", "Gilgamesh", "Alucard",
|
||
"Thorfinn", "Homura", "Sakamoto", "Shizo", "Doflamingo",
|
||
"Nagumo", "Rias", "Mamy", "Dark Mage", "Vengeful Swordsman",
|
||
"Harribel", "Violentine", "Dog Demon", "Heathcliff",
|
||
"Skull Knight")
|
||
_ALIAS_NAMES = "|".join(re.escape(name).replace(r"\ ", r"\s+")
|
||
for name in sorted(ALIASED_UNITS, key=len, reverse=True))
|
||
ALIAS_PAIR = re.compile(
|
||
r"(?<!\w)(?P<shiny1>Shiny\s+)?(?P<unit>" + _ALIAS_NAMES + r")"
|
||
r"(?P<status1>\s+(?:Evo|Unevo))?\s*(?P<sep>[/\-])\s*"
|
||
r"(?P<shiny2>Shiny\s+)?(?P=unit)"
|
||
r"(?P<status2>\s+(?:Evo|Unevo)|\s*\(\s*(?:Evo|Unevo)\s*\))?(?!\w)",
|
||
re.I,
|
||
)
|
||
ALIAS_PARENS = re.compile(
|
||
r"(?<!\w)(?P<shiny>Shiny\s+)?(?P<unit>" + _ALIAS_NAMES + r")"
|
||
r"(?P<status1>\s+(?:Evo|Unevo))?\s*\(\s*(?P<shiny2>Shiny\s+)?"
|
||
r"(?P=unit)(?P<status2>\s+(?:Evo|Unevo))?\s*\)",
|
||
re.I,
|
||
)
|
||
MAMY_ALIAS_CHAIN = re.compile(
|
||
r"(?<!\w)Shiny\s+(?:Mamy|Millie|Mami|Mammy)\s+(?:Evo|Unevo)"
|
||
r"(?:\s*/\s*|\s+)(?:Mamy|Millie|Mami|Mammy)\s+(?:Evo|Unevo)"
|
||
r"(?:(?:\s*/\s*|\s+)(?:Mamy|Millie|Mami|Mammy)\s+(?:Evo|Unevo))*",
|
||
re.I,
|
||
)
|
||
SHINY_NAMED_ALIAS = re.compile(
|
||
r"(?<!\w)Shiny\s+(?P<first>Hammerhead|Harribel|Mitsukai|Violentine|Inuyashu|Dog\s+Demon|Crusader|Heathcliff)"
|
||
r"(?P<status1>\s+(?:Evo|Unevo))?(?P<note>\s*\([^|()]{1,80}\))?\s*/\s*"
|
||
r"(?P<second>Hammerhead|Harribel|Mitsukai|Violentine|Inuyashu|Dog\s+Demon|Crusader|Heathcliff)"
|
||
r"(?P<status2>\s+(?:Evo|Unevo))?(?!\w)",
|
||
re.I,
|
||
)
|
||
JUDAR_PREFIX_ALIAS = re.compile(
|
||
r"(?<!\w)(?P<status>Evo|Unevo)\s+Dark\s+Mage\s*/\s*Judar"
|
||
r"(?:\s+(?P<other>Evo|Unevo))?(?!\w)",
|
||
re.I,
|
||
)
|
||
JUDAR_NOTE_ALIAS = re.compile(
|
||
r"(?<!\w)Dark\s+Mage\s+(?P<status>Evo|Unevo)"
|
||
r"(?P<note>\s*\([^|()]{1,80}\))\s*/\s*Judar"
|
||
r"(?:\s+(?P<other>Evo|Unevo))?(?!\w)",
|
||
re.I,
|
||
)
|
||
HEATHCLIFF_ADMIN_ALIAS = re.compile(
|
||
r"(?<!\w)(?P<shiny>Shiny\s+)?Heathcliff"
|
||
r"(?P<status>\s+(?:Evo|Unevo))?\s*\(\s*Admin\s*\)",
|
||
re.I,
|
||
)
|
||
DARK_MAGE_FALLEN_STAR_ALIAS = re.compile(
|
||
r"(?<!\w)(?P<shiny>Shiny\s+)?Dark\s+Mage"
|
||
r"(?P<status>\s+(?:Evo|Unevo))?\s*(?:[-–—]\s*)?"
|
||
r"(?:\(\s*Fallen\s+Star\s*\)|\bFallen\s+Star\b)",
|
||
re.I,
|
||
)
|
||
BUDDHA_NIRVANA_ALIAS = re.compile(
|
||
r"(?<!\w)(?P<shiny>Shiny\s+)?Buddha"
|
||
r"(?P<status>\s+(?:Evo|Unevo))?\s*(?:[-–—]\s*)?"
|
||
r"(?:\(\s*(?:Buddha\s+)?Nirvana\s*\)|(?:Buddha\s+)?Nirvana\b)",
|
||
re.I,
|
||
)
|
||
ALUCARD_UNHOLY_ALIAS = re.compile(
|
||
r"\s*\(\s*(?:Alucard\s+(?:Evo\s+)?)?Unholy\s+King\s*\)",
|
||
re.I,
|
||
)
|
||
SAKAMOTO_REDUNDANT_ALIAS = re.compile(
|
||
r"\s*\(\s*(?:Sakamoto(?:\s+Evo)?(?:\s+Prime)?|Prime)\s*\)",
|
||
re.I,
|
||
)
|
||
SAKAMOTO_PRIME_BARE = re.compile(
|
||
r"(?<!\w)(?P<shiny>Shiny\s+)?Sakamoto"
|
||
r"(?P<status>\s+(?:Evo|Unevo))?"
|
||
r"(?:\s*[-–—]\s*|\s+)Prime\b",
|
||
re.I,
|
||
)
|
||
AIZEN_TRANSCENDED_ALIAS = re.compile(
|
||
r"\s*\(\s*(?:Aizen\s+(?:Evo\s+)?)?Transcended\s*\)",
|
||
re.I,
|
||
)
|
||
AIZEN_TRANSCENDED_BARE = re.compile(
|
||
r"(?<!\w)(?P<shiny>Shiny\s+)?Aizen"
|
||
r"(?P<status>\s+(?:Evo|Unevo))?"
|
||
r"(?:\s*[-–—]\s*|\s+)Transcended\b",
|
||
re.I,
|
||
)
|
||
CID_NUCLEAR_ALIAS = re.compile(
|
||
r"\s*\(\s*(?:Cid\s+(?:Evo\s+)?)?Nuclear\s*\)",
|
||
re.I,
|
||
)
|
||
CID_NUCLEAR_BARE = re.compile(
|
||
r"(?<!\w)(?P<shiny>Shiny\s+)?Cid"
|
||
r"(?P<status>\s+(?:Evo|Unevo))?"
|
||
r"(?:\s*[-–—]\s*|\s+)Nuclear\b",
|
||
re.I,
|
||
)
|
||
GILGAMESH_HEROES_ALIAS = re.compile(
|
||
r"\s*\(\s*(?:Gilgamesh\s+(?:Evo\s+)?)?Lord\s+of\s+Heroes\s*\)",
|
||
re.I,
|
||
)
|
||
GILGAMESH_HEROES_BARE = re.compile(
|
||
r"(?<!\w)(?P<shiny>Shiny\s+)?Gilgamesh"
|
||
r"(?P<status>\s+(?:Evo|Unevo))?"
|
||
r"(?:\s*[-–—]\s*|\s+)Lord\s+of\s+Heroes\b",
|
||
re.I,
|
||
)
|
||
INHUMAN_NULLIFIER_ALIAS = re.compile(
|
||
r"\s*\(\s*(?:Inhuman\s+(?:Evo\s+)?)?Nullifier\s*\)",
|
||
re.I,
|
||
)
|
||
INHUMAN_NULLIFIER_BARE = re.compile(
|
||
r"(?<!\w)(?P<shiny>Shiny\s+)?Inhuman"
|
||
r"(?P<status>\s+(?:Evo|Unevo))?"
|
||
r"(?:\s*[-–—]\s*|\s+)Nullifier\b",
|
||
re.I,
|
||
)
|
||
POSEIDON_TYRANT_ALIAS = re.compile(
|
||
r"\s*\(\s*(?:Poseidon\s+(?:Evo\s+)?)?Tyrant\s+of\s+the\s+Seas\s*\)",
|
||
re.I,
|
||
)
|
||
POSEIDON_TYRANT_BARE = re.compile(
|
||
r"(?<!\w)(?P<shiny>Shiny\s+)?Poseidon"
|
||
r"(?P<status>\s+(?:Evo|Unevo))?"
|
||
r"(?:\s*[-–—]\s*|\s+)Tyrant\s+of\s+the\s+Seas\b",
|
||
re.I,
|
||
)
|
||
BLACK_DOG_HELLHOUND_ALIAS = re.compile(
|
||
r"\s*\(\s*(?:Black\s+Dog\s+(?:Evo\s+)?)?Hellhound\s*\)",
|
||
re.I,
|
||
)
|
||
BLACK_DOG_HELLHOUND_BARE = re.compile(
|
||
r"(?<!\w)(?P<shiny>Shiny\s+)?Black\s+Dog"
|
||
r"(?P<status>\s+(?:Evo|Unevo))?"
|
||
r"(?:\s*[-–—]\s*|\s+)Hellhound\b",
|
||
re.I,
|
||
)
|
||
BLACK_DOG_POSTFIX_SHINY = re.compile(
|
||
r"(?<!\w)Black\s+Dog(?P<status>\s+(?:Evo|Unevo))?\s+Shiny\b",
|
||
re.I,
|
||
)
|
||
ELF_MAGE_AURA_ALIAS = re.compile(
|
||
r"\s*\(\s*(?:Elf\s+Mage\s+(?:Evo\s+)?)?Aura\s*\)",
|
||
re.I,
|
||
)
|
||
ELF_MAGE_AURA_BARE = re.compile(
|
||
r"(?<!\w)(?P<shiny>Shiny\s+)?Elf\s+Mage"
|
||
r"(?P<status>\s+(?:Evo|Unevo))?"
|
||
r"(?:\s*[-–—]\s*|\s+)Aura\b",
|
||
re.I,
|
||
)
|
||
ELF_MAGE_POSTFIX_SHINY = re.compile(
|
||
r"(?<!\w)Elf\s+Mage(?P<status>\s+(?:Evo|Unevo))?\s+Shiny\b",
|
||
re.I,
|
||
)
|
||
KNOWN_SHINY_UNITS = tuple(tuple(name.casefold().split()) for name in KNOWN_UNIT_NAMES)
|
||
EVO_STATUS = re.compile(r"\b(?:Evo|Unevo)\b", re.I)
|
||
CONTACT_ADDRESS = re.compile(
|
||
r"(?:\b(?:delivered\s+with|sent\s+via)\s+)?"
|
||
r"(?:https?://[^\s|]+|[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}|"
|
||
r"[A-Za-z0-9_-]+(?:\{dot\}|\.)[A-Za-z]{2,})",
|
||
re.IGNORECASE,
|
||
)
|
||
CONTACT_REQUEST = re.compile(
|
||
r"\b(?:SEND\s+FRIENDS?\s+REQ(?:UEST)?\s+IF\s+U\s+CANT\s+DMS|DM\s+OFFERS?)\b",
|
||
re.I,
|
||
)
|
||
OFFER_HEADING = re.compile(r"(?:^|(?<=\|))\s*(?:/\s*)?(?:TRADING|FLIPPING|IN\s+STOCK)\s*[:=]?\s*", re.I)
|
||
FRIEND_BOUNDARY = re.compile(
|
||
r"(?:^|(?<=\|))\s*friends?\s*:?(?=\s*\||\s*$)|"
|
||
r"(?:^|(?<=\|))\s*friends?\s*:\s*(?=\S)",
|
||
re.I,
|
||
)
|
||
FRIEND_FIELD = re.compile(r"(?:^|(?<=\|))\s*friends?\s*(?=\||$)", re.I)
|
||
NFL_LABEL = re.compile(r"(?<!\w)NFL\s*[:=\-]?\s*", re.I)
|
||
CHALLENGE_NOTE = re.compile(
|
||
r"\(?\s*\bup\s+from\s+[^|)\n]{1,100}?\s+to\s+[^|)\n]{1,100}\)?",
|
||
re.I,
|
||
)
|
||
REPORT_HANDLE = re.compile(r"(?<![\w@])@[A-Za-z0-9_.-]{2,32}(?:#\d{4})?")
|
||
SCAM_LIST_HEADING = re.compile(r"^\s*scammers?\s+list\s*:\s*(.*)$", re.I)
|
||
SCAM_LIST_HANDLES = re.compile(
|
||
r"\s*@[A-Za-z0-9_.-]{2,32}(?:#\d{4})?"
|
||
r"(?:\s*[/,;|]\s*@[A-Za-z0-9_.-]{2,32}(?:#\d{4})?)*\s*"
|
||
)
|
||
SCAM_WARNING_START = re.compile(
|
||
r"\bscamm?er\s+@[A-Za-z0-9_.-]{2,32}|"
|
||
r"['\"`]?@[A-Za-z0-9_.-]{2,32}['\"`]?"
|
||
r"(?:\s+\(@[A-Za-z0-9_.-]{2,32}\))?"
|
||
r"\s+(?:is|was)\s+(?:a\s+)?scamm?er\b",
|
||
re.I,
|
||
)
|
||
NON_TRADE_NOTICES = re.compile(
|
||
r"\(?\s*(?:NO\s+(?:ANSWER|REPLY)\s*=\s*(?:AFK|ASLEEP)|"
|
||
r"WILL\s+REPLY\s+AS\s+SOON\s+AS\s+POSSIBLE\s+BUT\s+MAY\s+BE\s+ASLEEP|"
|
||
r"ANY\s+OFFERS\s+I\s+REPLY\s+TO\s+ALL,?\s+"
|
||
r"YOU\s+DONT\s+HAVE\s+TO\s+COME\s+WITH\s+ONE\s+BUT\s+ITS\s+PREFERRED|"
|
||
r"I(?:['’]?LL|\s+WILL)?\s+ALWAYS\s+(?:RESPOND|REPLY)|"
|
||
r"I\s+REPLY\s+TO\s+ALL(?:\s+OFFERS?)?|"
|
||
r"(?:OFFER\s*:\s*|DROP\s+OFFER\s*/\s*)?"
|
||
r"I\s+(?:DO\s+NOT|DON['’]?T)\s+OFFER|"
|
||
r"I(?:['’]?M|\s+AM)\s+REALLY\s+FRIENDLY|"
|
||
r"(?:ALL|ANY)\s+OFFERS?(?:\s+ALL)?\s+(?:(?:ARE|IS)\s+)?WELCOME"
|
||
r"(?:\s+WILL\s+RESPOND\s+TO\s+ALL)?|"
|
||
r"(?:I\s+|WILL\s+)?RESPOND\s+TO\s+ALL\s+OFFERS?|"
|
||
r"(?:PLS+\s+)?DM\s+ME\s+(?:IF\s+U\s+HAVE\s+(?:AN?\s+)?OFFER|"
|
||
r"FOR\s+TRADE|YOUR\s+OFFERS)|"
|
||
r"SCC?AMM?ERS?/BEGGARS\s+DONT\s+BOR?THER|"
|
||
r"DONT\s+COME\s+WITH\s+SHIT\s+OFFERS|"
|
||
r"I\s+AM\s+NOT\s+A\s+LINK\s+SENDER)\s*[.!?]*\s*\)?",
|
||
re.IGNORECASE,
|
||
)
|
||
INPUT_EXTENSIONS = {".txt", ".md", ".log"}
|
||
|
||
# Order matters: MLF/NLF must never be interpreted as simple LF.
|
||
LABEL = re.compile(
|
||
r"(?<![\w])(?P<label>mostly\s+looking\s+for|not\s+looking\s+for|"
|
||
r"looking\s+for|trading|flipping|in\s+stock|mlf|nlf|nfl|lf)(?![\w])\s*[:=\-]?\s*",
|
||
re.IGNORECASE,
|
||
)
|
||
TRADE_AT_LINE_START = re.compile(r"^(?:[\s|*~\-]*)(?:trade)\b\s*[:=\-]?\s*", re.I)
|
||
LOOKING_AT_LINE_START = re.compile(r"^looking\b(?!\s+for\b)\s*[:=\-]?\s*", re.I)
|
||
INLINE_FOR = re.compile(r"\bfor\b", re.I)
|
||
INLINE_OFFER_ITEM = re.compile(
|
||
r"\b(?:Fodder Units|battlepass(?:es)?|bundles?|gamepass(?:es)?|"
|
||
r"display\s+\d+\s+units?|rrs?|rerolls?|sss|stats?|skins?|"
|
||
r"relics?|items?|limit\s+break\s+unit|hunter)\b|\b\d+\s*rrs?\b", re.I,
|
||
)
|
||
INLINE_REQUEST = re.compile(
|
||
r"\b(?:offers?|upgrades?|downgrades?|overpays?|battlepass(?:es)?|"
|
||
r"bundles?|gamepass(?:es)?|gp|rrs?|rerolls?|sss|ss\+?|stats?|"
|
||
r"spa|dmg|damage|range|rng|skins?|relics?|items?|units?|"
|
||
r"adds?|anything|hunter|grand\s+return)\b", re.I,
|
||
)
|
||
INLINE_FOR_PURPOSE = re.compile(
|
||
r"^(?:sacrifice|limit\s+break|moderators?|server\s+boosters?|"
|
||
r"content\s+creators?|fair\s+trade|trading\b)", re.I,
|
||
)
|
||
GENERIC_REQUEST = re.compile(
|
||
r"^(?:any\s+)?(?:offers?|upgrades?|overpays?|downgrades?)"
|
||
r"(?:\s*[/,&+]\s*(?:offers?|upgrades?|overpays?|downgrades?))*\s*[!?.]*$",
|
||
re.I,
|
||
)
|
||
BOILERPLATE = re.compile(
|
||
r"^(?:weitergeleitet|forwarded|feel free to offer.*|dm me.*|"
|
||
r"i'?m not offering.*|open to all offers.*|dm if .*|send offers?.*|"
|
||
r"\(?come with an offer.*|units?|inv|inventory|unit \(all evo\))$",
|
||
re.I,
|
||
)
|
||
NON_ITEM_OFFER = re.compile(
|
||
r"^(?:channel\s+for\b.*|market\s+in\s+bio|"
|
||
r"have\s+units\s+to\s+sell\s+or\s+cross\s+trade\b.*|"
|
||
r"(?:please\s+use\b|total\s+value\s*:)\s*.*|"
|
||
r"i\s+can\s+also\s+buy\s+things\s+for\s+robux|"
|
||
r"(?:i\s+answer|i\s+respond)\s+.*|im\s+real\s+human\b.*|"
|
||
r"(?:no\s+response|ignore)\s*=\s*nty|"
|
||
r"(?:first\s+of\s+all\s+)?read\s+tiers|"
|
||
r"(?:no|not\s+looking\s+for)\s+shiny\s+units?|"
|
||
r"willing\s+to\s+(?:down|up)grade\b.*|"
|
||
r"(?:just|or\s+send|bring\s+an?|come\s+with\s+an?)\s+offers?\b.*|"
|
||
r"just\s+offer\s*/\s*dm\s+me|"
|
||
r"(?:all\s+evoed|all\s+of\s+this\s+are\s+evo|"
|
||
r"all\s+units?\s+(?:are\s+evolve|have\s+good\s+stats?)|"
|
||
r"all\s+good\s+stat)|"
|
||
r"these\s+all\s+till\s+i\s+get\b.*|"
|
||
r"(?:way\s+to|until)\s+\w+\s+evo\b.*|"
|
||
r"dont\s+.*?\s+evo\s+unless\b.*|"
|
||
r"(?:any\s+offer\s+is\s+appreciated|taking\s+offers|"
|
||
r"reply\s+to\s+all\s+dms|will\s+reply\s+to\s+any\s+offers|"
|
||
r"feel\s+free\s+to+\s+offer|pls\s+come\s+with\s+an?\s+offer|"
|
||
r"come\s+with\s+offer|"
|
||
r"\(?\s*looking\s+for\s+offers\s+on\s+my\s+unit\s*\)?)|"
|
||
r"(?:also|only|just|pre|pre-trade|offer|offers|my\s+offer|"
|
||
r"what\s+im|i\s+need|for\?|to\s+end|"
|
||
r"-?\s*\(\s*(?:units?|stats?|rr|bundles?|gamepass)\s*\)\s*-?|"
|
||
r"\(?\s*lf\s+offers?\s+too\s*\)?))\s*[:/?.]*$",
|
||
re.I,
|
||
)
|
||
OFFER_TIMESTAMP = re.compile(r"\d+\s*[•·]\s*\d{1,2}:\d{2}")
|
||
REQUEST_META = re.compile(
|
||
r"^(?:also|only|\(\s*lf\s*\)|keyword\s*:|"
|
||
r"\(message:\s*i\s+have\b.*|no\s+give\s+offer|"
|
||
r"this\s+post\s+was\s+sent\s+by|"
|
||
r"\(?\s*no\s+i\s+am\s+not\s+a\s+bot\s*\)?|"
|
||
r"(?:no\s+reply|no\s+response)\s*=\s*nty|"
|
||
r"(?:ignore\s*=\s*(?:nty|afk)|nty\s*=\s*ignore)\b.*|"
|
||
r"(?:i\s+respond|will\s+always\s+try\s+to\s+respond|"
|
||
r"will\s+read\s+all\s+dms|reply\s+to\s+all\s+dms)\b.*|"
|
||
r"(?:ill\s+respond\s+everyone|\+?\s*i['’]?ll\s+reply\s+to\s+all\s+dm)\b.*|"
|
||
r"(?:i\s+dont\s+make\s+an?\s+offer|im\s+not\s+making\s+offers)\b.*|"
|
||
r"dont\s+even\s+try\s+to\s+scam\s+me\b.*|"
|
||
r"no\s+pearn\s+scam|just\s+dm\s+me|"
|
||
r"(?:scammer\s+list|people\s+who\s+ask\s+if\s+they\s+may\s+offer)\b.*|"
|
||
r"(?:ignoring\s+clowns|clown|i\s+dont\s+make\s+offer)\b.*|"
|
||
r"i\s+won.t\s+offer\s+for\s+ur\s+units/items\b.*|"
|
||
r"please\s+dm\s+me\s+with\s+an\s+offer\b.*|"
|
||
r"dm\s+for\s+pics/offer|"
|
||
r"send\s+me\s+offers|"
|
||
r"(?:scammers?|switching\s+shiny\s+scammer|scammer\s+percentage)\s*:.+|"
|
||
r"(?:come\s+with\s+offers?(?:\s+please)?|just\s+dm\s+me|"
|
||
r"drop\s+ur\s+offer,?\s*im\s+not\s+offering|friend\s*#\s*\d+|"
|
||
r"i\s+don.?t\s+bite\s+send\s+whatever)\b.*|"
|
||
r"(?:please\s+come\s+to\s+my|feel\s+free\s+to\s+Dark\s+Mage\s+Evo)\b.*i\s+don.?t\s+bite.*|"
|
||
r"@[\w.-]+(?:\s+@?[\w.()@-]+)*|"
|
||
r"[\W_]+)$", re.I,
|
||
)
|
||
EMBEDDED_REQUEST_LABEL = re.compile(r"\(\s*(MLF|NLF|NFL)\s*:?\s*([^()]*)\)", re.I)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class Message:
|
||
author: str
|
||
body: str
|
||
|
||
|
||
def is_dyno_message(msg: Message) -> bool:
|
||
"""Identify Dyno by its Discord author, never by text in a user's offer."""
|
||
identity = msg.author.casefold()
|
||
return bool(re.fullmatch(
|
||
r"(?:display:dyno(?:#\d{4}|\s*\(bot\))?|handle:dyno(?:\.gg)?)",
|
||
identity,
|
||
))
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class ScamWarning:
|
||
reported_handles: str
|
||
warning_text: str
|
||
reporter_hash: str
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class Listing:
|
||
author: str
|
||
offer: str
|
||
lf: str = ""
|
||
mlf: str = ""
|
||
nlf: str = ""
|
||
|
||
@property
|
||
def looking_for(self) -> str:
|
||
# Compatibility with the original offer,looking_for CSV.
|
||
# Label MLF so it is not confused with ordinary LF requests.
|
||
if self.lf and self.mlf:
|
||
return f"{self.lf} | MLF: {self.mlf}"
|
||
if self.mlf:
|
||
return f"MLF: {self.mlf}"
|
||
return self.lf
|
||
|
||
|
||
def tidy_line(raw: str) -> str:
|
||
line = "".join(
|
||
ch for ch in html.unescape(raw) if unicodedata.category(ch) != "Cf"
|
||
)
|
||
line = re.sub(r"^\s*#{1,6}\s+", "", line)
|
||
# Clear markdown formatting without damaging stats such as S-/S+/SSS.
|
||
line = line.replace("**", "").replace("__", "").replace("`", "")
|
||
line = line.replace("*:*", ":")
|
||
return line.strip()
|
||
|
||
|
||
def author_from_header(value: str) -> tuple[str, str]:
|
||
"""Return a stable author identity and any inline text after header colon."""
|
||
value = tidy_line(value).strip(" ,")
|
||
inline = ""
|
||
# With handle: a colon after role / handle can precede text on same line.
|
||
match = re.search(r":\s+(?=\S)", value)
|
||
if match:
|
||
inline = value[match.end():].strip()
|
||
value = value[:match.start()]
|
||
value = re.sub(r"\s*\[[^\]\n]{0,70}\]\s*$", "", value).strip(" :*,")
|
||
handle = HANDLE.search(value)
|
||
if handle:
|
||
return "handle:" + handle.group(1).strip().casefold(), inline
|
||
return "display:" + value.casefold(), inline
|
||
|
||
|
||
def legacy_header(line: str) -> tuple[str, str] | None:
|
||
match = INLINE_HEADER.fullmatch(line)
|
||
if not match:
|
||
return None
|
||
rest = match.group("rest")
|
||
if rest.casefold().startswith(("trading ", "lf ", "mlf ", "nlf ")):
|
||
return None
|
||
return author_from_header(rest)
|
||
|
||
|
||
def iter_messages(lines: Iterable[str]) -> Iterator[Message]:
|
||
"""Stream user messages using either Discord's split or compact headers.
|
||
|
||
Only a few lines of lookahead are buffered; entire files aren't loaded.
|
||
"""
|
||
source = iter(tidy_line(line) for line in lines)
|
||
buffered: list[str] = []
|
||
author: str | None = None
|
||
body: list[str] = []
|
||
|
||
def peek(index: int) -> str | None:
|
||
while len(buffered) <= index:
|
||
try:
|
||
buffered.append(next(source))
|
||
except StopIteration:
|
||
return None
|
||
return buffered[index]
|
||
|
||
def take() -> str | None:
|
||
if peek(0) is None:
|
||
return None
|
||
return buffered.pop(0)
|
||
|
||
def finish() -> Message | None:
|
||
text = "\n".join(body).strip()
|
||
if not text:
|
||
return None
|
||
message = Message(author or "unknown:" + uuid.uuid4().hex, text)
|
||
return None if is_dyno_message(message) else message
|
||
|
||
while peek(0) is not None:
|
||
p0 = peek(0)
|
||
assert p0 is not None
|
||
split_timestamp = (
|
||
p0 == "[" and (peek(1) is not None and bool(TIME.fullmatch(peek(1) or "")))
|
||
and peek(2) == "]"
|
||
)
|
||
full_timestamp = bool(BRACKETED_TIME.fullmatch(p0))
|
||
header = legacy_header(p0) if not split_timestamp and not full_timestamp else None
|
||
|
||
if split_timestamp or full_timestamp or header:
|
||
prior = finish()
|
||
if prior:
|
||
yield prior
|
||
body = []
|
||
author = None
|
||
if split_timestamp:
|
||
take(); take(); take()
|
||
elif full_timestamp:
|
||
take()
|
||
if header is not None:
|
||
take()
|
||
author, inline = header
|
||
if inline:
|
||
body.append(inline)
|
||
else:
|
||
while peek(0) == "":
|
||
take()
|
||
next_line = take()
|
||
if next_line is not None:
|
||
author, inline = author_from_header(next_line)
|
||
if inline:
|
||
body.append(inline)
|
||
if peek(0) == ":":
|
||
take()
|
||
continue
|
||
body.append(take() or "")
|
||
|
||
last = finish()
|
||
if last:
|
||
yield last
|
||
|
||
|
||
def extract_scam_warnings(msg: Message) -> tuple[Message, list[ScamWarning]]:
|
||
"""Keep reported allegations separate from the surrounding trade text."""
|
||
kept_lines: list[str] = []
|
||
warnings: list[ScamWarning] = []
|
||
lines = msg.body.splitlines()
|
||
index = 0
|
||
while index < len(lines):
|
||
raw = lines[index]
|
||
heading = SCAM_LIST_HEADING.fullmatch(raw)
|
||
if heading:
|
||
list_lines = [heading.group(1)] if heading.group(1) else []
|
||
next_index = index + 1
|
||
while next_index < len(lines):
|
||
candidate = lines[next_index].strip()
|
||
if not candidate:
|
||
next_index += 1
|
||
continue
|
||
if not SCAM_LIST_HANDLES.fullmatch(candidate):
|
||
break
|
||
list_lines.append(candidate)
|
||
next_index += 1
|
||
handles = list(dict.fromkeys(
|
||
match.group()[1:] for line in list_lines
|
||
for match in REPORT_HANDLE.finditer(line)
|
||
))
|
||
if handles:
|
||
warnings.append(ScamWarning(" | ".join(handles),
|
||
"Scammer List: " + " / ".join(list_lines),
|
||
hash_author(msg.author)))
|
||
index = next_index
|
||
continue
|
||
index += 1
|
||
fragments = raw.split("|")
|
||
kept_fragments: list[str] = []
|
||
found = False
|
||
for fragment in fragments:
|
||
match = SCAM_WARNING_START.search(fragment)
|
||
if not match:
|
||
kept_fragments.append(fragment)
|
||
continue
|
||
warning_text = tidy_line(fragment[match.start():])
|
||
handles = list(dict.fromkeys(
|
||
handle.group()[1:].rstrip(".,;:")
|
||
for handle in REPORT_HANDLE.finditer(warning_text)
|
||
))
|
||
if not handles:
|
||
kept_fragments.append(fragment)
|
||
continue
|
||
warnings.append(ScamWarning(" | ".join(handles), warning_text,
|
||
hash_author(msg.author)))
|
||
prefix = fragment[:match.start()].strip()
|
||
if prefix:
|
||
kept_fragments.append(prefix)
|
||
found = True
|
||
if found:
|
||
line = " | ".join(part.strip() for part in kept_fragments if part.strip())
|
||
if line:
|
||
kept_lines.append(line)
|
||
else:
|
||
kept_lines.append(raw)
|
||
return Message(msg.author, "\n".join(kept_lines)), warnings
|
||
|
||
|
||
def remove_emoji_codes(value: str) -> str:
|
||
return LEGACY_BARE_EMOJI.sub(" ", EMOJI_CODE.sub(" ", value))
|
||
|
||
|
||
def remove_unicode_emoji(value: str) -> str:
|
||
value = KEYCAP_EMOJI.sub(" ", value)
|
||
return "".join(
|
||
ch for ch in value
|
||
if unicodedata.category(ch) not in {"So", "Sk", "Cf"}
|
||
and ch not in EMOJI_PUNCTUATION
|
||
and ord(ch) not in {0xFE0E, 0xFE0F, 0x20E3}
|
||
and not 0xE0100 <= ord(ch) <= 0xE01EF
|
||
)
|
||
|
||
|
||
def remove_decorative_marks(value: str) -> str:
|
||
return DECORATIVE_MARKS.sub(" ", value)
|
||
|
||
|
||
def remove_non_trade_notices(value: str) -> str:
|
||
value = CHALLENGE_NOTE.sub(" ", value)
|
||
value = NON_TRADE_NOTICES.sub(" ", value)
|
||
value = CONTACT_REQUEST.sub(" ", value)
|
||
return CONTACT_ADDRESS.sub(" ", value)
|
||
|
||
|
||
def normalize_fodder_units(value: str) -> str:
|
||
"""Keep fodders as an item class without assuming an evolution status."""
|
||
value = re.sub(
|
||
rf"\b(?P<count>(?:x\d+|\d+x|\d+))\s+Unevo\s+units?\s*/\s*"
|
||
rf"(?:{FODDER_NAME.pattern})",
|
||
lambda match: match.group("count") + " Fodder Units Unevo",
|
||
value, flags=re.I,
|
||
)
|
||
value = FODDER_MYTHICS.sub("Fodder Units", value)
|
||
value = FODDER_NAME.sub("Fodder Units", value)
|
||
def collapse_fodder_alias(match: re.Match[str]) -> str:
|
||
if not (FODDER_ALIAS_NAMES.fullmatch(match.group("left")) or
|
||
FODDER_ALIAS_NAMES.fullmatch(match.group("right"))):
|
||
return match.group()
|
||
status1 = (match.group("status1") or "").strip().capitalize()
|
||
status2 = (match.group("status2") or "").strip().capitalize()
|
||
if status1 and status2 and status1 != status2:
|
||
return match.group() # Keep distinct variants.
|
||
return "Fodder Units" + (" " + (status1 or status2) if status1 or status2 else "")
|
||
|
||
value = FODDER_ALIAS_PAIR.sub(collapse_fodder_alias, value)
|
||
value = FODDER_ALIAS_NAMES.sub("Fodder Units", value)
|
||
def move_status(match: re.Match[str]) -> str:
|
||
if re.search(r"\bFodder Units\s*$", value[:match.start()], re.I):
|
||
return match.group() # The status belongs to the first variant.
|
||
previous = list(UNIT_MENTION.finditer(value, 0, match.start()))
|
||
if previous and not value[previous[-1].end():match.start()].strip():
|
||
return match.group() # The status may belong to that unit.
|
||
return "Fodder Units " + match.group("status").capitalize()
|
||
|
||
value = re.sub(
|
||
r"\b(?P<status>Evo|Unevo)\s*/?\s*Fodder Units\b",
|
||
move_status,
|
||
value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
r"\bFodder Units\s*\(\s*(?P<status>Evo|Unevo)\s*\)",
|
||
lambda match: "Fodder Units " + match.group("status").capitalize(),
|
||
value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
r"\bFodder Units\s+(?P<count>\d+\+?)\s+(?P<status>Evo|Unevo)\b",
|
||
lambda match: match.group("count") + " Fodder Units " +
|
||
match.group("status").capitalize(),
|
||
value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
r"\bFodder Units\s*\(\s*(\d+)\s+(Evo|Unevo)\s+(\d+)\s+(Evo|Unevo)\s*\)",
|
||
lambda match: "Fodder Units (" + match.group(1) + " " +
|
||
match.group(2).capitalize() + ", " + match.group(3) + " " +
|
||
match.group(4).capitalize() + ")",
|
||
value, flags=re.I,
|
||
)
|
||
return value
|
||
|
||
|
||
def normalize_unit_names(value: str) -> str:
|
||
value = re.sub(r"(?<!\w)×\s*(\d+)(?=\s+\w)", r"\1x", value)
|
||
value = re.sub(r"\b(\d+)\s*×\s*(?=\w)", r"\1x ", value)
|
||
value = re.sub(r"\bInfinity\s+Mage\s*/\s*Merlin\s+(Evo|Unevo)\b",
|
||
lambda m: "Merlin " + m.group(1).capitalize(), value, flags=re.I)
|
||
value = re.sub(r"\bShiny(?=Heathcliff\b)", "Shiny ", value, flags=re.I)
|
||
value = re.sub(r"\b(\d+)x(?=Chuuni\b|Nagumo\b|DM\b)", r"\1x ", value, flags=re.I)
|
||
value = re.sub(r"\b(\d+)(?=Nagumo\b|DM\b)", r"\1x ", value, flags=re.I)
|
||
def collapse_shiny_named_alias(match: re.Match[str]) -> str:
|
||
if match.group("first").casefold() == match.group("second").casefold():
|
||
return match.group()
|
||
canonical_names = {
|
||
"hammerhead": "Harribel", "harribel": "Harribel",
|
||
"mitsukai": "Violentine", "violentine": "Violentine",
|
||
"inuyashu": "Dog Demon", "dog demon": "Dog Demon",
|
||
"crusader": "Heathcliff", "heathcliff": "Heathcliff",
|
||
}
|
||
first = canonical_names[match.group("first").casefold()]
|
||
second = canonical_names[match.group("second").casefold()]
|
||
if first != second:
|
||
return match.group()
|
||
status1 = (match.group("status1") or "").strip().capitalize()
|
||
status2 = (match.group("status2") or "").strip().capitalize()
|
||
if status1 and status2 and status1 != status2:
|
||
return match.group()
|
||
status = status1 or status2
|
||
return "Shiny " + first + (" " + status if status else "") + (match.group("note") or "")
|
||
|
||
def collapse_judar_alias(match: re.Match[str]) -> str:
|
||
status = match.group("status").capitalize()
|
||
other = match.group("other")
|
||
if other and other.casefold() != status.casefold():
|
||
return match.group()
|
||
if "note" in match.groupdict():
|
||
return "Dark Mage " + status + match.group("note")
|
||
return status + " Dark Mage"
|
||
|
||
def collapse_mamy_aliases(match: re.Match[str]) -> str:
|
||
names = re.findall(r"\b(?:Mamy|Millie|Mami|Mammy)\b", match.group(), re.I)
|
||
statuses = re.findall(r"\b(?:Evo|Unevo)\b", match.group(), re.I)
|
||
if (len({name.casefold() for name in names}) == 1 or
|
||
len({status.casefold() for status in statuses}) != 1):
|
||
return match.group()
|
||
return "Shiny Mamy " + statuses[0].capitalize()
|
||
|
||
value = SHINY_NAMED_ALIAS.sub(collapse_shiny_named_alias, value)
|
||
value = JUDAR_PREFIX_ALIAS.sub(collapse_judar_alias, value)
|
||
value = JUDAR_NOTE_ALIAS.sub(collapse_judar_alias, value)
|
||
value = MAMY_ALIAS_CHAIN.sub(collapse_mamy_aliases, value)
|
||
for pattern, canonical in UNIT_NAME_RULES:
|
||
value = pattern.sub(canonical, value)
|
||
value = autocorrect_unit_names(value)
|
||
value = re.sub(r"\b(?:1\s+)?Evo\s+Shiny\s+Somber\s*\(\s*Somber Evo\s*\)",
|
||
"1x Shiny Somber Evo", value, flags=re.I)
|
||
value = re.sub(r"\bEvo\s+Shiny\s+Doll\s*\(\s*Doll Evo\s*\)",
|
||
"Shiny Doll Evo", value, flags=re.I)
|
||
value = re.sub(r"\bShiny\s+Doll\s*\(\s*Doll Evo\s*\)",
|
||
"Shiny Doll Evo", value, flags=re.I)
|
||
value = re.sub(r"\bShiny\s+(Somber|Doll)\s*(?:Evo\s*)?/\s*\1\s+Evo\b",
|
||
lambda m: "Shiny " + m.group(1).title() + " Evo", value, flags=re.I)
|
||
value = re.sub(r"\bShiny\s+Skull\s+Knight\s+Evo\s*/\s*Skull\s+Knight(?:\s+Evo)?\b",
|
||
"Shiny Skull Knight Evo", value, flags=re.I)
|
||
value = re.sub(r"\bDeer\s+Tan\s+Evo\s+Shiny\s+AND\s+NON\b",
|
||
"Shiny Deer Tan Evo | Deer Tan Evo", value, flags=re.I)
|
||
value = re.sub(r"\bCid\s+Evo\s+Shiny\s+Unevo\b",
|
||
"Shiny Cid Evo", value, flags=re.I)
|
||
value = re.sub(r"\bJin\s+Mori\s*\(\s*Shiny\s*\)",
|
||
"Shiny Jin Mori", value, flags=re.I)
|
||
value = re.sub(r"\bGreen\s+alien\s*\(\s*Shiny\s*\)",
|
||
"Shiny Green Alien", value, flags=re.I)
|
||
value = re.sub(r"\bDeer\s+Tan\s+Evo\s*/\s*noko\s+tan\s*\(\s*Shiny\s*\)",
|
||
"Shiny Deer Tan Evo", value, flags=re.I)
|
||
value = re.sub(r"\bDark\s+Mage\s+Evo\s+Shiny\b",
|
||
"Shiny Dark Mage Evo", value, flags=re.I)
|
||
value = re.sub(r"\bUnevo\s+Shiny\s+Vanilla\s+Ice\s*\(\s*Cream Evo\s*\)",
|
||
"Shiny Cream Unevo", value, flags=re.I)
|
||
def drop_admin_alias(match: re.Match[str]) -> str:
|
||
status = (match.group("status") or "").strip().capitalize()
|
||
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
|
||
return match.group()
|
||
return ("Shiny " if match.group("shiny") else "") + "Heathcliff" + (
|
||
" " + status if status else ""
|
||
)
|
||
|
||
value = HEATHCLIFF_ADMIN_ALIAS.sub(drop_admin_alias, value)
|
||
def drop_fallen_star_alias(match: re.Match[str]) -> str:
|
||
status = (match.group("status") or "").strip().capitalize()
|
||
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
|
||
return match.group()
|
||
return ("Shiny " if match.group("shiny") else "") + "Dark Mage Evo"
|
||
|
||
value = DARK_MAGE_FALLEN_STAR_ALIAS.sub(drop_fallen_star_alias, value)
|
||
def drop_nirvana_alias(match: re.Match[str]) -> str:
|
||
status = (match.group("status") or "").strip().capitalize()
|
||
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
|
||
return match.group()
|
||
return ("Shiny " if match.group("shiny") else "") + "Buddha Evo"
|
||
|
||
value = BUDDHA_NIRVANA_ALIAS.sub(drop_nirvana_alias, value)
|
||
parts = value.split("|")
|
||
for index, part in enumerate(parts):
|
||
without_alias = ALUCARD_UNHOLY_ALIAS.sub("", part)
|
||
if (without_alias != part and re.search(r"\bAlucard\b", without_alias, re.I)
|
||
and not re.search(r"\bUnevo\s+Alucard\b|\bAlucard\s+Unevo\b",
|
||
without_alias, re.I)):
|
||
parts[index] = without_alias
|
||
value = "|".join(parts)
|
||
def drop_sakamoto_prime(match: re.Match[str]) -> str:
|
||
status = (match.group("status") or "").strip().capitalize()
|
||
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
|
||
return match.group()
|
||
return ("Shiny " if match.group("shiny") else "") + "Sakamoto Evo"
|
||
|
||
parts = value.split("|")
|
||
for index, part in enumerate(parts):
|
||
without_alias = SAKAMOTO_REDUNDANT_ALIAS.sub("", part)
|
||
if (without_alias != part and re.search(r"\bSakamoto\b", without_alias, re.I)
|
||
and not re.search(r"\bUnevo\s+Sakamoto\b|\bSakamoto\s+Unevo\b",
|
||
without_alias, re.I)):
|
||
parts[index] = without_alias
|
||
value = "|".join(parts)
|
||
value = SAKAMOTO_PRIME_BARE.sub(drop_sakamoto_prime, value)
|
||
parts = value.split("|")
|
||
for index, part in enumerate(parts):
|
||
without_alias = AIZEN_TRANSCENDED_ALIAS.sub("", part)
|
||
if (without_alias != part and re.search(r"\bAizen\b", without_alias, re.I)
|
||
and not re.search(r"\bUnevo\s+Aizen\b|\bAizen\s+Unevo\b",
|
||
without_alias, re.I)):
|
||
parts[index] = without_alias
|
||
value = "|".join(parts)
|
||
|
||
def drop_aizen_transcended(match: re.Match[str]) -> str:
|
||
status = (match.group("status") or "").strip().capitalize()
|
||
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
|
||
return match.group()
|
||
return ("Shiny " if match.group("shiny") else "") + "Aizen Evo"
|
||
|
||
value = AIZEN_TRANSCENDED_BARE.sub(drop_aizen_transcended, value)
|
||
parts = value.split("|")
|
||
for index, part in enumerate(parts):
|
||
without_alias = CID_NUCLEAR_ALIAS.sub("", part)
|
||
if (without_alias != part and re.search(r"\bCid\b", without_alias, re.I)
|
||
and not re.search(r"\bUnevo\s+Cid\b|\bCid\s+Unevo\b",
|
||
without_alias, re.I)):
|
||
parts[index] = without_alias
|
||
value = "|".join(parts)
|
||
|
||
def drop_cid_nuclear(match: re.Match[str]) -> str:
|
||
status = (match.group("status") or "").strip().capitalize()
|
||
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
|
||
return match.group()
|
||
return ("Shiny " if match.group("shiny") else "") + "Cid Evo"
|
||
|
||
value = CID_NUCLEAR_BARE.sub(drop_cid_nuclear, value)
|
||
parts = value.split("|")
|
||
for index, part in enumerate(parts):
|
||
without_alias = GILGAMESH_HEROES_ALIAS.sub("", part)
|
||
if (without_alias != part and re.search(r"\bGilgamesh\b", without_alias, re.I)
|
||
and not re.search(r"\bUnevo\s+Gilgamesh\b|\bGilgamesh\s+Unevo\b",
|
||
without_alias, re.I)):
|
||
parts[index] = without_alias
|
||
value = "|".join(parts)
|
||
|
||
def drop_gilgamesh_heroes(match: re.Match[str]) -> str:
|
||
status = (match.group("status") or "").strip().capitalize()
|
||
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
|
||
return match.group()
|
||
return ("Shiny " if match.group("shiny") else "") + "Gilgamesh Evo"
|
||
|
||
value = GILGAMESH_HEROES_BARE.sub(drop_gilgamesh_heroes, value)
|
||
parts = value.split("|")
|
||
for index, part in enumerate(parts):
|
||
without_alias = INHUMAN_NULLIFIER_ALIAS.sub("", part)
|
||
if (without_alias != part and re.search(r"\bInhuman\b", without_alias, re.I)
|
||
and not re.search(r"\bUnevo\s+Inhuman\b|\bInhuman\s+Unevo\b",
|
||
without_alias, re.I)):
|
||
parts[index] = without_alias
|
||
value = "|".join(parts)
|
||
|
||
def drop_inhuman_nullifier(match: re.Match[str]) -> str:
|
||
status = (match.group("status") or "").strip().capitalize()
|
||
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
|
||
return match.group()
|
||
return ("Shiny " if match.group("shiny") else "") + "Inhuman Evo"
|
||
|
||
value = INHUMAN_NULLIFIER_BARE.sub(drop_inhuman_nullifier, value)
|
||
parts = value.split("|")
|
||
for index, part in enumerate(parts):
|
||
without_alias = POSEIDON_TYRANT_ALIAS.sub("", part)
|
||
if (without_alias != part and re.search(r"\bPoseidon\b", without_alias, re.I)
|
||
and not re.search(r"\bUnevo\s+Poseidon\b|\bPoseidon\s+Unevo\b",
|
||
without_alias, re.I)):
|
||
parts[index] = without_alias
|
||
value = "|".join(parts)
|
||
|
||
def drop_poseidon_tyrant(match: re.Match[str]) -> str:
|
||
status = (match.group("status") or "").strip().capitalize()
|
||
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
|
||
return match.group()
|
||
return ("Shiny " if match.group("shiny") else "") + "Poseidon Evo"
|
||
|
||
value = POSEIDON_TYRANT_BARE.sub(drop_poseidon_tyrant, value)
|
||
parts = value.split("|")
|
||
for index, part in enumerate(parts):
|
||
without_alias = BLACK_DOG_HELLHOUND_ALIAS.sub("", part)
|
||
if (without_alias != part and re.search(r"\bBlack\s+Dog\b", without_alias, re.I)
|
||
and not re.search(r"\bUnevo\s+Black\s+Dog\b|\bBlack\s+Dog\s+Unevo\b",
|
||
without_alias, re.I)):
|
||
parts[index] = without_alias
|
||
value = "|".join(parts)
|
||
|
||
def drop_black_dog_hellhound(match: re.Match[str]) -> str:
|
||
status = (match.group("status") or "").strip().capitalize()
|
||
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
|
||
return match.group()
|
||
return ("Shiny " if match.group("shiny") else "") + "Black Dog Evo"
|
||
|
||
value = BLACK_DOG_HELLHOUND_BARE.sub(drop_black_dog_hellhound, value)
|
||
def move_black_dog_shiny(match: re.Match[str]) -> str:
|
||
prefix = "" if re.search(r"\bShiny\s+$", value[:match.start()], re.I) else "Shiny "
|
||
return prefix + "Black Dog" + (match.group("status") or "")
|
||
|
||
value = BLACK_DOG_POSTFIX_SHINY.sub(move_black_dog_shiny, value)
|
||
parts = value.split("|")
|
||
for index, part in enumerate(parts):
|
||
without_alias = ELF_MAGE_AURA_ALIAS.sub("", part)
|
||
if (without_alias != part and re.search(r"\bElf\s+Mage\b", without_alias, re.I)
|
||
and not re.search(r"\bUnevo\s+Elf\s+Mage\b|\bElf\s+Mage\s+Unevo\b",
|
||
without_alias, re.I)):
|
||
parts[index] = without_alias
|
||
value = "|".join(parts)
|
||
|
||
def drop_elf_mage_aura(match: re.Match[str]) -> str:
|
||
status = (match.group("status") or "").strip().capitalize()
|
||
if status == "Unevo" or re.search(r"\bUnevo\s+$", value[:match.start()], re.I):
|
||
return match.group()
|
||
return ("Shiny " if match.group("shiny") else "") + "Elf Mage Evo"
|
||
|
||
value = ELF_MAGE_AURA_BARE.sub(drop_elf_mage_aura, value)
|
||
|
||
def move_elf_mage_shiny(match: re.Match[str]) -> str:
|
||
prefix = "" if re.search(r"\bShiny\s+$", value[:match.start()], re.I) else "Shiny "
|
||
return prefix + "Elf Mage" + (match.group("status") or "")
|
||
|
||
value = ELF_MAGE_POSTFIX_SHINY.sub(move_elf_mage_shiny, value)
|
||
return normalize_fodder_units(value)
|
||
|
||
|
||
def collapse_alias_pairs(value: str) -> str:
|
||
def status(raw: str | None) -> str:
|
||
match = EVO_STATUS.search(raw or "")
|
||
return match.group().capitalize() if match else ""
|
||
|
||
def replace_parentheses(match: re.Match[str]) -> str:
|
||
status1, status2 = status(match.group("status1")), status(match.group("status2"))
|
||
if status1 and status2 and status1 != status2:
|
||
return match.group()
|
||
return (("Shiny " if match.group("shiny") or match.group("shiny2") else "") +
|
||
match.group("unit") + (" " + (status1 or status2) if status1 or status2 else ""))
|
||
|
||
value = ALIAS_PARENS.sub(replace_parentheses, value)
|
||
|
||
def replace(match: re.Match[str]) -> str:
|
||
shiny1, shiny2 = bool(match.group("shiny1")), bool(match.group("shiny2"))
|
||
if shiny1 != shiny2 and not (match.group("sep") == "-" and shiny1):
|
||
return match.group()
|
||
if re.match(r"\s*\[[^]]+\]", value[match.end():]):
|
||
return match.group() # The second copy has its own stats.
|
||
# A leading status belongs to the first unit, e.g. Unevo Alucard / Alucard Evo.
|
||
if re.search(r"\b(?:Evo|Unevo)\s+$", value[:match.start()], re.I):
|
||
return match.group()
|
||
status1 = status(match.group("status1"))
|
||
status2 = status(match.group("status2"))
|
||
if (status1 == "Unevo" and not status2) or (status2 == "Unevo" and not status1):
|
||
return match.group() # An unspecified variant defaults to Evo.
|
||
if status1 and status2 and status1 != status2:
|
||
return match.group()
|
||
resolved_status = status1 or status2
|
||
return (("Shiny " if shiny1 or shiny2 else "") + match.group("unit") +
|
||
(" " + resolved_status if resolved_status else ""))
|
||
|
||
while True:
|
||
updated = ALIAS_PAIR.sub(replace, value)
|
||
if updated == value:
|
||
return value
|
||
value = updated
|
||
|
||
|
||
CATEGORY_HEADING = re.compile(
|
||
r"(?:LIST|FRIENDS?\s*:?|STATS?\s*:?|SSS\s+STATS?\s*:?|"
|
||
r"(?:NORMAL|REGULAR)\s+UNITS?\s*/\s*"
|
||
r"(?:FODDERS?|FOODERS?|FODDER\s+UNITS?)\s*:?|"
|
||
r"(?:FODDERS?|FOODERS?|FODDER\s+UNITS?)\s*:|"
|
||
r"UNEVO\s+UNITS?\s*:?|SSS\s*/\s*SKINS?\s*:?|"
|
||
r"UNIT\s*\(\s*THAT\s+HAVE\s+GOOD\s+STAT\s*\)\s*:?|"
|
||
r"ITEMS?\s*:|GAMEPASS(?:ES)?\s*:|GP\s*:|ALL\s+EVO\s*:?|"
|
||
r"KEYWORD\s*:?|"
|
||
r"(?:SHINY\s+)?UNITS?(?:\s+AVAILABLE)?\s*:|"
|
||
r"(?:SHINY|SHINIES|SHINY\s+UNITS?|EVO|UNEVO|NORMAL|NORMAL\s+UNITS?|"
|
||
r"REGULAR\s+UNITS?(?:\s+FOR\s+TRADE)?|NON[- ]SHINY(?:\s+UNITS?)?|"
|
||
r"OTHER\s+UNITS?|SECRET\s+UNITS?|SSS\s+UNITS?|VALUE\s+UNITS?|"
|
||
r"SKINS?|MISC|EXTRAS?|OTHER|GAMEPASSES|"
|
||
r"HIGH\s+A\s+TIER/A\+|MID\s+A\s+TIER/A|A\s+TIER\s+UNITS?|"
|
||
r"HIGH\s+TIER\s+UNITS?\s*&\s*SHINIES|"
|
||
r"SECRET/NORMAL\s+UNITS?\s*&\s*RARE\s+MYTHICAL\s+SKINS?|"
|
||
r"THESE\s+UNITS?/SKINS?|TOURNEY\s*&\s*INF\s+CASTLE\s+UNITS?)\s*:?)",
|
||
re.I,
|
||
)
|
||
SHINY_HEADING = re.compile(r"(?:SHINY|SHINIES|SHINY\s+EVO|SHINY\s+UNITS?(?:\s+ALL\s+BELOW\s+ARE\s+SHINY)?)\s*:?$", re.I)
|
||
INLINE_CATEGORY_HEADING = re.compile(
|
||
r"^\s*(?P<label>SHINY(?:\s+EVO|\s+UNITS?)?|SHINIES|EVO|UNEVO|"
|
||
r"NORMAL(?:\s+UNITS?)?|REGULAR\s+UNITS?|NON[- ]SHINY(?:\s+UNITS?)?|"
|
||
r"UNITS?|ITEMS?|GAMEPASS(?:ES)?|GP)"
|
||
r"\s*:\s*(?=\S)", re.I,
|
||
)
|
||
UNEVO_HEADING = re.compile(r"UNEVO\s+UNITS?\s*:?$", re.I)
|
||
STATUS_HEADING = re.compile(
|
||
r"(?:\(?ALL\s+UNITS?\s+(?:BELOW\s+ARE\s+)?EVO\)?|"
|
||
r"UNITS?\s*(?:&\s*BULK\s+SSS\s*)?\(?\s*ALL\s+EVOS?\s*\)?|"
|
||
r"\(?ALL\s+EVO\)?(?:\s+COME\s+WITH\s+AN\s+OFFER)?)", re.I,
|
||
)
|
||
|
||
|
||
def strip_category_headings(value: str) -> str:
|
||
"""Remove standalone labels while retaining the Shiny variant they imply."""
|
||
parts = value.split("|")
|
||
if len(parts) == 1:
|
||
return "" if re.fullmatch(r"THESE\s+UNITS?/SKINS?\s*:?", value.strip(), re.I) else value
|
||
output: list[str] = []
|
||
shiny_section = False
|
||
unevo_section = False
|
||
for part in parts:
|
||
inline = INLINE_CATEGORY_HEADING.match(part)
|
||
if inline:
|
||
shiny_section = bool(re.match(r"SHINY|SHINIES", inline.group("label"), re.I))
|
||
unevo_section = False
|
||
part = part[inline.end():]
|
||
label = part.strip()
|
||
if SHINY_HEADING.fullmatch(label):
|
||
shiny_section = True
|
||
unevo_section = False
|
||
continue
|
||
if UNEVO_HEADING.fullmatch(label):
|
||
shiny_section = False
|
||
unevo_section = True
|
||
continue
|
||
if CATEGORY_HEADING.fullmatch(label) or STATUS_HEADING.fullmatch(label):
|
||
shiny_section = False
|
||
unevo_section = False
|
||
continue
|
||
part = re.sub(r"^\s*-\s*(?=[A-Za-z])", "", part)
|
||
if unevo_section:
|
||
for match in reversed(list(UNIT_MENTION.finditer(part))):
|
||
suffix = part[match.end():]
|
||
status = re.match(r"\s+(?:Evo|Unevo)\b|\s*\(\s*(?:Evo|Unevo)\s*\)", suffix, re.I)
|
||
end = match.end() + (status.end() if status else 0)
|
||
part = part[:match.end()] + " Unevo" + part[end:]
|
||
if shiny_section and label:
|
||
matches = list(UNIT_MENTION.finditer(part))
|
||
if matches:
|
||
for match in reversed(matches):
|
||
before = part[:match.start()]
|
||
if not re.search(r"\bShiny(?:\s+Evo)?\s+$", before, re.I):
|
||
part = part[:match.start()] + "Shiny " + part[match.start():]
|
||
elif not re.search(r"\bShiny\b", part, re.I):
|
||
part = re.sub(r"^(\s*(?:(?:x?\d+x?)\s+)?)", r"\1Shiny ", part, count=1, flags=re.I)
|
||
fragments = re.split(r"(\s+/\s+)", part)
|
||
for index in range(0, len(fragments), 2):
|
||
fragment = fragments[index]
|
||
if (index and re.search(r"\b[A-Za-z]{3,}\b", fragment) and
|
||
not re.search(r"\bShiny\b", fragment, re.I) and
|
||
not UNIT_MENTION.search(fragment)):
|
||
fragments[index] = re.sub(
|
||
r"^(\s*(?:(?:x?\d+x?)\s+)?)", r"\1Shiny ",
|
||
fragment, count=1, flags=re.I,
|
||
)
|
||
part = "".join(fragments)
|
||
output.append(part)
|
||
return "|".join(output)
|
||
|
||
|
||
def normalize_shiny_evo_order(value: str) -> str:
|
||
"""Keep one Evo and put Shiny immediately before the unit."""
|
||
unit = UNIT_MENTION.pattern
|
||
def split_variants(match: re.Match[str]) -> str:
|
||
first, second = match.group("first").capitalize(), match.group("second").capitalize()
|
||
if first == second:
|
||
return match.group()
|
||
name = ("Shiny " if match.group("shiny") else "") + match.group("unit")
|
||
variants = name + " " + first + " | " + name + " " + second
|
||
quantity = match.group("quantity")
|
||
if not quantity:
|
||
return variants
|
||
count = int(re.search(r"\d+", quantity).group())
|
||
if count == 2:
|
||
return variants # Two units, one of each variant.
|
||
if count == 1:
|
||
return match.group() # Two variants cannot be assigned to one unit.
|
||
return str(count) + " total across variants: " + variants
|
||
|
||
quantity = r"(?P<quantity>(?:x\d+|\d+\s*x|\d+)\s+)?"
|
||
name = rf"(?P<shiny>Shiny\s+)?(?P<unit>{unit})"
|
||
statuses = r"(?P<first>Evo|Unevo)\s*(?:and|&|/|\+)\s*(?P<second>Evo|Unevo)"
|
||
value = re.sub(
|
||
rf"(?<!\w){quantity}{name}\s*\(\s*{statuses}\s*\)",
|
||
split_variants, value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
rf"(?<!\w){quantity}{name}\s+{statuses}\b(?!\s+Items?\b)",
|
||
split_variants, value, flags=re.I,
|
||
)
|
||
value = re.sub(r"\b(Evo|Unevo)\s*<\s*\1\s*>", r"\1", value, flags=re.I)
|
||
value = re.sub(
|
||
rf"(?P<unit>{unit})\s*\(\s*(?P<status>Evo|Unevo)\s*\)",
|
||
lambda m: m.group("unit") + " " + m.group("status").capitalize(),
|
||
value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
rf"\bShiny\s+Unevo\s+(?P<unit>{unit})(?:\s+Unevo)?(?!\s+Evo\b)",
|
||
lambda m: "Shiny " + m.group("unit") + " Unevo", value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
rf"(?P<lead>^|[|/,~+;]|\b(?:and|or|for|with)\b)\s*"
|
||
rf"Unevo\s+Shiny\s+(?P<unit>{unit}|elf\b)(?:\s+Unevo)?(?!\s+Evo\b)",
|
||
lambda m: m.group("lead") + " Shiny " +
|
||
("Elf Mage" if m.group("unit").casefold() == "elf" else m.group("unit")) +
|
||
" Unevo", value, flags=re.I,
|
||
)
|
||
def move_unevo(match: re.Match[str]) -> str:
|
||
previous = list(UNIT_MENTION.finditer(value, 0, match.start()))
|
||
if previous and not value[previous[-1].end():match.start()].strip():
|
||
return match.group() # Unevo may belong to the preceding unit.
|
||
return match.group("unit") + " Unevo"
|
||
|
||
value = re.sub(
|
||
rf"\bUnevo\s+(?P<unit>{unit})(?:\s+Unevo)?"
|
||
rf"(?!\s*(?:Evo\b|\(\s*Evo\s*\)))",
|
||
move_unevo, value, flags=re.I,
|
||
)
|
||
def move_evo(match: re.Match[str]) -> str:
|
||
previous = list(UNIT_MENTION.finditer(value, 0, match.start()))
|
||
if previous and not value[previous[-1].end():match.start()].strip():
|
||
return match.group() # Evo may belong to the preceding unit.
|
||
return match.group("unit") + " Evo"
|
||
|
||
value = re.sub(
|
||
rf"\bEvo\s+(?P<unit>{unit})(?:\s+Evo)?"
|
||
rf"(?!\s*(?:Unevo\b|\(\s*Unevo\s*\)))",
|
||
move_evo, value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
rf"(?:\[\s*Shiny\s*\]|\(\s*Shiny\s*\))\s*(?={unit})",
|
||
"Shiny ", value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
rf"(?P<unit>{unit})\s*\(\s*Shiny\s+(?P<status>Evo|Unevo)\s*\)",
|
||
lambda m: "Shiny " + m.group("unit") + " " + m.group("status"),
|
||
value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
rf"(?P<unit>{unit})\s*\(\s*Shiny\s+(?P<note>(?:Evo|Unevo)\b[^)]*)\)",
|
||
lambda m: "Shiny " + m.group("unit") + " (" + m.group("note") + ")",
|
||
value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
rf"(?P<unit>{unit})(?:\s+(?P<status>Evo|Unevo))?\s+"
|
||
rf"(?:\[\s*Shiny\s*\]|Shiny)"
|
||
rf"(?:\s*\(\s*(?P<status2>Evo|Unevo)\s*\))?"
|
||
rf"(?=\s*(?:\||$|[,;/)]|x\d+\b|\d+x\b))",
|
||
lambda m: "Shiny " + m.group("unit") + " " +
|
||
(m.group("status") or m.group("status2") or "Evo"),
|
||
value, flags=re.I,
|
||
)
|
||
value = re.sub(r"\bShiny\s+Shiny\b", "Shiny", value, flags=re.I)
|
||
value = re.sub(
|
||
rf"\bShiny\s+Evo\s+(?P<unit>{unit})(?:\s+Evo)?",
|
||
lambda m: "Shiny " + m.group("unit") + " Evo", value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
rf"(?P<unit>{unit})\s+Evo\s+Shiny\s*(?:Evo\b|\(\s*Evo\s*\))",
|
||
lambda m: "Shiny " + m.group("unit") + " Evo", value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
rf"(?P<unit>{unit})\s+Evo\s+Shiny(?=\s*(?:\||$|[,;/)]))",
|
||
lambda m: "Shiny " + m.group("unit") + " Evo", value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
r"\b(?P<unit>Silver Slayer|Toad Sensei|Doll|Violentine)\s+Evo\s+Shiny\b"
|
||
r"(?!\s+(?:pass|hunter)\b)",
|
||
lambda m: "Shiny " + m.group("unit").title() + " Evo", value, flags=re.I,
|
||
)
|
||
value = re.sub(r"\bUnevo\s+Shiny\s+Cream\b",
|
||
"Shiny Cream Unevo", value, flags=re.I)
|
||
value = re.sub(r"\bEvo\s+Shiny\s+Chuuni\b",
|
||
"Shiny Chuuni Evo", value, flags=re.I)
|
||
parts = value.split("|")
|
||
for i, part in enumerate(parts):
|
||
part = re.sub(
|
||
rf"\b(?P<my>my)\s+Evo\s+Shiny\s+(?P<unit>{unit})(?:\s+Evo)?",
|
||
lambda m: m.group("my") + " Shiny " + m.group("unit") + " Evo",
|
||
part, flags=re.I,
|
||
)
|
||
parts[i] = re.sub(
|
||
rf"^(\s*(?:(?:x?\d+x?)\s+)?)Evo\s+Shiny\s+(?P<unit>{unit})(?:\s+Evo)?",
|
||
lambda m: m.group(1) + "Shiny " + m.group("unit") + " Evo",
|
||
part, count=1, flags=re.I,
|
||
)
|
||
return collapse_alias_pairs("|".join(parts))
|
||
|
||
|
||
def normalize_evo_status(value: str) -> str:
|
||
"""Add the default Evo status to recognized units without a local status."""
|
||
matches = list(UNIT_MENTION.finditer(value))
|
||
insertions: list[int] = []
|
||
for index, match in enumerate(matches):
|
||
prefix = value[:match.start()]
|
||
opening = value.rfind("(", 0, match.start())
|
||
if opening > value.rfind(")", 0, match.start()) and index:
|
||
previous = matches[index - 1]
|
||
if re.fullmatch(r"\s*(?:Evo|Unevo)?\s*", value[previous.end():opening], re.I):
|
||
continue # An alternate name in parentheses is the same unit.
|
||
if re.search(r"\bEvo\s+Items?\s*:\s*$", prefix, re.I):
|
||
continue
|
||
before = re.search(
|
||
r"\b(?:Evo|Unevo)\b(?:\s+(?:Shiny|x\d+|\d+x))*\s*$",
|
||
prefix, re.I,
|
||
)
|
||
if before and index:
|
||
between = value[matches[index - 1].end():match.start()]
|
||
if re.fullmatch(r"\s*(?:\([^)]*\)\s*)?(?:Evo|Unevo)\s*(?:Shiny\s*)?", between, re.I):
|
||
before = None # The status belongs to the preceding unit.
|
||
if before:
|
||
continue
|
||
suffix = value[match.end():]
|
||
direct = re.match(r"\s*(?:(?:x\d+|\d+x|\d+)\s+)?(?:Evo|Unevo)\b", suffix, re.I)
|
||
if direct:
|
||
continue
|
||
if suffix.lstrip().startswith("("):
|
||
bracket = suffix.find(")")
|
||
if 0 < bracket < 100:
|
||
if EVO_STATUS.search(suffix[:bracket + 1]):
|
||
continue
|
||
if re.match(r"\s*(?:Evo|Unevo)\b", suffix[bracket + 1:], re.I):
|
||
continue
|
||
insertions.append(match.end())
|
||
for position in reversed(insertions):
|
||
value = value[:position] + " Evo" + value[position:]
|
||
return value
|
||
|
||
|
||
def normalize_variant_quantities(value: str) -> str:
|
||
"""Expand explicit inventory totals without losing their shiny or Evo status."""
|
||
unit = UNIT_MENTION.pattern
|
||
value = re.sub(
|
||
rf"(?P<unit>{unit})\s+(?P<status>Evo|Unevo)\s+×(?P<count>\d+)\b",
|
||
lambda m: f'{m.group("count")}x {m.group("unit")} {m.group("status")}',
|
||
value, flags=re.I,
|
||
)
|
||
value = re.sub(r"\b3\s+Fodder\s+Units\s*\(\s*2\s+Unevo\s*,\s*1\s+Evo\s*\)",
|
||
"2x Fodder Units Unevo | 1x Fodder Units Evo", value, flags=re.I)
|
||
|
||
def shiny_remainder(match: re.Match[str]) -> str:
|
||
total, shiny = int(match.group("total")), int(match.group("shiny_count"))
|
||
if shiny > total:
|
||
return match.group()
|
||
name, status = match.group("unit").title(), match.group("status").capitalize()
|
||
output = [f"{shiny}x Shiny {name} {status}"]
|
||
if total > shiny:
|
||
output.append(f"{total - shiny}x {name} {status}")
|
||
return " | ".join(output)
|
||
|
||
value = re.sub(
|
||
rf"(?<!\w)(?P<total>\d+)\s*[xX]?\s+(?P<unit>{unit})\s+"
|
||
rf"(?P<status>Evo|Unevo)\s*\(\s*(?P<shiny_count>\d+)\s*[xX]?\s+Shiny\s*\)",
|
||
shiny_remainder, value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
rf"(?<!\w)(?P<unit>{unit})\s+(?P<status>Evo|Unevo)\s*\(\s*Shiny\s*\)",
|
||
lambda m: f'Shiny {m.group("unit").title()} {m.group("status").capitalize()}',
|
||
value, flags=re.I,
|
||
)
|
||
|
||
def counted_variants(match: re.Match[str]) -> str:
|
||
total = int(match.group("total"))
|
||
first_count = int(match.group("first_count"))
|
||
second_count = (int(match.group("second_count"))
|
||
if match.group("second_count") else total - first_count)
|
||
if (first_count > total or second_count < 0 or
|
||
first_count + second_count != total):
|
||
return match.group()
|
||
first_status = match.group("first_status").capitalize()
|
||
second_status = ((match.group("second_status") or
|
||
("Unevo" if first_status == "Evo" else "Evo")).capitalize())
|
||
if first_status == second_status:
|
||
return match.group()
|
||
name = ("Shiny " if match.group("shiny") else "") + match.group("unit").title()
|
||
variants = []
|
||
for count, status in ((first_count, first_status), (second_count, second_status)):
|
||
if count:
|
||
variants.append(f"{count}x {name} {status}")
|
||
return " | ".join(variants)
|
||
|
||
value = re.sub(
|
||
rf"(?<!\w)(?P<total>\d+)\s*[xX]?\s+(?P<shiny>Shiny\s+)?"
|
||
rf"(?P<unit>{unit})\s*\(\s*(?P<first_count>\d+)\s+"
|
||
rf"(?P<first_status>Evo|Unevo)\s*,?\s*"
|
||
rf"(?:(?P<second_count>\d+)\s+(?P<second_status>Evo|Unevo))?\s*\)",
|
||
counted_variants, value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
rf"(?<!\w)(?P<first_count>\d+)\s+(?P<unit>{unit})\s+"
|
||
rf"(?P<first_status>Evo|Unevo)\s+(?P<second_count>\d+)\s+"
|
||
rf"(?P<second_status>Evo|Unevo)\b",
|
||
lambda m: (f'{m.group("first_count")}x {m.group("unit").title()} '
|
||
f'{m.group("first_status").capitalize()} | '
|
||
f'{m.group("second_count")}x {m.group("unit").title()} '
|
||
f'{m.group("second_status").capitalize()}'),
|
||
value, flags=re.I,
|
||
)
|
||
value = re.sub(
|
||
rf"(?<!\w)(?P<unit>{unit})\s+(?P<first_count>\d+)\s+"
|
||
rf"(?P<first_status>Evo|Unevo)\s*[/,]\s*"
|
||
rf"(?P<second_count>\d+)\s+(?P<second_status>Evo|Unevo)\b",
|
||
lambda m: (f'{m.group("first_count")}x {m.group("unit").title()} '
|
||
f'{m.group("first_status").capitalize()} | '
|
||
f'{m.group("second_count")}x {m.group("unit").title()} '
|
||
f'{m.group("second_status").capitalize()}'),
|
||
value, flags=re.I,
|
||
)
|
||
value = re.sub(r"\b(\d+)\s*Evo\s+Nagumo\s+Evo\b", r"\1x Nagumo Evo", value, flags=re.I)
|
||
value = re.sub(r"\b(\d+)\s+Evo\s+Chuuni\b", r"\1x Chuuni Evo", value, flags=re.I)
|
||
value = re.sub(r"\bNagumo\s+(\d+)\s+Evo\b", r"\1x Nagumo Evo", value, flags=re.I)
|
||
value = re.sub(r"\b2\s+Skull\s+Knight\s+1\s+Unevo\b",
|
||
"1x Skull Knight Evo | 1x Skull Knight Unevo", value, flags=re.I)
|
||
value = re.sub(r"\b3\s+Nagumo\s+2\s+Unevo\s+1\s+Evo\b",
|
||
"2x Nagumo Unevo | 1x Nagumo Evo", value, flags=re.I)
|
||
value = re.sub(r"\bBuddha\s*\(\s*Buddha Evo\s*\)\s*Evo\b",
|
||
"Buddha Evo", value, flags=re.I)
|
||
return value
|
||
|
||
|
||
def normalize_body_line(raw: str) -> str:
|
||
value = tidy_line(raw)
|
||
value = remove_unicode_emoji(value)
|
||
# In copied reposts, the next Trading label can touch the word "units".
|
||
value = re.sub(r"\bunitstrade\b", "units | Trading:", value, flags=re.I)
|
||
value = normalize_shiny_evo_order(normalize_variant_quantities(normalize_unit_names(
|
||
remove_non_trade_notices(remove_decorative_marks(remove_emoji_codes(value)))
|
||
)))
|
||
value = value.replace("!", "")
|
||
value = normalize_shiny_evo_order(normalize_evo_status(normalize_shiny_evo_order(value)))
|
||
value = re.sub(r"^\s*[-•]+\s+", "", value)
|
||
value = re.sub(r"(?:\s*\|\s*){2,}", " | ", value)
|
||
value = re.sub(r"\s+", " ", value).strip(" |")
|
||
return value
|
||
|
||
|
||
def category_for_label(value: str) -> str:
|
||
label = re.sub(r"\s+", " ", value.casefold())
|
||
if label in {"trading", "flipping", "trade", "in stock"}:
|
||
return "offer"
|
||
if label in {"mlf", "mostly looking for"}:
|
||
return "mlf"
|
||
if label in {"nlf", "nfl", "not looking for"}:
|
||
return "nlf"
|
||
return "lf"
|
||
|
||
|
||
def is_boilerplate(line: str) -> bool:
|
||
simple = line.strip().strip("|").strip()
|
||
return bool(BOILERPLATE.fullmatch(simple) or BOILERPLATE.fullmatch(simple.strip(" ()[]")))
|
||
|
||
|
||
def clean_offer_items(offer: str) -> str:
|
||
"""Remove clear chat/UI fragments while retaining unnamed tradeable items."""
|
||
# A pipe inside a stat tuple is a separator within one unit, not a new item.
|
||
offer = re.sub(r"\([^()]*\)|\{[^{}]*\}",
|
||
lambda match: match.group().replace("|", "/"), offer)
|
||
kept: list[str] = []
|
||
for raw in offer.split("|"):
|
||
segment = raw.strip().strip("'\"").strip()
|
||
if (not segment or OFFER_TIMESTAMP.fullmatch(segment)
|
||
or re.fullmatch(r"[\W_]+", segment, re.UNICODE)
|
||
or NON_ITEM_OFFER.fullmatch(segment)
|
||
or is_boilerplate(segment)):
|
||
continue
|
||
segment = re.sub(r"^'?[+•⟡-]\s*", "", segment)
|
||
segment = re.sub(r"^(?:also\s+got|can\s+add)\s+", "", segment, flags=re.I)
|
||
segment = re.sub(r"\(\s*(?:LF|MLF|NOT\s+LOOKING\s+FOR|DM\s+FOR\s+THE\s+STATS)\b[^)]*\)",
|
||
"", segment, flags=re.I)
|
||
segment = re.sub(r"\s+(?:dm\s+me(?:\s+good\s+offers)?|i['’]?ll\s+reply|"
|
||
r"can\s+do\s+any\s+proof\s+u\s+want)\s*$", "", segment, flags=re.I)
|
||
segment = re.sub(r"\s+-\s*$", "", segment).strip(" ,;")
|
||
if re.fullmatch(r"(?:SSS|SS|S[+-]?|A[+-]?|B[+-]?)", segment, re.I):
|
||
if kept and re.search(r"\b(?:SSS|SS|S[+-]?|A[+-]?|B[+-]?)$", kept[-1], re.I):
|
||
kept[-1] += " / " + segment
|
||
continue
|
||
if (re.fullmatch(r"\d+(?:\.\d+)?%", segment) and kept
|
||
and re.search(r"\bFULL\s+SSS\b", kept[-1], re.I)):
|
||
kept[-1] += " / " + segment
|
||
continue
|
||
if segment and not NON_ITEM_OFFER.fullmatch(segment):
|
||
kept.append(segment)
|
||
return " | ".join(kept)
|
||
|
||
|
||
def separate_received_bid(offer: str) -> tuple[str, str]:
|
||
"""Keep an already received best/high offer out of owned inventory."""
|
||
owned: list[str] = []
|
||
bids: list[str] = []
|
||
for raw in offer.split("|"):
|
||
part = raw.strip()
|
||
match = re.search(r"\b(?:BEST|HIGH)\s+OFFER\s*:?\s*", part, re.I)
|
||
if match:
|
||
if part[:match.start()].strip(" ,;:-"):
|
||
owned.append(part[:match.start()].strip(" ,;:-"))
|
||
bid = part[match.end():].strip(" ,;:-")
|
||
if bid:
|
||
bids.append(bid)
|
||
continue
|
||
part = re.sub(r"^PRE[-\s]?TRADE\s+", "", part, flags=re.I)
|
||
if part:
|
||
owned.append(part)
|
||
return " | ".join(owned), " | ".join(bids)
|
||
|
||
|
||
def clean_request_segments(value: str) -> str:
|
||
"""Keep requested units and conditions, discarding clear UI/chat fragments."""
|
||
kept = []
|
||
for raw in value.split("|"):
|
||
segment = raw.strip().strip(" ,;#'\"")
|
||
if segment.casefold() == "ignoring clowns/lowballs":
|
||
segment = "Lowballs"
|
||
if not segment or REQUEST_META.fullmatch(segment):
|
||
continue
|
||
segment = re.sub(r"\s+IF\s+NO\s+REPLY\s+means\s+ignore\s*$", "", segment, flags=re.I)
|
||
segment = re.sub(r"\s+NOT\s+A\s+BOT\s*$", "", segment, flags=re.I)
|
||
segment = re.sub(r"(?:\s*\W+\s*|\s+)(?:PLEASE\s+)?DM\s+(?:ME|YOUR\s+OFFERS|ME\s+FOR\s+OFFERS)\]?\s*$",
|
||
"", segment, flags=re.I)
|
||
segment = re.sub(r"\s+I\s+REPLY\s+ALWAYS\s*$", "", segment, flags=re.I)
|
||
segment = re.sub(r"\s+i\s+don.?t\s+bite\s+send\s+whatever\s*$", "", segment, flags=re.I)
|
||
segment = re.sub(r"\s*(?:/|,)\s*(?:ignore\s*=\s*nty|no\s+response\s*=\s*nty)\s*$",
|
||
"", segment, flags=re.I)
|
||
segment = segment.strip(" ,;#'\"")
|
||
if segment and not REQUEST_META.fullmatch(segment):
|
||
kept.append(segment)
|
||
return " | ".join(kept)
|
||
|
||
|
||
def clean_request_fields(lf: str, mlf: str, nlf: str,
|
||
looking_for: str = "") -> tuple[str, str, str, str]:
|
||
"""Repair explicit MLF/NLF labels and rebuild the compatibility field."""
|
||
# A copied repost joined 'GOOD OFFERS' to its next Trading label and then
|
||
# repeated the same offer inventory in LF.
|
||
if re.fullmatch(r"GOOD OFFERSTrading\s*\|.*\|\s*GOOD OFFERS", lf, re.I):
|
||
lf = "GOOD OFFERS"
|
||
# In one listing, the NLF section names excluded low-value offers and then
|
||
# states a positive stat requirement for the offered Homura.
|
||
wanted_stat = "Only SSS stats (for Homura Evo)"
|
||
if wanted_stat in nlf:
|
||
nlf = nlf.replace("; " + wanted_stat, "").replace(wanted_stat, "").strip(" ;|")
|
||
lf = " | ".join(value for value in (lf, wanted_stat) if value)
|
||
if not lf and mlf and looking_for.upper().startswith("MLF: "):
|
||
combined = looking_for[5:].strip()
|
||
if combined.endswith(mlf) and combined != mlf:
|
||
mlf = combined # A legacy export lost the leading MLF fragment.
|
||
# One stored repost put a repeated offer inventory into MLF after a glued label.
|
||
mlf = re.sub(r"\bunits(?:trade|\s*\|\s*Trading:)\s*\|.*$", "units", mlf, flags=re.I)
|
||
|
||
moved_mlf: list[str] = []
|
||
moved_nlf: list[str] = []
|
||
|
||
def move_label(match: re.Match[str]) -> str:
|
||
destination = moved_mlf if match.group(1).upper() == "MLF" else moved_nlf
|
||
destination.append(match.group(2).strip())
|
||
return ""
|
||
|
||
lf = EMBEDDED_REQUEST_LABEL.sub(move_label, lf)
|
||
lf_parts = []
|
||
for segment in clean_request_segments(lf).split(" | "):
|
||
negative = re.fullmatch(r"(?:NO\s+WANT\s+(.+)|NO\s+(LOW\s*BALLS?))", segment, re.I)
|
||
if negative:
|
||
moved_nlf.append((negative.group(1) or negative.group(2)).strip())
|
||
elif segment:
|
||
lf_parts.append(segment)
|
||
lf = " | ".join(lf_parts)
|
||
mlf = clean_request_segments(" | ".join(part for part in [mlf, *moved_mlf] if part))
|
||
nlf = clean_request_segments(" | ".join(part for part in [nlf, *moved_nlf] if part))
|
||
return Listing("", "", lf, mlf, nlf).looking_for, lf, mlf, nlf
|
||
|
||
|
||
def separate_friend_offer(mlf: str) -> tuple[str, str | None]:
|
||
"""A copied 'My Friend is | X' section describes the friend's inventory."""
|
||
parts = [part.strip() for part in mlf.split("|")]
|
||
for index, part in enumerate(parts[:-1]):
|
||
if part.casefold() == "my friend is" and parts[index + 1]:
|
||
friend_offer = parts[index + 1]
|
||
remaining = " | ".join(part for i, part in enumerate(parts)
|
||
if i not in (index, index + 1) and part)
|
||
return remaining, friend_offer
|
||
return mlf, None
|
||
|
||
|
||
def repair_misfiled_inventory(offer: str, lf: str, nlf: str) -> tuple[str, str, str]:
|
||
"""Repair a confirmed legacy listing whose inventory followed an NLF label."""
|
||
if not (nlf.startswith("Shiny Gilgamesh Evo | x1 FULL SSS Aizen Evo")
|
||
and "x1 FULL SSS Homura Evo (LF " in nlf):
|
||
return offer, lf, nlf
|
||
items = []
|
||
for part in nlf.split("|"):
|
||
if "WILL READ ALL DMS" in part.upper():
|
||
continue
|
||
embedded_lf = re.search(r"\(\s*LF\s+([^)]*)\)", part, re.I)
|
||
if embedded_lf:
|
||
lf = " | ".join(value for value in (lf, embedded_lf.group(1).strip()) if value)
|
||
part = part[:embedded_lf.start()] + part[embedded_lf.end():]
|
||
items.append(part.strip())
|
||
return clean_offer_items(offer + " | " + " | ".join(items)), lf, ""
|
||
|
||
|
||
def repair_misfiled_mlf_inventory(offer: str, lf: str,
|
||
mlf: str) -> tuple[str, str, str]:
|
||
"""Repair the confirmed repost where normal-unit inventory followed MLF."""
|
||
marker = "OVERPAY | NORMAL UNITS | x1 Aizen Evo (FULL S) | x6 Homura Evo ALL GOOD STATS"
|
||
if not mlf.startswith(marker):
|
||
return offer, lf, mlf
|
||
parts = [part.strip() for part in mlf.split("|")]
|
||
inventory = []
|
||
for part in parts[2:]:
|
||
embedded_lf = re.search(r"\(\s*LF\s+([^)]*)\)", part, re.I)
|
||
if embedded_lf:
|
||
lf = " | ".join(value for value in (lf, embedded_lf.group(1).strip()) if value)
|
||
part = part[:embedded_lf.start()] + part[embedded_lf.end():]
|
||
inventory.append(part.strip())
|
||
return clean_offer_items(offer + " | " + " | ".join(inventory)), lf, "OVERPAY"
|
||
|
||
|
||
def repair_glued_reposts(offer: str, lf: str, mlf: str) -> tuple[str, str, str]:
|
||
"""Repair two confirmed reposts where a Trading label joined a request."""
|
||
if (re.search(r"Homura(?: Evo)?, Battlepass and addTrade\s*\|", lf, re.I)
|
||
and re.search(r"\|\s*Chuuni(?: Evo)? too\s*\|", lf, re.I)):
|
||
lf = lf.split("Trade | ", 1)[0]
|
||
offer = clean_offer_items(offer + " | Chuuni Evo")
|
||
if (mlf.startswith("UPGRADEtrading | Buddha Evo with SSS spa ")
|
||
and " | UPGRADE | Buddha Evo with SSS spa " in mlf):
|
||
buddha = mlf.split(" | ", 2)[1]
|
||
offer = clean_offer_items(offer + " | " + buddha)
|
||
mlf = "UPGRADE"
|
||
return offer, lf, mlf
|
||
|
||
|
||
def repair_misfiled_lf_inventory(offer: str, lf: str) -> tuple[str, str]:
|
||
"""Move three confirmed inventory lists out of the LF section."""
|
||
parts = [part.strip() for part in lf.split("|")]
|
||
if (lf.startswith("2X SSS DMG FOR MY Shiny Poseidon Evo | Evo MYTIC's | ")
|
||
and parts[-1].startswith("Shiny POSEI/Chuuni Evo AND ADDS FOR MY ROGER Evo")):
|
||
offer = clean_offer_items(offer + " | " + " | ".join(parts[1:-1]))
|
||
return offer, " | ".join((parts[0], parts[-1]))
|
||
if (lf.startswith("S stat Fodder Units | 4 Deer Tan Evo | ")
|
||
and parts[-1].startswith("Vip and Shiny hunter(")):
|
||
inventory = list(dict.fromkeys(parts[:-1]))
|
||
offer = clean_offer_items(offer + " | " + " | ".join(inventory))
|
||
return offer, parts[-1]
|
||
if (" | Shiny UNITS | " in lf and " | NON-Shiny UNITS | " in lf
|
||
and parts[-1].startswith("s tier upgrade for my Shiny units")):
|
||
inventory = [part for part in parts[1:-1]
|
||
if part.casefold() not in {"shiny units", "non-shiny units"}]
|
||
offer = clean_offer_items(offer + " | " + " | ".join(inventory))
|
||
return offer, " | ".join((parts[0], parts[-1]))
|
||
return offer, lf
|
||
|
||
|
||
def repair_inline_side_cues(offer: str, lf: str, nlf: str) -> tuple[str, str, str]:
|
||
"""Separate explicit requests and exclusions embedded in offered items."""
|
||
offered = []
|
||
wanted = []
|
||
excluded = []
|
||
for raw in offer.split("|"):
|
||
item = raw.strip()
|
||
if re.fullmatch(r"Shiny Mist Ninja Evo LOOKIN FOR FAIR TRADE NO SCAM", item, re.I):
|
||
offered.append("Shiny Mist Ninja Evo")
|
||
wanted.append("FAIR TRADE")
|
||
elif re.fullmatch(r"\(my My SS SPA AND SS RNG FOR Battlepass\)", item, re.I):
|
||
offered.append("My SS SPA AND SS RNG")
|
||
wanted.append("Battlepass")
|
||
elif match := re.fullmatch(r"(Homura Evo sss rng)\s*\(\s*for\s+(4 sss dmg/spa)\)", item, re.I):
|
||
offered.append(match.group(1))
|
||
wanted.append(match.group(2))
|
||
elif item.casefold() == "or pick) (almost all for aizen evo btw)":
|
||
if not re.search(r"\bAizen Evo\b", lf, re.I):
|
||
wanted.append("Aizen Evo")
|
||
elif item.casefold() == "my units for good offers":
|
||
wanted.append("GOOD OFFERS")
|
||
elif re.fullmatch(r"Chuuni Evo WITH S\+ SPA FOR SOMETHING", item, re.I):
|
||
offered.append("Chuuni Evo WITH S+ SPA")
|
||
wanted.append("SOMETHING")
|
||
elif item.casefold() == "battlepass (will not trade for dark mage evo + adds)":
|
||
offered.append("Battlepass")
|
||
excluded.append("Dark Mage Evo + ADDS")
|
||
elif item.casefold() == "my 3 units display for good damage unit":
|
||
offered.append("3 UNITS DISPLAY")
|
||
wanted.append("GOOD DAMAGE UNIT")
|
||
elif item.casefold() == "or bundle for ssss":
|
||
offered.append("bundle")
|
||
wanted.append("SSS")
|
||
elif item.casefold() == "buhha + cid evo for shiny or sss or":
|
||
offered.append("Buddha + Cid Evo")
|
||
wanted.extend(("Shiny", "SSS", "OFFER"))
|
||
elif item.casefold().startswith("olf homura evo/overpays/chuuni evo item"):
|
||
wanted.append("Homura Evo/overpays/Chuuni Evo item")
|
||
elif item.casefold() == "upgrades/":
|
||
wanted.append("UPGRADES")
|
||
elif item.casefold() == "6x dark mage evo (all good stats) [2x for any sss]":
|
||
offered.append("6x Dark Mage Evo (ALL GOOD STATS)")
|
||
wanted.append("ANY SSS for 2 Dark Mage Evo")
|
||
elif item.casefold() == "100+ fodder units (9 for 10rr)":
|
||
offered.append("100+ Fodder Units")
|
||
wanted.append("10 RR for 9 Fodder Units")
|
||
else:
|
||
offered.append(item)
|
||
lf_parts = [lf] if lf else []
|
||
for request in wanted:
|
||
if request and not any(request.casefold() == part.casefold() for part in lf_parts):
|
||
lf_parts.append(request)
|
||
lf = " | ".join(lf_parts)
|
||
nlf = " | ".join(part for part in (nlf, *excluded) if part)
|
||
return clean_offer_items(" | ".join(offered)), lf, nlf
|
||
|
||
|
||
def repair_standalone_lf_inventory(offer: str, lf: str,
|
||
mlf: str) -> tuple[str, str]:
|
||
"""Move two confirmed Homura listings' inventory lists out of LF."""
|
||
if ("My Alucard" not in mlf and "my Alucard" not in mlf):
|
||
return offer, lf
|
||
if not ("Shiny Dark Mage" in mlf and lf.startswith("Alucard")
|
||
and " | Aizen" in lf):
|
||
return offer, lf
|
||
parts = [part.strip() for part in lf.split("|")]
|
||
if len(parts) < 5 or not re.search(r"Aizen.*UPGRADES", parts[-1], re.I):
|
||
return offer, lf
|
||
inventory = parts[:-1]
|
||
if not any("Shiny Dark Mage" in item for item in inventory):
|
||
inventory.append("Shiny Dark Mage Evo")
|
||
return clean_offer_items(offer + " | " + " | ".join(inventory)), parts[-1]
|
||
|
||
|
||
def repair_confirmed_long_lf_inventory(offer: str, lf: str) -> tuple[str, str]:
|
||
"""Move two confirmed offered inventories out of long LF sections."""
|
||
parts = [part.strip() for part in lf.split("|")]
|
||
if (lf.startswith("Sss for Each | 3Dark Mage Evo | ") and len(parts) >= 9
|
||
and "my Homura" in parts[8]):
|
||
inventory = [parts[index] for index in (1, 3, 5, 6)]
|
||
offer = clean_offer_items(offer + " | " + " | ".join(inventory))
|
||
return offer, " | ".join(("SSS for each", "SSS Stats", parts[8]))
|
||
if (lf.startswith("FULL SSS Aizen Evo LOW % FOR MY Aizen Evo | ")
|
||
and len(parts) == 17 and parts[14].startswith("HIGH SSS DMG")):
|
||
offer = clean_offer_items(offer + " | " + " | ".join(parts[1:14]))
|
||
return offer, " | ".join((parts[0], *parts[14:]))
|
||
return offer, lf
|
||
|
||
|
||
def repair_alucard_lf_inventory(offer: str, lf: str) -> tuple[str, str]:
|
||
"""Separate confirmed offered units from two Alucard stat requests."""
|
||
parts = [part.strip() for part in lf.split("|")]
|
||
if not (re.match(r"%29\+ high sss dmg or aizen", lf, re.I)
|
||
and len(parts) >= 12
|
||
and re.match(r"shiny\s+(?:chunni|chuuni)\b", parts[3], re.I)
|
||
and parts[11].casefold().startswith("offers")):
|
||
return offer, lf
|
||
inventory = ["Shiny Chuuni Evo", "Dark Mage Evo", *parts[4:7], *parts[8:11]]
|
||
offer = clean_offer_items(offer + " | " + " | ".join(inventory))
|
||
lf = " | ".join((*parts[:3], "sss dmg or spa", parts[7], parts[11]))
|
||
return offer, lf
|
||
|
||
|
||
OWNED_VARIANT = re.compile(
|
||
r"(?<!\w)(?P<shiny>Shiny\s+)?(?P<name>"
|
||
+ "|".join(re.escape(name).replace(r"\ ", r"\s+") for name in KNOWN_UNIT_NAMES)
|
||
+ r")\s+(?P<state>Evo|Unevo)\b", re.I,
|
||
)
|
||
|
||
|
||
def recover_explicit_my_offers(offer: str, lf: str, mlf: str) -> str:
|
||
"""Add named units explicitly owned in full LF/MLF exchange proposals."""
|
||
known = {name.casefold(): name for name in KNOWN_UNIT_NAMES}
|
||
|
||
def key(match: re.Match[str]) -> tuple[bool, str, str]:
|
||
return bool(match.group("shiny")), match.group("name").casefold(), match.group("state").casefold()
|
||
|
||
offered = {key(match) for match in OWNED_VARIANT.finditer(normalize_unit_names(offer))}
|
||
additions = []
|
||
for request in (lf, mlf):
|
||
for segment in request.split("|"):
|
||
for clause in re.finditer(r"\bmy\s+(.{0,130}?)\s+for\b", segment, re.I):
|
||
left = normalize_unit_names(clause.group(1))
|
||
for match in OWNED_VARIANT.finditer(left):
|
||
variant = key(match)
|
||
if variant in offered:
|
||
continue
|
||
shiny, name, state = variant
|
||
# Both phrases already describe owned units, despite
|
||
# unusual stat placement or a plural unit name.
|
||
if (shiny and name == "scarlet slayer"
|
||
and re.search(r"Shiny SS DMG SCARLET SLAYER Evo", offer, re.I)):
|
||
continue
|
||
if (not shiny and name == "homura" and state == "evo"
|
||
and re.search(r"\b\d+\s+homuras\b", offer, re.I)):
|
||
continue
|
||
additions.append(f"{'Shiny ' if shiny else ''}{known[name]} {state.capitalize()}")
|
||
offered.add(variant)
|
||
return clean_offer_items(offer + " | " + " | ".join(additions)) if additions else offer
|
||
|
||
|
||
def recover_partial_proposal_offers(offer: str, lf: str, mlf: str) -> str:
|
||
"""Complete offered sides stated in otherwise partial inventory lists."""
|
||
additions = []
|
||
if ("Shiny Somber Evo + Shiny Sakamoto Evo + Jelly Evo + " in lf
|
||
and "2 x Cid Unevo + 2 x Nagumo Unevo for Shiny Chuuni Evo" in lf):
|
||
additions.extend(("2 x Cid Unevo", "2 x Nagumo Unevo"))
|
||
if "GIVING CLEAN BD AND Shiny Skull Knight Evo FOR Shiny Alucard Evo" in lf:
|
||
additions.append("Shiny Skull Knight Evo")
|
||
if (re.search(r"Shiny toad sensei Evo and Nagumo Evo for Shiny Cid Evo", lf, re.I)
|
||
and not re.search(r"\bNagumo Evo\b", offer, re.I)):
|
||
additions.append("Nagumo Evo")
|
||
if "Chuuni Evo/Evo ITEM FOR Chuuni Evo AND Buddha Unevo" in mlf:
|
||
additions.extend(("Chuuni Evo", "Evo ITEM"))
|
||
return clean_offer_items(offer + " | " + " | ".join(additions)) if additions else offer
|
||
|
||
|
||
def repair_confirmed_proposal_sides(offer: str, lf: str,
|
||
mlf: str) -> tuple[str, str, str]:
|
||
"""Apply confirmed directions of three ambiguous full proposals."""
|
||
gohan_request = "Shiny Gohan Evo / Gohan Evo / Shiny Android 21 Evo for bundles or RR"
|
||
if gohan_request in lf:
|
||
offer = clean_offer_items(
|
||
offer + " | Shiny Gohan Evo | Gohan Evo | Shiny Android 21 Evo")
|
||
lf = lf.replace(gohan_request, "bundles or RR", 1)
|
||
if "Shiny Chuuni Evo for Aizen Evo" in mlf:
|
||
offer = clean_offer_items(offer + " | Shiny Chuuni Evo")
|
||
if ("S TIER UNITS, Alucard Evo, Aizen Evo, X2 Shiny Chuuni Evo + "
|
||
"Gilgamesh Evo FOR Shiny Mamy Evo" in mlf):
|
||
offer = clean_offer_items(
|
||
offer + " | S TIER UNITS | Alucard Evo | Aizen Evo | "
|
||
"X2 Shiny Chuuni Evo | Gilgamesh Evo")
|
||
return offer, lf, mlf
|
||
|
||
|
||
def expand_friend_listings(listings: list[Listing]) -> list[Listing]:
|
||
expanded = []
|
||
for listing in listings:
|
||
mlf, friend_offer = separate_friend_offer(listing.mlf)
|
||
if not friend_offer:
|
||
expanded.append(listing)
|
||
continue
|
||
expanded.append(Listing(listing.author, listing.offer, listing.lf, mlf, listing.nlf))
|
||
expanded.append(Listing(f"friend:{hash_author(listing.author)}:my_friend_is",
|
||
clean_offer_items(friend_offer)))
|
||
return expanded
|
||
|
||
|
||
def normalized_chunk(lines: list[str]) -> str:
|
||
cleaned: list[str] = []
|
||
for raw in lines:
|
||
line = normalize_body_line(raw)
|
||
if not line or is_boilerplate(line):
|
||
continue
|
||
# Decorative token-only lines (not real item entries).
|
||
if re.fullmatch(r"(?:\||[-=~* ])+", line):
|
||
continue
|
||
cleaned.append(line.strip(" |"))
|
||
return " | ".join(line for line in cleaned if line)
|
||
|
||
|
||
def distinct_chunks(chunks: list[list[str]]) -> str:
|
||
seen: set[str] = set()
|
||
unique: list[str] = []
|
||
for section in chunks:
|
||
cleaned = normalized_chunk(section)
|
||
key = canon(cleaned)
|
||
if not cleaned or not key or key in seen:
|
||
continue
|
||
seen.add(key)
|
||
unique.append(cleaned)
|
||
return " | ".join(unique)
|
||
|
||
|
||
def looks_like_variant_item(value: str) -> bool:
|
||
return bool(
|
||
2 <= len(value.split()) <= 6 and
|
||
re.fullmatch(r"[\w #+.'-]+", value) and
|
||
re.search(r"\b(?:evo|unevo|shiny)\b", value, re.I)
|
||
)
|
||
|
||
|
||
def split_inline_offer_for(offer: str, lf: str = "") -> tuple[str, str]:
|
||
"""Move clear 'Trading X for Y' requests out of the offered inventory."""
|
||
offered: list[str] = []
|
||
requested: list[str] = []
|
||
for segment in offer.split("|"):
|
||
segment = segment.strip()
|
||
if not segment:
|
||
continue
|
||
split: tuple[str, str] | None = None
|
||
for match in INLINE_FOR.finditer(segment):
|
||
before = segment[:match.start()]
|
||
if before.count("(") > before.count(")"):
|
||
continue
|
||
left = before.strip(" .,:;/-")
|
||
right = segment[match.end():].strip(" .,:;/-")
|
||
if (not right or INLINE_FOR_PURPOSE.match(right) or
|
||
re.search(r"\b(?:or|and|for)$", right, re.I)):
|
||
continue
|
||
normalized_left = normalize_unit_names(left)
|
||
normalized_right = normalize_unit_names(right)
|
||
right_is_unit = bool(UNIT_MENTION.search(normalized_right) or
|
||
looks_like_variant_item(normalized_right))
|
||
right_is_request = right_is_unit or bool(INLINE_REQUEST.search(normalized_right))
|
||
left_is_item = bool(UNIT_MENTION.search(normalized_left) or
|
||
INLINE_OFFER_ITEM.search(normalized_left) or
|
||
looks_like_variant_item(normalized_left))
|
||
short_unknown_item = bool(
|
||
right_is_unit and 1 <= len(left.split()) <= 5 and
|
||
re.fullmatch(r"[\w #+.'-]+", left) and
|
||
not re.match(r"(?:channel|i\s+can|you\s+can)\b", left, re.I)
|
||
)
|
||
if not right_is_request:
|
||
continue
|
||
if left.casefold() in {"", "all", "both"}:
|
||
if offered:
|
||
split = ("", right)
|
||
break
|
||
continue
|
||
if left_is_item or short_unknown_item:
|
||
split = (left, right)
|
||
break
|
||
if split is None:
|
||
offered.append(segment)
|
||
continue
|
||
if split[0]:
|
||
offered.append(split[0])
|
||
requested.append(split[1])
|
||
|
||
if not offered or not requested:
|
||
return offer, lf
|
||
existing = lf.strip(" |")
|
||
merged = [existing] if existing else []
|
||
seen = canon(existing) if existing else ""
|
||
for request in requested:
|
||
key = canon(request)
|
||
if not key or key in seen or any(canon(part) == key for part in merged):
|
||
continue
|
||
merged.append(request)
|
||
seen = canon(" | ".join(merged))
|
||
return " | ".join(offered), " | ".join(merged)
|
||
|
||
|
||
def parse_listing(msg: Message) -> Listing | None:
|
||
"""One CSV row per Discord message, not per 'TRADING' word.
|
||
|
||
LF without a concrete offer is excluded. Handles multiple TRADING labels,
|
||
repeated paragraphs within one message, MLF and NLF, and a conservative
|
||
LF-first inventory variant (LF OFFERS/UPGRADES followed by item lines).
|
||
"""
|
||
groups: dict[str, list[list[str]]] = {"offer": [], "lf": [], "mlf": [], "nlf": []}
|
||
current = "preface"
|
||
seen_offer_marker = False
|
||
for raw in msg.body.splitlines():
|
||
line = normalize_body_line(raw)
|
||
if not line:
|
||
continue
|
||
if is_boilerplate(line):
|
||
continue
|
||
|
||
# Explicit 'TRADE ...' is also common in trading channels.
|
||
short_trade = TRADE_AT_LINE_START.match(line)
|
||
# A few servers use a separate 'LOOKING' heading without 'FOR'.
|
||
short_looking = LOOKING_AT_LINE_START.match(line)
|
||
markers: list[tuple[int, int, str]] = [
|
||
(match.start(), match.end(), category_for_label(match.group("label")))
|
||
for match in LABEL.finditer(line)
|
||
if not (category_for_label(match.group("label")) != "offer"
|
||
and line[:match.start()].count("(") > line[:match.start()].count(")"))
|
||
]
|
||
if short_trade and not any(start == short_trade.start() for start, _, _ in markers):
|
||
markers.append((short_trade.start(), short_trade.end(), "offer"))
|
||
if short_looking and not any(start == short_looking.start() for start, _, _ in markers):
|
||
markers.append((short_looking.start(), short_looking.end(), "lf"))
|
||
markers.sort(key=lambda item: item[0])
|
||
|
||
if not markers:
|
||
if current != "preface":
|
||
groups[current][-1].append(line)
|
||
continue
|
||
|
||
first = markers[0][0]
|
||
prefix = line[:first].strip(" :|-")
|
||
if prefix and current != "preface" and prefix.casefold() not in {"i am mainly", "im mainly"}:
|
||
groups[current][-1].append(prefix)
|
||
for i, (start, end, category) in enumerate(markers):
|
||
current = category
|
||
if category == "offer":
|
||
seen_offer_marker = True
|
||
groups[category].append([])
|
||
end_of_text = markers[i + 1][0] if i + 1 < len(markers) else len(line)
|
||
fragment = line[end:end_of_text].strip(" :|-")
|
||
if fragment:
|
||
groups[category][-1].append(fragment)
|
||
|
||
if not seen_offer_marker:
|
||
# Specific salvage case: 'LF OFFERS/UPGRADES' on first line, followed
|
||
# by a multiline inventory. This is not an LF-only request.
|
||
if len(groups["lf"]) == 1:
|
||
section = groups["lf"][0]
|
||
if (len(section) >= 3 and GENERIC_REQUEST.fullmatch(section[0])
|
||
and len([s for s in section[1:] if not BOILERPLATE.fullmatch(s)]) >= 2):
|
||
groups["offer"].append(section[1:])
|
||
groups["lf"] = [[section[0]]]
|
||
else:
|
||
return None
|
||
else:
|
||
return None
|
||
|
||
offer = clean_offer_items(distinct_chunks(groups["offer"]))
|
||
if not offer:
|
||
return None
|
||
lf = distinct_chunks(groups["lf"])
|
||
offer, lf = split_inline_offer_for(offer, lf)
|
||
offer, lf, nlf = repair_inline_side_cues(
|
||
offer, lf, distinct_chunks(groups["nlf"]))
|
||
offer, lf, nlf = repair_misfiled_inventory(offer, lf, nlf)
|
||
offer, lf, mlf = repair_misfiled_mlf_inventory(
|
||
offer, lf, distinct_chunks(groups["mlf"]))
|
||
offer, lf, mlf = repair_glued_reposts(offer, lf, mlf)
|
||
offer, lf = repair_misfiled_lf_inventory(offer, lf)
|
||
offer, lf = repair_standalone_lf_inventory(offer, lf, mlf)
|
||
offer, lf = repair_confirmed_long_lf_inventory(offer, lf)
|
||
offer, lf = repair_alucard_lf_inventory(offer, lf)
|
||
_, lf, mlf, nlf = clean_request_fields(lf, mlf, nlf)
|
||
offer, lf, mlf = repair_confirmed_proposal_sides(offer, lf, mlf)
|
||
offer = recover_explicit_my_offers(offer, lf, mlf)
|
||
offer = recover_partial_proposal_offers(offer, lf, mlf)
|
||
return Listing(author=msg.author, offer=offer, lf=lf, mlf=mlf, nlf=nlf)
|
||
|
||
|
||
def parse_listings(msg: Message) -> list[Listing]:
|
||
"""Split explicit Friend(s) sections into trades with a separate identity."""
|
||
if is_dyno_message(msg):
|
||
return []
|
||
if not any(FRIEND_BOUNDARY.search(line) for line in msg.body.splitlines()):
|
||
listing = parse_listing(msg)
|
||
return expand_friend_listings([listing]) if listing else []
|
||
parts: list[str] = []
|
||
sections: list[Message] = []
|
||
author = msg.author
|
||
friend_number = 0
|
||
for raw in msg.body.splitlines():
|
||
rest = raw
|
||
while match := FRIEND_BOUNDARY.search(rest):
|
||
before = rest[:match.start()].strip(" |")
|
||
if before:
|
||
parts.append(before)
|
||
if parts:
|
||
sections.append(Message(author, "\n".join(parts)))
|
||
friend_number += 1
|
||
author = f"friend:{hash_author(msg.author)}:{friend_number}"
|
||
parts = ["Trading:"]
|
||
rest = rest[match.end():]
|
||
if rest.strip(" |"):
|
||
parts.append(rest.strip(" |") if friend_number else rest)
|
||
if parts:
|
||
sections.append(Message(author, "\n".join(parts)))
|
||
listings: list[Listing] = []
|
||
parsed_sections: list[Message] = []
|
||
for section in sections:
|
||
listing = parse_listing(section)
|
||
if listing:
|
||
listings.append(listing)
|
||
parsed_sections.append(section)
|
||
elif listings and section.author.startswith("friend:"):
|
||
# A Friend marker can occur only in LF/MLF text. Keep those terms
|
||
# with the preceding trade when no friend offer follows it.
|
||
remainder = section.body.removeprefix("Trading:").strip()
|
||
if remainder:
|
||
prior = parsed_sections[-1]
|
||
combined = Message(prior.author, prior.body + "\n" + remainder)
|
||
merged = parse_listing(combined)
|
||
if merged:
|
||
listings[-1] = merged
|
||
parsed_sections[-1] = combined
|
||
return expand_friend_listings(listings)
|
||
|
||
|
||
def canon(value: str) -> str:
|
||
value = clean_export_text(html.unescape(value)).casefold()
|
||
value = re.sub(r"(\d+)\s*[×x]\b", r"\1x", value)
|
||
return " ".join(WORD.findall(value))
|
||
|
||
|
||
def shiny_signature(value: str) -> Counter[str]:
|
||
words = WORD.findall(normalize_unit_names(value).casefold())
|
||
signature: Counter[str] = Counter()
|
||
for i, word in enumerate(words):
|
||
if word != "shiny":
|
||
continue
|
||
j = i + 1
|
||
while j < len(words) and (words[j] in {"evo", "unevo"} or
|
||
re.fullmatch(r"(?:x\d+|\d+x)", words[j])):
|
||
j += 1
|
||
unit = next((" ".join(name) for name in KNOWN_SHINY_UNITS
|
||
if tuple(words[j:j + len(name)]) == name),
|
||
words[j] if j < len(words) else "")
|
||
signature[unit] += 1
|
||
return signature
|
||
|
||
|
||
def token_overlap(a: str, b: str) -> float:
|
||
ta, tb = Counter(WORD.findall(a)), Counter(WORD.findall(b))
|
||
denom = sum(ta.values()) + sum(tb.values())
|
||
return 2 * sum((ta & tb).values()) / denom if denom else 1.0
|
||
|
||
|
||
def similar_update(old_offer: str, old_lf: str, new_offer: str, new_lf: str, threshold: float) -> bool:
|
||
if old_offer == new_offer and old_lf == new_lf:
|
||
return True
|
||
if shiny_signature(old_offer) != shiny_signature(new_offer):
|
||
return False
|
||
if shiny_signature(old_lf) != shiny_signature(new_lf):
|
||
return False
|
||
if min(len(old_offer.split()), len(new_offer.split())) < 5:
|
||
return False
|
||
if bool(old_lf) != bool(new_lf):
|
||
return False
|
||
if old_lf and SequenceMatcher(None, old_lf, new_lf).ratio() < 0.75:
|
||
return False
|
||
return (
|
||
SequenceMatcher(None, old_offer, new_offer).ratio() >= threshold
|
||
and token_overlap(old_offer, new_offer) >= max(0.77, threshold - 0.08)
|
||
)
|
||
|
||
|
||
def hash_author(author: str) -> str:
|
||
return hashlib.sha256(author.encode("utf-8")).hexdigest()[:24]
|
||
|
||
|
||
def clean_export_text(value: str) -> str:
|
||
# Existing database rows may still contain emoji and formatting marks.
|
||
original = value
|
||
value = remove_unicode_emoji(value)
|
||
# Remove an Excel escape added by an earlier export before an arrow.
|
||
value = re.sub(r"^'(?=-+>+|-[A-Za-z])", "", value)
|
||
cleaned = OFFER_HEADING.sub("", remove_non_trade_notices(remove_decorative_marks(remove_emoji_codes(value))))
|
||
cleaned = normalize_shiny_evo_order(normalize_variant_quantities(normalize_unit_names(cleaned)))
|
||
cleaned = collapse_alias_pairs(strip_category_headings(cleaned))
|
||
cleaned = normalize_shiny_evo_order(normalize_evo_status(cleaned.replace("!", "")))
|
||
if cleaned != original or re.search(r"^\s*\||\|\s*$|\|\s*\|", cleaned):
|
||
parts = (re.sub(r"\s+", " ", part).strip() for part in cleaned.split("|"))
|
||
value = " | ".join(part for part in parts if part and not re.fullmatch(r"[-—–~*]+", part))
|
||
return value
|
||
|
||
|
||
def csv_safe(value: str) -> str:
|
||
value = clean_export_text(value)
|
||
return excel_safe(value)
|
||
|
||
|
||
def normalize_request_segments(value: str) -> str:
|
||
"""Normalize unit names without treating request headings as offer headings."""
|
||
normalized = []
|
||
for part in value.split("|"):
|
||
part = part.strip()
|
||
if not part:
|
||
continue
|
||
shiny_list = re.fullmatch(r"SHINIES:\s*(.+)", part, re.I)
|
||
if shiny_list:
|
||
normalized.append(",".join(
|
||
clean_export_text("Shiny " + unit.strip())
|
||
for unit in shiny_list.group(1).split(",") if unit.strip()
|
||
))
|
||
else:
|
||
normalized.append(clean_export_text(part))
|
||
return clean_request_segments(" | ".join(normalized))
|
||
|
||
|
||
def excel_safe(value: str) -> str:
|
||
# Prevent formula injection if opening arbitrary user text in Excel.
|
||
return "'" + value if value and value.lstrip().startswith(("=", "+", "-", "@")) else value
|
||
|
||
|
||
def record_scam_warning(conn: sqlite3.Connection, warning: ScamWarning) -> None:
|
||
conn.execute(
|
||
"""INSERT INTO scam_warnings (reported_handles,warning_text,reporter_hash)
|
||
VALUES (?,?,?)
|
||
ON CONFLICT(reported_handles,warning_text,reporter_hash)
|
||
DO UPDATE SET reports_seen=reports_seen+1""",
|
||
(warning.reported_handles, warning.warning_text, warning.reporter_hash),
|
||
)
|
||
|
||
|
||
def migrate_friend_trades(conn: sqlite3.Connection) -> None:
|
||
"""Split legacy Friend(s) sections already stored as one trade."""
|
||
rows = list(conn.execute(
|
||
"SELECT id,author_hash,offer,lf,mlf,nlf,seen_count,update_count,last_seen FROM trades"
|
||
))
|
||
for row_id, author_hash, offer, lf, mlf, nlf, seen, updates, last_seen in rows:
|
||
if not any(FRIEND_FIELD.search(value) for value in (offer, lf, mlf, nlf)):
|
||
continue
|
||
offers = [clean_export_text(part.strip(" |")) for part in FRIEND_FIELD.split(offer)]
|
||
lf, mlf, nlf = (
|
||
clean_export_text(" | ".join(part.strip() for part in FRIEND_FIELD.split(value) if part.strip(" |")))
|
||
for value in (lf, mlf, nlf)
|
||
)
|
||
main = Listing("", offers[0], lf, mlf, nlf)
|
||
conn.execute(
|
||
"""UPDATE trades SET offer=?,looking_for=?,lf=?,mlf=?,nlf=?,
|
||
canon_offer=?,canon_lf=? WHERE id=?""",
|
||
(main.offer, main.looking_for, main.lf, main.mlf, main.nlf,
|
||
canon(main.offer), canon(main.looking_for), row_id),
|
||
)
|
||
for friend_number, friend_offer in enumerate(offers[1:], 1):
|
||
if not friend_offer:
|
||
continue
|
||
friend = Listing("", friend_offer, lf, mlf, nlf)
|
||
friend_hash = hash_author(f"friend:{author_hash}:{friend_number}")
|
||
conn.execute(
|
||
"""INSERT INTO trades (author_hash,offer,looking_for,canon_offer,canon_lf,
|
||
seen_count,update_count,last_seen,lf,mlf,nlf)
|
||
VALUES (?,?,?,?,?,?,?,?,?,?,?)""",
|
||
(friend_hash, friend.offer, friend.looking_for,
|
||
canon(friend.offer), canon(friend.looking_for), seen, updates,
|
||
last_seen, friend.lf, friend.mlf, friend.nlf),
|
||
)
|
||
|
||
|
||
def migrate_nfl_labels(conn: sqlite3.Connection) -> None:
|
||
"""Move legacy NFL text from LF to the not-looking-for field."""
|
||
for row_id, offer, lf, mlf, nlf in conn.execute(
|
||
"SELECT id,offer,lf,mlf,nlf FROM trades WHERE lf LIKE '%NFL%'"
|
||
):
|
||
match = NFL_LABEL.search(lf)
|
||
if not match:
|
||
continue
|
||
moved = lf[match.end():].strip(" |")
|
||
lf = lf[:match.start()].strip(" |")
|
||
nlf = " | ".join(part for part in (nlf, moved) if part)
|
||
listing = Listing("", offer, lf, mlf, nlf)
|
||
conn.execute(
|
||
"""UPDATE trades SET looking_for=?,lf=?,nlf=?,canon_lf=? WHERE id=?""",
|
||
(listing.looking_for, listing.lf, listing.nlf,
|
||
canon(listing.looking_for), row_id),
|
||
)
|
||
|
||
|
||
def migrate_inline_for_trades(conn: sqlite3.Connection) -> int:
|
||
"""Move requests in stored 'Trading X for Y' offers into LF."""
|
||
changed = 0
|
||
rows = list(conn.execute("SELECT id,offer,lf,mlf,nlf FROM trades"))
|
||
for row_id, offer, lf, mlf, nlf in rows:
|
||
new_offer, new_lf = split_inline_offer_for(offer, lf)
|
||
if (new_offer, new_lf) == (offer, lf):
|
||
continue
|
||
listing = Listing("", new_offer, new_lf, mlf, nlf)
|
||
conn.execute(
|
||
"""UPDATE trades SET offer=?,looking_for=?,lf=?,canon_offer=?,canon_lf=?
|
||
WHERE id=?""",
|
||
(new_offer, listing.looking_for, new_lf, canon(new_offer),
|
||
canon(listing.looking_for), row_id),
|
||
)
|
||
changed += 1
|
||
return changed
|
||
|
||
|
||
def open_database(path: Path) -> sqlite3.Connection:
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
conn = sqlite3.connect(path)
|
||
conn.execute("PRAGMA busy_timeout=10000")
|
||
conn.execute("PRAGMA journal_mode=WAL")
|
||
conn.execute(
|
||
"""CREATE TABLE IF NOT EXISTS trades (
|
||
id INTEGER PRIMARY KEY,
|
||
author_hash TEXT NOT NULL,
|
||
offer TEXT NOT NULL,
|
||
looking_for TEXT NOT NULL,
|
||
canon_offer TEXT NOT NULL,
|
||
canon_lf TEXT NOT NULL,
|
||
seen_count INTEGER NOT NULL DEFAULT 1,
|
||
update_count INTEGER NOT NULL DEFAULT 0,
|
||
last_seen INTEGER NOT NULL,
|
||
lf TEXT NOT NULL DEFAULT '',
|
||
mlf TEXT NOT NULL DEFAULT '',
|
||
nlf TEXT NOT NULL DEFAULT ''
|
||
)"""
|
||
)
|
||
conn.execute(
|
||
"""CREATE TABLE IF NOT EXISTS scam_warnings (
|
||
id INTEGER PRIMARY KEY,
|
||
reported_handles TEXT NOT NULL,
|
||
warning_text TEXT NOT NULL,
|
||
reporter_hash TEXT NOT NULL,
|
||
reports_seen INTEGER NOT NULL DEFAULT 1,
|
||
UNIQUE(reported_handles,warning_text,reporter_hash)
|
||
)"""
|
||
)
|
||
# Schema migration from the old parser's existing SQLite state.
|
||
columns = {row[1] for row in conn.execute("PRAGMA table_info(trades)")}
|
||
migrated = "lf" not in columns
|
||
for column in ("lf", "mlf", "nlf"):
|
||
if column not in columns:
|
||
conn.execute(f"ALTER TABLE trades ADD COLUMN {column} TEXT NOT NULL DEFAULT ''")
|
||
if migrated:
|
||
conn.execute("UPDATE trades SET lf=looking_for")
|
||
conn.execute("CREATE INDEX IF NOT EXISTS trades_exact ON trades(author_hash, canon_offer, canon_lf)")
|
||
conn.execute("CREATE INDEX IF NOT EXISTS trades_author_recent ON trades(author_hash, last_seen DESC)")
|
||
migrate_friend_trades(conn)
|
||
if conn.execute("PRAGMA user_version").fetchone()[0] < 1:
|
||
for row_id, offer, looking_for in conn.execute("SELECT id,offer,looking_for FROM trades"):
|
||
conn.execute(
|
||
"UPDATE trades SET canon_offer=?,canon_lf=? WHERE id=?",
|
||
(canon(offer), canon(looking_for), row_id),
|
||
)
|
||
conn.execute("PRAGMA user_version=1")
|
||
if conn.execute("PRAGMA user_version").fetchone()[0] < 2:
|
||
migrate_nfl_labels(conn)
|
||
conn.execute("PRAGMA user_version=2")
|
||
if conn.execute("PRAGMA user_version").fetchone()[0] < 56:
|
||
for row_id, offer, looking_for in conn.execute("SELECT id,offer,looking_for FROM trades"):
|
||
conn.execute(
|
||
"UPDATE trades SET canon_offer=?,canon_lf=? WHERE id=?",
|
||
(canon(offer), canon(looking_for), row_id),
|
||
)
|
||
conn.execute("PRAGMA user_version=56")
|
||
if conn.execute("PRAGMA user_version").fetchone()[0] < 57:
|
||
migrate_inline_for_trades(conn)
|
||
conn.execute("PRAGMA user_version=57")
|
||
conn.commit()
|
||
return conn
|
||
|
||
|
||
def import_previous_state(conn: sqlite3.Connection, path: Path) -> int:
|
||
old = json.loads(path.read_text(encoding="utf-8-sig"))
|
||
if not isinstance(old, list):
|
||
raise ValueError("legacy JSON state must be a list")
|
||
for i, item in enumerate(old, start=1):
|
||
offer, lf = item["offer"], item["looking_for"]
|
||
conn.execute(
|
||
"""INSERT INTO trades
|
||
(author_hash, offer, looking_for, canon_offer, canon_lf,
|
||
seen_count, update_count, last_seen, lf)
|
||
VALUES(?,?,?,?,?,?,?,?,?)""",
|
||
(item["author_hash"], offer, lf, canon(offer), canon(lf),
|
||
int(item.get("seen_count", 1)), int(item.get("update_count", 0)), i, lf),
|
||
)
|
||
return len(old)
|
||
|
||
|
||
class TradeStore:
|
||
def __init__(self, conn: sqlite3.Connection, threshold: float, no_fuzzy: bool):
|
||
self.conn = conn
|
||
self.threshold = threshold
|
||
self.no_fuzzy = no_fuzzy
|
||
self.sequence = int(conn.execute("SELECT COALESCE(MAX(last_seen),0) FROM trades").fetchone()[0])
|
||
self.added = 0
|
||
self.exact = 0
|
||
self.updated = 0
|
||
|
||
def add(self, listing: Listing) -> None:
|
||
self.sequence += 1
|
||
ah = hash_author(listing.author)
|
||
co, cl = canon(listing.offer), canon(listing.looking_for)
|
||
exact = self.conn.execute(
|
||
"""SELECT id FROM trades WHERE author_hash=? AND canon_offer=? AND canon_lf=?
|
||
ORDER BY last_seen DESC LIMIT 1""",
|
||
(ah, co, cl),
|
||
).fetchone()
|
||
if exact:
|
||
self.conn.execute(
|
||
"""UPDATE trades SET seen_count=seen_count+1, last_seen=?,
|
||
lf=?, mlf=?, nlf=? WHERE id=?""",
|
||
(self.sequence, listing.lf, listing.mlf, listing.nlf, exact[0]),
|
||
)
|
||
self.exact += 1
|
||
return
|
||
|
||
if not self.no_fuzzy:
|
||
for old_id, oo, ol in self.conn.execute(
|
||
"""SELECT id, canon_offer, canon_lf FROM trades WHERE author_hash=?
|
||
ORDER BY last_seen DESC LIMIT 80""", (ah,),
|
||
):
|
||
if similar_update(oo, ol, co, cl, self.threshold):
|
||
self.conn.execute(
|
||
"""UPDATE trades SET offer=?, looking_for=?, canon_offer=?, canon_lf=?,
|
||
lf=?,mlf=?,nlf=?,seen_count=seen_count+1,
|
||
update_count=update_count+1,last_seen=? WHERE id=?""",
|
||
(listing.offer, listing.looking_for, co, cl, listing.lf,
|
||
listing.mlf, listing.nlf, self.sequence, old_id),
|
||
)
|
||
self.updated += 1
|
||
return
|
||
|
||
self.conn.execute(
|
||
"""INSERT INTO trades (author_hash, offer, looking_for, canon_offer,
|
||
canon_lf, last_seen, lf, mlf, nlf) VALUES(?,?,?,?,?,?,?,?,?)""",
|
||
(ah, listing.offer, listing.looking_for, co, cl, self.sequence,
|
||
listing.lf, listing.mlf, listing.nlf),
|
||
)
|
||
self.added += 1
|
||
|
||
|
||
def resolve_files(arguments: list[str]) -> list[Path]:
|
||
found: list[Path] = []
|
||
seen: set[Path] = set()
|
||
for arg in arguments:
|
||
candidates = [Path(p) for p in glob.glob(arg, recursive=True)] if glob.has_magic(arg) else [Path(arg)]
|
||
if not candidates:
|
||
raise FileNotFoundError(f"No files match {arg!r}")
|
||
for candidate in candidates:
|
||
if candidate.is_dir():
|
||
paths = sorted(p for p in candidate.rglob("*") if p.is_file() and p.suffix.lower() in INPUT_EXTENSIONS)
|
||
elif candidate.is_file():
|
||
paths = [candidate]
|
||
else:
|
||
raise FileNotFoundError(f"Input does not exist: {candidate}")
|
||
for path in paths:
|
||
identity = path.resolve()
|
||
if identity not in seen:
|
||
found.append(path)
|
||
seen.add(identity)
|
||
return found
|
||
|
||
|
||
def export_csv(conn: sqlite3.Connection, output: Path, detailed: bool) -> int:
|
||
output.parent.mkdir(parents=True, exist_ok=True)
|
||
count = 0
|
||
emitted_friends: set[tuple[str, str]] = set()
|
||
with output.open("w", encoding="utf-8-sig", newline="") as stream:
|
||
writer = csv.writer(stream)
|
||
if detailed:
|
||
writer.writerow(["offer", "looking_for", "lf", "mlf", "nlf",
|
||
"author_hash", "reposts_seen", "updates_seen",
|
||
"pretrade", "received_bid"])
|
||
else:
|
||
writer.writerow(["offer", "looking_for"])
|
||
rows = conn.execute(
|
||
"""SELECT offer,looking_for,lf,mlf,nlf,author_hash,seen_count,update_count
|
||
FROM trades ORDER BY id"""
|
||
)
|
||
for row in rows:
|
||
pretrade = bool(re.search(r"\b(?:PRE|PRE[-\s]?TRADE)\b", row[0], re.I))
|
||
offer = clean_offer_items(clean_export_text(row[0]))
|
||
offer, received_bid = separate_received_bid(offer)
|
||
if not offer:
|
||
continue
|
||
values = list(row)
|
||
offer, raw_lf = split_inline_offer_for(offer, values[2])
|
||
offer, raw_lf, values[4] = repair_inline_side_cues(
|
||
offer, raw_lf, values[4])
|
||
values[3], friend_offer = separate_friend_offer(values[3])
|
||
offer, raw_lf, values[4] = repair_misfiled_inventory(offer, raw_lf, values[4])
|
||
offer, raw_lf, values[3] = repair_misfiled_mlf_inventory(
|
||
offer, raw_lf, values[3])
|
||
offer, raw_lf, values[3] = repair_glued_reposts(
|
||
offer, raw_lf, values[3])
|
||
offer, raw_lf = repair_misfiled_lf_inventory(offer, raw_lf)
|
||
offer, raw_lf = repair_standalone_lf_inventory(
|
||
offer, raw_lf, values[3])
|
||
offer, raw_lf = repair_confirmed_long_lf_inventory(offer, raw_lf)
|
||
offer, raw_lf = repair_alucard_lf_inventory(offer, raw_lf)
|
||
offer = clean_offer_items(clean_export_text(offer))
|
||
values[1:5] = clean_request_fields(raw_lf, values[3], values[4], values[1])
|
||
values[1:5] = clean_request_fields(*(
|
||
normalize_request_segments(value) for value in values[2:5]))
|
||
offer, values[2], values[3] = repair_confirmed_proposal_sides(
|
||
offer, values[2], values[3])
|
||
values[1] = Listing("", "", values[2], values[3], values[4]).looking_for
|
||
offer = recover_explicit_my_offers(offer, values[2], values[3])
|
||
offer = recover_partial_proposal_offers(offer, values[2], values[3])
|
||
values[0] = offer
|
||
values.extend(["yes" if pretrade else "", received_bid])
|
||
export_values = values if detailed else values[:2]
|
||
writer.writerow([excel_safe(v) if isinstance(v, str) else v for v in export_values])
|
||
count += 1
|
||
if friend_offer:
|
||
friend_offer = clean_offer_items(clean_export_text(friend_offer))
|
||
friend_hash = hash_author(f"friend:{values[5]}:my_friend_is")
|
||
key = (friend_hash, canon(friend_offer))
|
||
already_stored = conn.execute(
|
||
"SELECT 1 FROM trades WHERE author_hash=? AND canon_offer=? LIMIT 1", key
|
||
).fetchone()
|
||
if (friend_offer and key not in emitted_friends and not already_stored):
|
||
friend_values = [friend_offer, "", "", "", "", friend_hash, 1, 0, "", ""]
|
||
writer.writerow([excel_safe(v) if isinstance(v, str) else v
|
||
for v in (friend_values if detailed else friend_values[:2])])
|
||
emitted_friends.add(key)
|
||
count += 1
|
||
return count
|
||
|
||
|
||
def export_scam_warnings(conn: sqlite3.Connection, output: Path) -> int:
|
||
output.parent.mkdir(parents=True, exist_ok=True)
|
||
count = 0
|
||
with output.open("w", encoding="utf-8-sig", newline="") as stream:
|
||
# Explicit quoting keeps spreadsheet editors from treating the leading
|
||
# apostrophe in an Excel-escaped @handle as a CSV quote character.
|
||
writer = csv.writer(stream, quoting=csv.QUOTE_ALL)
|
||
writer.writerow(["reported_handles", "warning_text", "reporter_hash", "reports_seen"])
|
||
for handles, warning_text, reporter_hash, seen in conn.execute(
|
||
"""SELECT reported_handles,warning_text,reporter_hash,reports_seen
|
||
FROM scam_warnings ORDER BY id"""
|
||
):
|
||
writer.writerow([handles, excel_safe(warning_text), reporter_hash, seen])
|
||
count += 1
|
||
return count
|
||
|
||
|
||
def main(argv: list[str] | None = None) -> int:
|
||
p = argparse.ArgumentParser(description="Convert messy Discord copy-paste into a scalable deduplicated trade CSV")
|
||
p.add_argument("files", nargs="*", help="Input text files, folders or globs (otherwise pipe from clipboard)")
|
||
p.add_argument("-o", "--output", type=Path, default=Path("trades.csv"))
|
||
p.add_argument("--warnings-output", type=Path,
|
||
help="CSV for reported scam warnings (default: scammer_warnings.csv beside --output)")
|
||
p.add_argument("--state", type=Path, default=Path("trades_state.sqlite"))
|
||
p.add_argument("--import-json", type=Path, help="Import the old version's JSON history")
|
||
p.add_argument("--reset", action="store_true", help="Discard existing database rows before processing")
|
||
p.add_argument("--detailed", action="store_true", help="Export separate LF, MLF, NLF and deduplication metadata")
|
||
p.add_argument("--no-fuzzy", action="store_true", help="Disable merging similar inventory updates")
|
||
p.add_argument("--threshold", type=float, default=0.87, help="Fuzzy similarity threshold (default 0.87)")
|
||
p.add_argument("--progress-every", type=int, default=10000)
|
||
args = p.parse_args(argv)
|
||
|
||
if not 0 <= args.threshold <= 1:
|
||
p.error("--threshold must be between 0 and 1")
|
||
if args.progress_every < 0:
|
||
p.error("--progress-every must be >= 0")
|
||
if not args.files and sys.stdin.isatty():
|
||
p.print_help()
|
||
print("Example: Get-Clipboard -Raw | py discord_trade_parser.py", file=sys.stderr)
|
||
return 2
|
||
legacy = args.import_json
|
||
if args.state.suffix.lower() == ".json":
|
||
legacy = legacy or args.state
|
||
args.state = args.state.with_suffix(".sqlite")
|
||
if legacy is None and args.state == Path("trades_state.sqlite") and Path("trades_state.json").exists():
|
||
legacy = Path("trades_state.json")
|
||
if args.state.resolve() == args.output.resolve():
|
||
p.error("--output and --state cannot be the same path")
|
||
warnings_output = args.warnings_output or args.output.with_name("scammer_warnings.csv")
|
||
if warnings_output.resolve() in {args.output.resolve(), args.state.resolve()}:
|
||
p.error("--warnings-output must differ from --output and --state")
|
||
try:
|
||
files = resolve_files(args.files) if args.files else []
|
||
except FileNotFoundError as e:
|
||
p.error(str(e))
|
||
if args.files and not files:
|
||
p.error("No text files found")
|
||
|
||
new_state = not args.state.exists()
|
||
try:
|
||
conn = open_database(args.state)
|
||
try:
|
||
if args.reset:
|
||
conn.execute("DELETE FROM trades")
|
||
conn.execute("DELETE FROM scam_warnings")
|
||
conn.commit()
|
||
elif new_state and legacy and legacy.exists():
|
||
count = import_previous_state(conn, legacy)
|
||
conn.commit()
|
||
print(f"Imported {count} listings from {legacy}", file=sys.stderr)
|
||
|
||
store = TradeStore(conn, args.threshold, args.no_fuzzy)
|
||
messages = 0
|
||
skipped = 0
|
||
warnings_found = 0
|
||
conn.execute("BEGIN")
|
||
streams = []
|
||
if files:
|
||
# Open files one by one; the total input is never held in RAM.
|
||
for path in files:
|
||
with path.open("r", encoding="utf-8-sig", errors="replace") as stream:
|
||
for message in iter_messages(stream):
|
||
messages += 1
|
||
trade_message, warnings = extract_scam_warnings(message)
|
||
for warning in warnings:
|
||
record_scam_warning(conn, warning)
|
||
warnings_found += len(warnings)
|
||
listings = parse_listings(trade_message)
|
||
if listings:
|
||
for listing in listings:
|
||
store.add(listing)
|
||
else:
|
||
skipped += 1
|
||
if args.progress_every and messages % args.progress_every == 0:
|
||
print(f"Processed {messages:,} messages ...", file=sys.stderr)
|
||
else:
|
||
for message in iter_messages(sys.stdin):
|
||
messages += 1
|
||
trade_message, warnings = extract_scam_warnings(message)
|
||
for warning in warnings:
|
||
record_scam_warning(conn, warning)
|
||
warnings_found += len(warnings)
|
||
listings = parse_listings(trade_message)
|
||
if listings:
|
||
for listing in listings:
|
||
store.add(listing)
|
||
else:
|
||
skipped += 1
|
||
if args.progress_every and messages % args.progress_every == 0:
|
||
print(f"Processed {messages:,} messages ...", file=sys.stderr)
|
||
conn.commit()
|
||
rows = export_csv(conn, args.output, args.detailed)
|
||
warning_rows = export_scam_warnings(conn, warnings_output)
|
||
print(f"Messages: {messages:,}; excluded (no identifiable offer): {skipped:,}; "
|
||
f"new listings: {store.added:,}; exact reposts: {store.exact:,}; "
|
||
f"similar updates: {store.updated:,}; CSV rows: {rows:,}; "
|
||
f"warning reports: {warnings_found:,}; warning CSV rows: {warning_rows:,}")
|
||
print(f"Saved {args.output}, {warnings_output}, and {args.state}")
|
||
return 0
|
||
except Exception:
|
||
conn.rollback()
|
||
raise
|
||
finally:
|
||
conn.close()
|
||
except (OSError, sqlite3.Error, ValueError, KeyError, json.JSONDecodeError) as e:
|
||
print(f"Error: {e}", file=sys.stderr)
|
||
return 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|