Update Discord trade listings

This commit is contained in:
2026-11-20 00:40:07 +01:00
parent f37559ad6a
commit af8b173abd
13 changed files with 2120 additions and 996 deletions
+442 -23
View File
@@ -475,6 +475,34 @@ NON_ITEM_OFFER = re.compile(
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)
@@ -1248,6 +1276,8 @@ def normalize_evo_status(value: str) -> str:
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_unit_names(
remove_non_trade_notices(remove_decorative_marks(remove_emoji_codes(value)))
))
@@ -1308,6 +1338,340 @@ def clean_offer_items(offer: str) -> str:
return " | ".join(kept)
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:
@@ -1475,19 +1839,28 @@ def parse_listing(msg: Message) -> Listing | None:
return None
lf = distinct_chunks(groups["lf"])
offer, lf = split_inline_offer_for(offer, lf)
return Listing(
author=msg.author, offer=offer,
lf=lf,
mlf=distinct_chunks(groups["mlf"]),
nlf=distinct_chunks(groups["nlf"]),
)
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 not any(FRIEND_BOUNDARY.search(line) for line in msg.body.splitlines()):
listing = parse_listing(msg)
return [listing] if listing else []
return expand_friend_listings([listing]) if listing else []
parts: list[str] = []
sections: list[Message] = []
author = msg.author
@@ -1526,7 +1899,7 @@ def parse_listings(msg: Message) -> list[Listing]:
if merged:
listings[-1] = merged
parsed_sections[-1] = combined
return listings
return expand_friend_listings(listings)
def canon(value: str) -> str:
@@ -1602,6 +1975,24 @@ def csv_safe(value: str) -> str:
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
@@ -1851,35 +2242,63 @@ def resolve_files(arguments: list[str]) -> list[Path]:
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"])
rows = conn.execute(
"""SELECT offer,looking_for,lf,mlf,nlf,author_hash,seen_count,update_count
FROM trades ORDER BY id"""
)
else:
writer.writerow(["offer", "looking_for"])
rows = conn.execute("SELECT offer,looking_for FROM trades ORDER BY id")
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:
offer = clean_offer_items(clean_export_text(row[0]))
if not offer:
continue
values = list(row)
if detailed:
old_lf = clean_export_text(values[2])
moved_offer, lf = split_inline_offer_for(offer, old_lf)
if (moved_offer, lf) != (offer, old_lf):
values[2] = lf
values[1] = Listing("", moved_offer, lf, values[3], values[4]).looking_for
offer = moved_offer
else:
offer, values[1] = split_inline_offer_for(offer, values[1])
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
writer.writerow([csv_safe(v) if isinstance(v, str) else v for v in values])
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