Spaces:
Sleeping
Sleeping
Download footnote_parser.py from bdschi1/financial-model-builder-v2: direct link, hf CLI and curl.
- Browser
- Download file 9.38 kB
-
https://huggingface.co/spaces/bdschi1/financial-model-builder-v2/resolve/main/footnote_parser.py
- Command line
-
hf download hf://spaces/bdschi1/financial-model-builder-v2/footnote_parser.py
-
curl -L -o footnote_parser.py https://huggingface.co/spaces/bdschi1/financial-model-builder-v2/resolve/main/footnote_parser.py
9.38 kB
| """ | |
| Footnote parser β extracts footnote sections from 10-K HTML filings | |
| and uses an LLM for structured analysis of each footnote. | |
| Ported from v17 with v2 LLM provider pattern (llm_provider.get_provider()). | |
| """ | |
| import json | |
| import re | |
| class FootnoteParser: | |
| """Parses 10-K footnotes from HTML, optionally using LLM for structured extraction.""" | |
| def __init__(self, llm=None, company_name: str = ""): | |
| """ | |
| Args: | |
| llm: LLM provider instance from llm_provider.get_provider(). | |
| Must implement generate(prompt, system_prompt=None) -> str. | |
| If None, only parse_footnotes_no_llm() works. | |
| company_name: For context in LLM prompts. | |
| """ | |
| self.llm = llm | |
| self.company = company_name | |
| # ββ HTML β footnote section extraction βββββββββββββββββββββ | |
| def _strip_html(self, html_content: str) -> str: | |
| """Strip HTML tags, scripts, styles β return clean text.""" | |
| text = re.sub(r'<style[^>]*>.*?</style>', '', html_content, | |
| flags=re.DOTALL | re.IGNORECASE) | |
| text = re.sub(r'<script[^>]*>.*?</script>', '', text, | |
| flags=re.DOTALL | re.IGNORECASE) | |
| text = re.sub(r'<[^>]+>', ' ', text) | |
| text = re.sub(r'[ \t]+', ' ', text) | |
| text = re.sub(r'\n\s*\n', '\n', text) | |
| return text | |
| def _find_footnote_sections(self, text: str) -> list[dict]: | |
| """ | |
| Locate footnote boundaries in cleaned text. | |
| Returns list of {"note_number": str, "title": str, "text": str}. | |
| """ | |
| # Primary pattern: "Note 1 β Description" | |
| pattern = re.compile( | |
| r'(?:^|\n)\s*' | |
| r'(?:NOTE|Note)\s+' | |
| r'(\d+)\s*' | |
| r'[β\-β:.]\s*' | |
| r'([^\n]{5,120})', | |
| re.MULTILINE | |
| ) | |
| matches = list(pattern.finditer(text)) | |
| if not matches: | |
| # Alternate pattern: "1. Summary of Significant..." | |
| pattern2 = re.compile( | |
| r'(?:^|\n)\s*(\d{1,2})\.\s+' | |
| r'((?:Summary|Description|Basis|Revenue|Income|' | |
| r'Inventories|Property|Goodwill|Intangible|Debt|' | |
| r'Lease|Commitment|Contingenc|Stock|Share|Fair|' | |
| r'Segment|Related|Subsequent|Pension|Benefit|' | |
| r'Accumulated|Earnings|Tax|Financial|Derivative|' | |
| r'Investment|Acquisition|Restructuring|' | |
| r'Accounting|Consolidat)[^\n]{3,120})', | |
| re.MULTILINE | re.IGNORECASE | |
| ) | |
| matches = list(pattern2.finditer(text)) | |
| footnotes = [] | |
| for i, match in enumerate(matches): | |
| note_num = match.group(1) | |
| title = match.group(2).strip() | |
| start_pos = match.end() | |
| # End at next footnote or 15000 chars, whichever first | |
| if i + 1 < len(matches): | |
| end_pos = matches[i + 1].start() | |
| else: | |
| end_pos = min(start_pos + 15000, len(text)) | |
| note_text = text[start_pos:end_pos].strip() | |
| footnotes.append({ | |
| "note_number": note_num, | |
| "title": title, | |
| "text": note_text, | |
| }) | |
| return footnotes | |
| # ββ LLM-based analysis βββββββββββββββββββββββββββββββββββββ | |
| def _analyze_footnote(self, footnote: dict) -> dict: | |
| """Send footnote text to LLM for structured analysis.""" | |
| fn_text = footnote.get("text", "") | |
| if len(fn_text) > 6000: | |
| fn_text = fn_text[:6000] + "\n... [truncated]" | |
| system_prompt = ( | |
| "You are a financial analyst reviewing SEC 10-K footnotes. " | |
| "Extract structured information. Respond ONLY with valid JSON." | |
| ) | |
| user_prompt = ( | |
| f"Analyze this footnote from {self.company}'s 10-K filing.\n\n" | |
| f"Footnote: Note {footnote.get('note_number', '?')} β " | |
| f"{footnote.get('title', 'Unknown')}\n\n" | |
| f"Footnote text:\n{fn_text}\n\n" | |
| f"Provide a JSON response with these fields:\n" | |
| f'{{\n' | |
| f' "note_number": {footnote.get("note_number", "?")},\n' | |
| f' "note_title": "...",\n' | |
| f' "key_content_summary": "2-3 sentence summary of the key ' | |
| f'information",\n' | |
| f' "significant_estimates": ["list of significant estimates, ' | |
| f'assumptions, or judgments"],\n' | |
| f' "flags_findings": ["any restatements, error corrections, ' | |
| f'unusual items, or red flags"],\n' | |
| f' "risk_level": "Low|Medium|High",\n' | |
| f' "key_figures": [{{"description": "...", "amount": "...", ' | |
| f'"period": "..."}}]\n' | |
| f'}}' | |
| ) | |
| # v2 LLM provider uses generate(prompt, system_prompt=...) | |
| response = self.llm.generate(user_prompt, system_prompt=system_prompt) | |
| parsed = self._extract_json(response) | |
| if parsed: | |
| # Normalize list fields | |
| for field in ("significant_estimates", "flags_findings"): | |
| val = parsed.get(field, "") | |
| if isinstance(val, str) and val: | |
| parsed[field] = [val] | |
| elif not isinstance(val, list): | |
| parsed[field] = [] | |
| if not isinstance(parsed.get("key_figures"), list): | |
| parsed["key_figures"] = [] | |
| return parsed | |
| # Fallback: return raw text in structured form | |
| return { | |
| "note_number": int(footnote.get("note_number", 0)) or footnote.get("note_number", "?"), | |
| "note_title": footnote.get("title", "Unknown"), | |
| "key_content_summary": response[:500] if response else "No analysis available", | |
| "significant_estimates": [], | |
| "flags_findings": [], | |
| "risk_level": "Low", | |
| "key_figures": [], | |
| } | |
| def _extract_json(self, text: str) -> dict | None: | |
| """Try to extract a JSON object from LLM response text.""" | |
| if not text: | |
| return None | |
| # Direct parse | |
| try: | |
| return json.loads(text) | |
| except (json.JSONDecodeError, TypeError): | |
| pass | |
| # Markdown code fence | |
| match = re.search(r'```(?:json)?\s*(\{.*?\})\s*```', text, re.DOTALL) | |
| if match: | |
| try: | |
| return json.loads(match.group(1)) | |
| except json.JSONDecodeError: | |
| pass | |
| # Any JSON object | |
| match = re.search(r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}', text, re.DOTALL) | |
| if match: | |
| try: | |
| return json.loads(match.group(0)) | |
| except json.JSONDecodeError: | |
| pass | |
| return None | |
| # ββ Public API βββββββββββββββββββββββββββββββββββββββββββββ | |
| def parse_footnotes(self, html_content: str) -> list[dict]: | |
| """ | |
| Extract and analyze footnotes from 10-K HTML. | |
| Requires an LLM provider. Each footnote is sent to the LLM | |
| for structured analysis. | |
| Returns: | |
| [ | |
| { | |
| "note_number": 1, | |
| "note_title": "Summary of Significant Accounting Policies", | |
| "key_content_summary": "...", | |
| "significant_estimates": ["...", ...], | |
| "flags_findings": ["...", ...], | |
| "risk_level": "Low" | "Medium" | "High", | |
| "key_figures": [{"description": str, "amount": str, "period": str}], | |
| }, | |
| ... | |
| ] | |
| """ | |
| if not self.llm: | |
| raise RuntimeError("parse_footnotes requires an LLM provider; " | |
| "use parse_footnotes_no_llm() instead") | |
| text = self._strip_html(html_content) | |
| sections = self._find_footnote_sections(text) | |
| if not sections: | |
| return [] | |
| results = [] | |
| for fn in sections: | |
| try: | |
| analysis = self._analyze_footnote(fn) | |
| results.append(analysis) | |
| except Exception as e: | |
| results.append({ | |
| "note_number": int(fn.get("note_number", 0)) or fn.get("note_number", "?"), | |
| "note_title": fn.get("title", "Unknown"), | |
| "key_content_summary": f"Error during analysis: {e}", | |
| "significant_estimates": [], | |
| "flags_findings": [], | |
| "risk_level": "Low", | |
| "key_figures": [], | |
| "error": str(e), | |
| }) | |
| return results | |
| def parse_footnotes_no_llm(self, html_content: str) -> list[dict]: | |
| """Extract footnote structure without LLM analysis (titles + raw text only).""" | |
| text = self._strip_html(html_content) | |
| sections = self._find_footnote_sections(text) | |
| return [ | |
| { | |
| "note_number": int(fn["note_number"]) if fn["note_number"].isdigit() else fn["note_number"], | |
| "note_title": fn["title"], | |
| "raw_text": fn["text"][:2000], # cap raw text at 2000 chars | |
| } | |
| for fn in sections | |
| ] | |