Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download sinetti_services/ask_answer_format.py from Couscouskabyle/iscc-app: direct link, hf CLI and curl.
- Browser
- Download file 17.4 kB
-
https://huggingface.co/spaces/Couscouskabyle/iscc-app/resolve/main/sinetti_services/ask_answer_format.py
- Command line
-
hf download hf://spaces/Couscouskabyle/iscc-app/sinetti_services/ask_answer_format.py
-
curl -L -o ask_answer_format.py https://huggingface.co/spaces/Couscouskabyle/iscc-app/resolve/main/sinetti_services/ask_answer_format.py
17.4 kB
| """Pure Ask Sinetti answer formatting helpers. | |
| - Convert leftover Markdown pipe tables into bullet lists. | |
| - Parse inline document cites ``[file, page_or_slide]``. | |
| - Split retrieved passages into Cited (used) vs Related (unused). | |
| """ | |
| from __future__ import annotations | |
| import re | |
| _TABLE_SEP = re.compile(r"^\s*\|?(?:\s*:?-{3,}:?\s*\|)+\s*:?-{3,}:?\s*\|?\s*$") | |
| _PIPE_ROW = re.compile(r"^\s*\|(.+)\|\s*$") | |
| _INLINE_CITE = re.compile(r"\[([^\[\]]+?),\s*([^\[\]]+?)\]") | |
| def parse_inline_cites(text: str) -> list[tuple[str, str]]: | |
| """Return ``(file, page_or_slide)`` pairs from inline ``[file, page]`` markers.""" | |
| out: list[tuple[str, str]] = [] | |
| seen: set[tuple[str, str]] = set() | |
| for match in _INLINE_CITE.finditer(text or ""): | |
| file_name = match.group(1).strip() | |
| page = match.group(2).strip() | |
| if not file_name or not page: | |
| continue | |
| key = (file_name, page) | |
| if key in seen: | |
| continue | |
| seen.add(key) | |
| out.append(key) | |
| return out | |
| def _cells(row: str) -> list[str]: | |
| m = _PIPE_ROW.match(row) | |
| if not m: | |
| return [] | |
| return [c.strip() for c in m.group(1).split("|")] | |
| def _is_sep_row(row: str) -> bool: | |
| return bool(_TABLE_SEP.match(row)) | |
| def _format_bullet(cells: list[str]) -> str: | |
| if not cells: | |
| return "" | |
| head = cells[0] | |
| if not head.startswith("**"): | |
| head = f"**{head}**" | |
| rest = [c for c in cells[1:] if c] | |
| if not rest: | |
| return f"- {head}" | |
| return f"- {head} — " + " · ".join(rest) | |
| def sanitize_answer(text: str) -> str: | |
| """Flatten GFM pipe tables into bullet lists; leave other prose intact. | |
| Fail-open: on any unexpected shape, strip separator rows and emit bullets for | |
| remaining pipe rows rather than raising. | |
| """ | |
| raw = text if isinstance(text, str) else str(text or "") | |
| if "|" not in raw: | |
| return raw | |
| try: | |
| lines = raw.splitlines() | |
| out: list[str] = [] | |
| i = 0 | |
| n = len(lines) | |
| while i < n: | |
| line = lines[i] | |
| cells = _cells(line) | |
| if cells and i + 1 < n and _is_sep_row(lines[i + 1]): | |
| # Header + separator (+ optional data rows) → bullets | |
| i += 2 | |
| # Skip emitting a bare header-only bullet when data rows follow; | |
| # include header cells as the first bullet when there is no data. | |
| data_rows: list[list[str]] = [] | |
| while i < n: | |
| data = _cells(lines[i]) | |
| if not data or _is_sep_row(lines[i]): | |
| break | |
| data_rows.append(data) | |
| i += 1 | |
| if data_rows: | |
| for data in data_rows: | |
| # Prefer "**first col** — rest" using data cells (header often redundant) | |
| out.append(_format_bullet(data)) | |
| else: | |
| out.append(_format_bullet(cells)) | |
| continue | |
| if cells and _is_sep_row(line): | |
| i += 1 | |
| continue | |
| if cells and any("|" in c or c for c in cells): | |
| # Orphan pipe row (no separator) — still flatten | |
| out.append(_format_bullet(cells)) | |
| i += 1 | |
| continue | |
| out.append(line) | |
| i += 1 | |
| return "\n".join(out) | |
| except Exception: | |
| # Last resort: drop separator-looking lines, keep text | |
| return "\n".join( | |
| ln for ln in raw.splitlines() if not _is_sep_row(ln) | |
| ) | |
| def _section_key(value: str) -> str: | |
| """Normalised section label from a cite page slot or a passage section ("" if none).""" | |
| text = re.sub(r"\s+", " ", str(value or "")).strip().casefold() | |
| if text.startswith("section "): | |
| text = text[len("section "):].strip() | |
| text = text.split(" › ", 1)[0].strip() # "3.3 X › 3.3.9 Y": the top-level section governs | |
| return text if re.match(r"\d+(?:\.\d+)* \S", text) else "" | |
| def split_cited_related( | |
| passages: list, | |
| answer_text: str, | |
| *, | |
| citation_builder, | |
| threshold: float = 0.35, | |
| ) -> tuple[list[dict], list[dict]]: | |
| """Split threshold-passing passages into Cited (matched inline) vs Related. | |
| ``citation_builder(passage) -> dict`` builds the public citation entry | |
| (handles admin/non-admin file labelling + source_url). | |
| """ | |
| cites = set(parse_inline_cites(answer_text)) | |
| # Passages print their document section after the marker (SIN-0203) and Sonnet was seen | |
| # folding it into the marker: [file, section 3.1 Used cooking oil]. Resolve such a cite to | |
| # every retrieved passage of that file whose section matches, instead of losing it. | |
| section_cites = {(file_name, _section_key(page)) for file_name, page in cites if _section_key(page)} | |
| cited: list[dict] = [] | |
| related: list[dict] = [] | |
| seen_cited: set[tuple[str, str]] = set() | |
| seen_related: set[tuple[str, str]] = set() | |
| for passage in passages or []: | |
| score = float(getattr(passage, "score", 0) or 0) | |
| if score < threshold: | |
| continue | |
| file_name = getattr(passage, "file", "") or "" | |
| page = getattr(passage, "page_or_slide", "") or "" | |
| key = (file_name, page) | |
| entry = citation_builder(passage) | |
| entry_key = (entry.get("file", ""), entry.get("page_or_slide", "")) | |
| section = _section_key(getattr(passage, "section", "") or "") | |
| by_section = bool(section) and ( | |
| (file_name, section) in section_cites or (entry.get("file"), section) in section_cites) | |
| if key in cites or (entry.get("file"), page) in cites or by_section: | |
| if entry_key in seen_cited: | |
| continue | |
| seen_cited.add(entry_key) | |
| cited.append(entry) | |
| else: | |
| if entry_key in seen_related: | |
| continue | |
| seen_related.add(entry_key) | |
| related.append(entry) | |
| return cited, related | |
| # A number the tools never produced is worse than no number: the Apply row | |
| # beside the answer shows the real cohort size, so a stated count that | |
| # disagrees with it is visible to the reader as a contradiction. | |
| _COUNT_NOUNS = { | |
| "holder": "holders", | |
| "holders": "holders", | |
| "collector": "holders", | |
| "collectors": "holders", | |
| "supplier": "holders", | |
| "suppliers": "holders", | |
| "producer": "holders", | |
| "producers": "holders", | |
| "company": "holders", | |
| "companies": "holders", | |
| "certificate": "certificates", | |
| "certificates": "certificates", | |
| } | |
| _COUNT_NOUN_RE = re.compile( | |
| r"\b(" + "|".join(sorted(_COUNT_NOUNS, key=len, reverse=True)) + r")\b", | |
| re.IGNORECASE, | |
| ) | |
| _NUMBER_RE = re.compile(r"\b\d[\d,]*\b") | |
| # "top 5 holders" counts what is shown, not what matched. | |
| _SAMPLE_LEAD_RE = re.compile( | |
| r"(?:top|first|last|up to|a few of|some of|sample of|showing)\s*$", | |
| re.IGNORECASE, | |
| ) | |
| _COUNT_LOOKAHEAD = 70 | |
| # Years and dates are never cohort sizes (SIN-0581: "collected in 2025:** … per | |
| # certificate" lost its year). A year-shaped number counts only when its noun | |
| # follows at once ("2014 certificates"), never after a time word ("in 2025 holders"). | |
| _YEAR_RE = re.compile(r"(?:19|20)\d\d") | |
| _TIME_LEAD_RE = re.compile( | |
| r"\b(?:in|since|from|during|until|till|before|after|by|year|fy|end of|as of)\s*$", | |
| re.IGNORECASE, | |
| ) | |
| _NOUN_AT_ONCE_RE = re.compile(r"[\s*_]*(?:[A-Za-z-]+[\s*_]+)?$") | |
| _DATE_RE = re.compile(r"\b(?:\d{4}-\d{1,2}-\d{1,2}|\d{1,2}[/.]\d{1,2}[/.]\d{2,4})\b") | |
| def correct_stated_counts(text: str, match_count: dict | None) -> str: | |
| """Replace cohort sizes in ``text`` that disagree with the tool result. | |
| Only a number that heads a cohort claim ("14 … collectors", "(14 | |
| certificates)") is touched, and only when the tools actually returned a | |
| count to check it against. | |
| """ | |
| counts = { | |
| key: value | |
| for key, value in (match_count or {}).items() | |
| if isinstance(value, int) and not isinstance(value, bool) | |
| } | |
| if not text or not counts: | |
| return text | |
| out: list[str] = [] | |
| cursor = 0 | |
| for number in _NUMBER_RE.finditer(text): | |
| window = text[number.end(): number.end() + _COUNT_LOOKAHEAD] | |
| noun = _COUNT_NOUN_RE.search(window) | |
| if noun is None or any(char.isdigit() for char in window[: noun.start()]): | |
| continue | |
| truth = counts.get(_COUNT_NOUNS[noun.group(1).lower()]) | |
| if truth is None or _SAMPLE_LEAD_RE.search(text[:number.start()]): | |
| continue | |
| if number.group(0).replace(",", "") == str(truth): | |
| continue | |
| out.append(text[cursor:number.start()]) | |
| out.append(str(truth)) | |
| cursor = number.end() | |
| out.append(text[cursor:]) | |
| return "".join(out) | |
| _BULLET_RE = re.compile(r"^(\s*[-*]\s+)\*\*(?P<name>[^*]+)\*\*", re.MULTILINE) | |
| def _holder_key(value: str) -> str: | |
| return re.sub(r"[^a-z0-9]+", " ", str(value or "").casefold()).strip() | |
| def _is_known_holder(name: str, known_keys: list[str]) -> bool: | |
| """Whether the answer's trading name opens one of the tools' holder names. | |
| Register holder names carry their address ("Ecopor S.A., Jujuy 903, …") | |
| while answers print the trading name, so the answer's name is matched as | |
| the opening of a returned one rather than for equality. | |
| """ | |
| key = _holder_key(name) | |
| if not key: | |
| return False | |
| return any( | |
| candidate == key or candidate.startswith(f"{key} ") | |
| for candidate in known_keys | |
| ) | |
| def drop_unverified_holders(text: str, known_holders) -> str: | |
| """Remove bulleted holders that no tool returned this turn. | |
| A named company in the wrong cohort is worse than a wrong total, so a | |
| name the tools never produced is dropped rather than shown. Pruning only | |
| happens inside a list already proven to be holders — at least one sibling | |
| bullet must match a returned holder — so material lists, which share the | |
| bullet shape, are never touched. | |
| """ | |
| known_keys = [_holder_key(item) for item in (known_holders or [])] | |
| known_keys = [key for key in known_keys if key] | |
| if not text or not known_keys: | |
| return text | |
| bullets = list(_BULLET_RE.finditer(text)) | |
| if not bullets: | |
| return text | |
| verdicts = [_is_known_holder(m.group("name"), known_keys) for m in bullets] | |
| if not any(verdicts) or all(verdicts): | |
| return text | |
| drop_spans = [] | |
| for bullet, verified in zip(bullets, verdicts): | |
| if verified: | |
| continue | |
| end = text.find("\n", bullet.start()) | |
| drop_spans.append((bullet.start(), len(text) if end == -1 else end + 1)) | |
| out = [] | |
| cursor = 0 | |
| for start, end in drop_spans: | |
| out.append(text[cursor:start]) | |
| cursor = end | |
| out.append(text[cursor:]) | |
| return "".join(out) | |
| # The system prompt already forbids naming internal tool APIs, but a prompt | |
| # rule alone has been violated before ("`cb_pairing_check` needs a named CB + | |
| # country pair…" reached a user). Tool identifiers are snake_case strings that | |
| # never occur in legitimate answer prose, so scrubbing them mechanically is | |
| # safe: a parenthetical naming one is dropped whole, any other mention takes | |
| # its containing sentence with it — mechanics without the identifier still | |
| # read as broken internals talk. | |
| _SENTENCE_END = re.compile(r"[.!?](?=\s|$)") | |
| def _drop_span(line: str, start: int, end: int) -> str: | |
| merged = line[:start] + line[end:] | |
| merged = re.sub(r"\s+([.,;:!?])", r"\1", merged) | |
| return re.sub(r" +", " ", merged) | |
| def scrub_internal_tool_names(text: str, tool_names) -> str: | |
| """Remove sentences/parentheticals that name an internal tool API.""" | |
| names = sorted({str(n) for n in (tool_names or []) if n}, key=len, reverse=True) | |
| if not text or not names: | |
| return text | |
| pattern = re.compile( | |
| r"\b(?:" + "|".join(re.escape(n) for n in names) + r")\b" | |
| ) | |
| out_lines: list[str] = [] | |
| for line in text.split("\n"): | |
| match = pattern.search(line) | |
| while match is not None: | |
| open_idx = line.rfind("(", 0, match.start()) | |
| close_idx = line.find(")", match.end()) | |
| enclosed = ( | |
| open_idx != -1 | |
| and close_idx != -1 | |
| and ")" not in line[open_idx: match.start()] | |
| ) | |
| if enclosed: | |
| line = _drop_span(line, open_idx, close_idx + 1).rstrip() | |
| else: | |
| starts = [ | |
| m.end() for m in _SENTENCE_END.finditer(line[: match.start()]) | |
| ] | |
| start = starts[-1] if starts else 0 | |
| end_match = _SENTENCE_END.search(line, match.end()) | |
| end = end_match.end() if end_match else len(line) | |
| line = _drop_span(line, start, end) | |
| match = pattern.search(line) | |
| line = line.rstrip() | |
| if re.fullmatch(r"\s*[-*]\s*", line): | |
| continue | |
| out_lines.append(line) | |
| return "\n".join(out_lines).strip() | |
| def _cohort_count_matches(text: str): | |
| """Yield the number matches that head a cohort claim ("14 … collectors").""" | |
| for number in _NUMBER_RE.finditer(text): | |
| window = text[number.end(): number.end() + _COUNT_LOOKAHEAD] | |
| noun = _COUNT_NOUN_RE.search(window) | |
| if noun is None or any(char.isdigit() for char in window[: noun.start()]): | |
| continue | |
| if _SAMPLE_LEAD_RE.search(text[:number.start()]): | |
| continue | |
| if _is_year_or_date(text, number, window[: noun.start()]): | |
| continue | |
| yield number | |
| def _is_year_or_date(text: str, number, before_noun: str) -> bool: | |
| start = number.start() | |
| # Part of a date: 2026-10-11, 11/10/2025, 11.10.2025. | |
| if any(date.start() <= start < date.end() for date in _DATE_RE.finditer(text)): | |
| return True | |
| if not _YEAR_RE.fullmatch(number.group(0)): | |
| return False | |
| if _TIME_LEAD_RE.search(text[:start]): | |
| return True | |
| return _NOUN_AT_ONCE_RE.fullmatch(before_noun) is None | |
| def stated_cohort_counts(text: str) -> list[int]: | |
| """Every holder / certificate count the answer states, in reading order.""" | |
| return [ | |
| int(number.group(0).replace(",", "")) | |
| for number in _cohort_count_matches(text or "") | |
| ] | |
| # A line left with count nouns and connectives only ("**Combined:** **distinct | |
| # holders** and **certificates**") is a label with its figures cut out — it | |
| # promises a number the reader never gets. | |
| _DANGLING_FILLER = frozenset(_COUNT_NOUNS) | frozenset({ | |
| "a", "an", "the", "and", "or", "of", "in", "is", "are", "there", "total", | |
| "totals", "combined", "distinct", "unique", "overall", "all", "both", | |
| "across", "together", "schemes", "scheme", "registers", "register", | |
| "with", "plus", "only", "number", "numbers", "count", "counts", | |
| }) | |
| _LINE_LABEL_RE = re.compile(r"^\s*(?:[-*]\s+)?[^:]{1,40}:\s*") | |
| def _is_dangling_count_label(line: str) -> bool: | |
| plain = re.sub(r"[*_`]+", "", line) | |
| plain = _LINE_LABEL_RE.sub("", plain, count=1) | |
| words = re.findall(r"[A-Za-z]+", plain) | |
| return bool(words) and all(word.lower() in _DANGLING_FILLER for word in words) | |
| def dangling_count_labels(text: str) -> list[str]: | |
| """Lines that name a holder / certificate total without stating one.""" | |
| return [ | |
| line for line in (text or "").split("\n") | |
| if _COUNT_NOUN_RE.search(line) and not any(ch.isdigit() for ch in line) | |
| and _is_dangling_count_label(line) | |
| ] | |
| def suppress_unverified_counts(text: str, known_counts) -> str: | |
| """Delete a cohort size that no tool returned this turn. | |
| The number is removed rather than replaced: that it is wrong is provable, | |
| which of the turn's counts was meant is not. "14 UCO collectors" becomes | |
| "UCO collectors" — short of an answer, but never a figure nobody computed. | |
| A line that the cut leaves as a bare label ("**Combined:** **distinct | |
| holders** and **certificates**") is dropped whole: an empty numeric claim | |
| reads as a defect, not as caution. | |
| """ | |
| counts = { | |
| value for value in (known_counts or set()) | |
| if isinstance(value, int) and not isinstance(value, bool) | |
| } | |
| if not text or not counts: | |
| return text | |
| out_lines: list[str] = [] | |
| for line in text.split("\n"): | |
| out: list[str] = [] | |
| cursor = 0 | |
| cut = False | |
| for number in _cohort_count_matches(line): | |
| if int(number.group(0).replace(",", "")) in counts: | |
| continue | |
| cut = True | |
| out.append(line[cursor:number.start()]) | |
| cursor = number.end() | |
| while cursor < len(line) and line[cursor] == " ": | |
| cursor += 1 | |
| out.append(line[cursor:]) | |
| rebuilt = "".join(out) | |
| if cut and _is_dangling_count_label(rebuilt): | |
| continue | |
| out_lines.append(rebuilt) | |
| return "\n".join(out_lines) | |