Download scripts/parser.py from dmytrotm/rag: direct link, hf CLI and curl.
- Browser
- Download file 23.7 kB
-
https://huggingface.co/spaces/dmytrotm/rag/resolve/main/scripts/parser.py
- Command line
-
hf download hf://spaces/dmytrotm/rag/scripts/parser.py
-
curl -L -o parser.py https://huggingface.co/spaces/dmytrotm/rag/resolve/main/scripts/parser.py
23.7 kB
| import os | |
| import re | |
| import json | |
| import datetime | |
| from bs4 import BeautifulSoup | |
| from collections import defaultdict | |
| from pathlib import Path | |
| class LegalDocumentParser: | |
| def __init__(self): | |
| self.chunks = [] | |
| self.statistics = defaultdict(int) | |
| def parse_document(self, html_file): | |
| """Main method to parse a single HTML document.""" | |
| print(f"Parsing file: {html_file.name}") | |
| try: | |
| with open(html_file, 'r', encoding='utf-8') as f: | |
| html_content = f.read() | |
| except UnicodeDecodeError: | |
| # Fallback for some windows-1251 legacy files if any | |
| with open(html_file, 'r', encoding='windows-1251') as f: | |
| html_content = f.read() | |
| soup = BeautifulSoup(html_content, 'html.parser') | |
| # 1. Extract Document Metadata | |
| doc_metadata = self.extract_document_metadata(soup, html_file.name) | |
| print(f" Document: {doc_metadata['document_type']}") | |
| # 2. Extract Articles with Hierarchy (Section/Chapter) | |
| articles_data = self.extract_articles_with_hierarchy(soup) | |
| print(f" Found articles: {len(articles_data)}") | |
| # 3. Process each article | |
| for article_data in articles_data: | |
| chunks = self.process_article(article_data, doc_metadata) | |
| if chunks: | |
| self.chunks.extend(chunks) | |
| self.statistics[doc_metadata['document_type']] += 1 | |
| def extract_document_metadata(self, soup, filename): | |
| """Extracts high-level document metadata.""" | |
| doc_type = self.detect_document_type(soup, filename) | |
| taxonomy = self.get_taxonomy(doc_type) | |
| return { | |
| 'document_type': doc_type, | |
| 'document_code': self.extract_document_code(soup), | |
| 'document_name': self.extract_document_name(soup), | |
| 'date_adopted': self.extract_date_adopted(soup), | |
| 'source_file': filename, | |
| 'source_path': f"docs/{filename}", | |
| 'taxonomy': taxonomy | |
| } | |
| def extract_articles_with_hierarchy(self, soup): | |
| """ | |
| Iterates through the document to find articles while tracking | |
| the current Section (Розділ) and Chapter (Глава). | |
| Also detects "Прикінцеві та перехідні положення" (Final/Transitional Provisions) | |
| and handles them separately to avoid polluting regular articles. | |
| """ | |
| articles_data = [] | |
| # Content usually in div#article or body | |
| content_div = soup.find('div', id='article') or soup.body | |
| if not content_div: | |
| return [] | |
| # State trackers | |
| current_section = None | |
| current_chapter = None | |
| in_transitional_provisions = False # Flag for transitional provisions | |
| # Buffer for current article | |
| current_article_lines = [] | |
| current_article_header_text = None | |
| # Pattern to detect article start: "Стаття 1." or "Стаття 1-1." | |
| article_start_pattern = re.compile(r'^Стаття\s+(\d+(?:-\d+)?)\.') | |
| # Patterns for hierarchy | |
| section_pattern = re.compile(r'^Розділ\s+([IVXLCDM\d]+)', re.IGNORECASE) | |
| chapter_pattern = re.compile(r'^Глава\s+(\d+)', re.IGNORECASE) | |
| # Pattern to detect transitional provisions header (should be the main content of the line) | |
| transitional_pattern = re.compile(r'^(?:РОЗДІЛ\s+[IVXLCDM]+\s+)?(?:ПРИКІНЦЕВІ|ПЕРЕХІДНІ)(?:\s+ТА\s+(?:ПРИКІНЦЕВІ|ПЕРЕХІДНІ))?\s+ПОЛОЖЕННЯ$', re.IGNORECASE) | |
| for p in content_div.find_all('p'): | |
| text = p.get_text().strip() | |
| if not text: | |
| continue | |
| # Check for transitional provisions section (Strict match to avoid editorial notes) | |
| if len(text) < 100 and transitional_pattern.search(text): | |
| # Save current article before entering transitional provisions | |
| if current_article_lines: | |
| articles_data.append({ | |
| 'lines': current_article_lines, | |
| 'section': current_section, | |
| 'chapter': current_chapter | |
| }) | |
| current_article_lines = [] | |
| in_transitional_provisions = True | |
| current_section = "Прикінцеві положення" | |
| current_chapter = None | |
| continue | |
| # If in transitional provisions, skip processing (don't create article chunks) | |
| if in_transitional_provisions: | |
| continue | |
| # 1. Check for Hierarchy Changes | |
| # Note: Sections/Chapters are usually own paragraphs | |
| sec_match = section_pattern.match(text) | |
| if sec_match: | |
| current_section = sec_match.group(1) | |
| # Reset chapter when section changes? Usually yes, but implies chapter structure is nested | |
| current_chapter = None | |
| continue | |
| chap_match = chapter_pattern.match(text) | |
| if chap_match: | |
| current_chapter = chap_match.group(1) | |
| continue | |
| # 2. Check for Article Start | |
| art_match = article_start_pattern.match(text) | |
| if art_match: | |
| # Save previous article | |
| if current_article_lines: | |
| articles_data.append({ | |
| 'lines': current_article_lines, | |
| 'section': current_section, | |
| 'chapter': current_chapter | |
| }) | |
| # Start new article | |
| current_article_lines = [text] | |
| current_article_header_text = text # First line usually contains "Стаття X. Title" | |
| else: | |
| # Continue current article | |
| if current_article_lines: | |
| current_article_lines.append(text) | |
| # Save last article (only if not in transitional provisions) | |
| if current_article_lines and not in_transitional_provisions: | |
| articles_data.append({ | |
| 'lines': current_article_lines, | |
| 'section': current_section, | |
| 'chapter': current_chapter | |
| }) | |
| return articles_data | |
| def process_article(self, article_data, doc_metadata): | |
| """ | |
| Process raw article lines into chunks. | |
| Handles text cleaning, splitting, and metadata enrichment. | |
| """ | |
| raw_lines = article_data['lines'] | |
| if not raw_lines: | |
| return [] | |
| # 1. Basic Extraction (Number, Title) | |
| header_text = raw_lines[0] | |
| article_number = self.extract_article_number(header_text) | |
| if not article_number: | |
| return [] | |
| # 2. Reconstruct Full Text for Analysis | |
| full_text = "\n".join(raw_lines) | |
| # 3. Extract Article Title (from first line usually) | |
| article_title = self.extract_article_title(header_text) | |
| # 4. Split into Parts (raw text with notes) | |
| parts = self.split_into_parts(full_text) | |
| total_parts = len(parts) | |
| has_multiple_parts = total_parts > 1 | |
| chunks = [] | |
| for part_num, raw_part_text in parts: | |
| # 5. Clean Text & Extract Editorial Notes (per part) | |
| clean_part_text, part_editorial_notes = self.clean_editorial_notes(raw_part_text) | |
| # Extract last modified date from notes | |
| last_modified = self.extract_last_modified_from_notes(part_editorial_notes) | |
| # 6. Extract References | |
| internal_references = self.extract_references(clean_part_text, article_number) | |
| # 7. Build Chunk ID | |
| chunk_id = self.generate_id(doc_metadata['document_type'], article_number, part_num) | |
| # Format citations | |
| citation_short = self.format_citation_short_ukr(doc_metadata['document_type'], article_number, part_num) | |
| citation_full = self.format_citation_full(doc_metadata['document_name'], article_number, part_num) | |
| # 8. Construct Metadata | |
| chunk_metadata = { | |
| 'document_type': doc_metadata['document_type'], | |
| 'document_code': doc_metadata.get('document_code'), | |
| 'document_name': doc_metadata['document_name'], | |
| 'article_number': article_number, | |
| 'part_number': part_num, | |
| 'article_title': article_title, | |
| 'section': article_data['section'], | |
| 'chapter': article_data['chapter'], | |
| 'date_adopted': doc_metadata.get('date_adopted'), | |
| 'date_effective': doc_metadata.get('date_adopted'), | |
| 'last_modified': last_modified, | |
| 'status': "чинна", | |
| 'category': doc_metadata['taxonomy']['category'], | |
| 'legal_area': doc_metadata['taxonomy']['legal_area'], | |
| 'keywords': doc_metadata['taxonomy']['keywords'], | |
| 'source_file': doc_metadata['source_file'], | |
| 'source_path': doc_metadata['source_path'], | |
| 'citation_format': citation_full, | |
| 'citation_short': citation_short, | |
| 'internal_references': internal_references, | |
| 'editorial_notes': part_editorial_notes, | |
| 'has_note': len(part_editorial_notes) > 0, | |
| 'has_multiple_parts': has_multiple_parts, | |
| 'total_parts': total_parts | |
| } | |
| chunks.append({ | |
| 'id': chunk_id, | |
| 'text': clean_part_text.strip(), | |
| 'metadata': chunk_metadata | |
| }) | |
| return chunks | |
| def clean_editorial_notes(self, text): | |
| """ | |
| Extracts content in curly braces {note} and removes it from text. | |
| Returns: (cleaned_text, list_of_notes) | |
| """ | |
| notes = [] | |
| def replace_func(match): | |
| note_content = match.group(0) | |
| notes.append(note_content) | |
| return "" # Remove from text | |
| # Regex to capture { ... } | |
| # Non-greedy match | |
| cleaned_text = re.sub(r'\{.*?\}', replace_func, text, flags=re.DOTALL) | |
| # Clean up multiple newlines created by removal | |
| cleaned_text = re.sub(r'\n{3,}', '\n\n', cleaned_text) | |
| return cleaned_text, notes | |
| def extract_last_modified_from_notes(self, notes): | |
| """ | |
| Parses editorial notes to find the latest date in format DD.MM.YYYY. | |
| Returns YYYY-MM-DD string or None. | |
| """ | |
| if not notes: | |
| return None | |
| dates = [] | |
| # Pattern for dates in notes: "від 12.01.2023" | |
| date_pattern = re.compile(r'від\s+(\d{2}\.\d{2}\.\d{4})') | |
| for note in notes: | |
| matches = date_pattern.findall(note) | |
| for d_str in matches: | |
| try: | |
| dt = datetime.datetime.strptime(d_str, '%d.%m.%Y') | |
| dates.append(dt) | |
| except ValueError: | |
| pass | |
| if dates: | |
| # Return the latest date found | |
| return max(dates).strftime('%Y-%m-%d') | |
| return None | |
| def split_into_parts(self, text): | |
| """ | |
| Splits text into parts based on "1. " or "186.1. " pattern. | |
| Merges any text appearing BEFORE the first part (the preamble/header) | |
| into the first part found, to avoid creating 'orphan header' chunks. | |
| Ignores list items like "1) " to keep them attached to the parent part. | |
| Returns: [(part_num, text), ...] | |
| """ | |
| parts = [] | |
| lines = text.split('\n') | |
| # Buffer to hold text. Starts accumulating the Preamble. | |
| # When we hit a new Part Number, we flush the buffer to the *previous* part. | |
| # EXCEPTION: If current_part_num is None (we are in Preamble), and we hit Part 1, | |
| # we do NOT flush. We keep the buffer (Header) and just adopt the new part number. | |
| buffer = [] | |
| current_part_num = None | |
| for line in lines: | |
| line = line.strip() | |
| if not line: continue | |
| # Match start of a new part: "1. " or "187.1. " | |
| match = re.match(r'^(\d+(?:\.\d+)?)\.\s+', line) | |
| if match: | |
| new_num = match.group(1) | |
| # If we were strictly tracking a previous part (num is not None), save it. | |
| if current_part_num is not None: | |
| parts.append((current_part_num, "\n".join(buffer))) | |
| buffer = [] | |
| # If current_part_num was None, it means the buffer contains the Preamble/Header. | |
| # We KEEP the buffer, and just switch the ID to the new part. | |
| # Thus: Part 1 = [Header] + [1. Text...] | |
| current_part_num = new_num | |
| buffer.append(line) | |
| else: | |
| buffer.append(line) | |
| # Save the last accumulating part | |
| if buffer: | |
| # If we never found a numbered part, current_part_num is None. | |
| # In that case, the whole text is one chunk (p_None), which is handled later as p_1 or base. | |
| parts.append((current_part_num, "\n".join(buffer))) | |
| return parts | |
| def extract_references(self, text, current_article_number=None): | |
| """ | |
| Finds citations like "ст. 123", "статті 5". | |
| Ignores self-references. | |
| Returns list of objects: [{"article_number": "..."}] | |
| """ | |
| refs = [] | |
| seen = set() | |
| # Regex for 'ст. 5', 'статті 5' | |
| matches = re.finditer(r'(?:ст\.|статт[а-ї-я]+)\s+(\d+(?:-\d+)?)', text, re.IGNORECASE) | |
| for m in matches: | |
| ref_num = m.group(1) | |
| if ref_num != current_article_number and ref_num not in seen: | |
| refs.append({ | |
| "article_number": ref_num | |
| }) | |
| seen.add(ref_num) | |
| return sorted(refs, key=lambda x: (len(x['article_number']), x['article_number'])) | |
| def extract_article_number(self, header_line): | |
| """Extracts X from 'Стаття X. Title'""" | |
| match = re.search(r'Стаття\s+(\d+(?:-\d+)?)', header_line) | |
| return match.group(1) if match else None | |
| def extract_article_title(self, header_line): | |
| """ | |
| Extracts 'Title' from 'Стаття X. Title'. | |
| """ | |
| # Remove 'Стаття X.' part | |
| clean = re.sub(r'^Стаття\s+\d+(?:-\d+)?\.?\s*', '', header_line).strip() | |
| if not clean or clean == '.': | |
| return None | |
| return clean | |
| # --- Helpers --- | |
| def detect_document_type(self, soup, filename): | |
| title = getattr(soup.find('title'), 'text', '') | |
| if "Конституція" in title: return "Конституція України" | |
| if "Кримінальний" in title: return "Кримінальний кодекс України" | |
| if "Цивільний" in title: return "Цивільний кодекс України" | |
| if "Господарський" in title: return "Господарський кодекс України" | |
| if "Сімейний" in title: return "Сімейний кодекс України" | |
| if "Земельний" in title: return "Земельний кодекс України" | |
| if "Податковий" in title: return "Податковий кодекс України" | |
| if "законів про працю" in title: return "Кодекс законів про працю України" | |
| if "адміністративного судочинства" in title: return "Кодекс адміністративного судочинства України" | |
| # Filename fallback | |
| f = filename.lower() | |
| if "constitution" in f: return "Конституція України" | |
| if "criminal" in f: return "Кримінальний кодекс України" | |
| if "civil" in f: return "Цивільний кодекс України" | |
| if "land" in f: return "Земельний кодекс України" | |
| if "tax" in f: return "Податковий кодекс України" | |
| if "family" in f: return "Сімейний кодекс України" | |
| if "work" in f: return "Кодекс законів про працю України" | |
| if "admin" in f: return "Кодекс адміністративного судочинства України" | |
| return "Unknown Document" | |
| def get_taxonomy(self, doc_type): | |
| """Returns legal_area, category, and keywords based on doc type.""" | |
| # Defaults | |
| res = { | |
| "legal_area": "законодавство", | |
| "category": ["кодекс"], | |
| "keywords": [] | |
| } | |
| if doc_type == "Конституція України": | |
| res["legal_area"] = "конституційне_право" | |
| res["category"] = ["конституція", "основний_закон"] | |
| res["keywords"] = ["права_людини", "державний_устрій", "суверенітет"] | |
| elif doc_type == "Кримінальний кодекс України": | |
| res["legal_area"] = "кримінальне_право" | |
| res["keywords"] = ["злочин", "покарання", "відповідальність"] | |
| elif doc_type == "Цивільний кодекс України": | |
| res["legal_area"] = "цивільне_право" | |
| res["keywords"] = ["власність", "договір", "зобов'язання", "спадщина"] | |
| elif doc_type == "Господарський кодекс України": | |
| res["legal_area"] = "господарське_право" | |
| res["keywords"] = ["підприємництво", "господарювання"] | |
| elif doc_type == "Сімейний кодекс України": | |
| res["legal_area"] = "сімейне_право" | |
| res["keywords"] = ["сім'я", "шлюб", "діти", "батьки"] | |
| elif doc_type == "Земельний кодекс України": | |
| res["legal_area"] = "земельне_право" | |
| res["keywords"] = ["земля", "ділянка", "землекористування"] | |
| elif doc_type == "Податковий кодекс України": | |
| res["legal_area"] = "податкове_право" | |
| res["keywords"] = ["податок", "збір", "платник", "ставка"] | |
| elif doc_type == "Кодекс законів про працю України": | |
| res["legal_area"] = "трудове_право" | |
| res["keywords"] = ["праця", "робота", "звільнення", "відпустка"] | |
| elif doc_type == "Кодекс адміністративного судочинства України": | |
| res["legal_area"] = "адміністративне_судочинство" | |
| res["keywords"] = ["суд", "позов", "процес"] | |
| return res | |
| def extract_document_code(self, soup): | |
| title = getattr(soup.find('title'), 'text', '') | |
| match = re.search(r'№\s+([\d\w/\-\s]+)$', title) | |
| return match.group(1).strip() if match else None | |
| def extract_document_name(self, soup): | |
| title = getattr(soup.find('title'), 'text', '') | |
| return title.split('|')[0].strip() | |
| def extract_date_adopted(self, soup): | |
| title = getattr(soup.find('title'), 'text', '') | |
| match = re.search(r'від\s+(\d{2}\.\d{2}\.\d{4})', title) | |
| if match: | |
| try: | |
| return datetime.datetime.strptime(match.group(1), '%d.%m.%Y').strftime('%Y-%m-%d') | |
| except ValueError: pass | |
| return None | |
| def format_citation_short_ukr(self, doc_type, art_num, part_num): | |
| shorts = { | |
| "Конституція України": "КУ", | |
| "Кримінальний кодекс України": "ККУ", | |
| "Цивільний кодекс України": "ЦКУ", | |
| "Господарський кодекс України": "ГКУ", | |
| "Кодекс законів про працю України": "КЗпП", | |
| "Сімейний кодекс України": "СКУ", | |
| "Земельний кодекс України": "ЗКУ", | |
| "Податковий кодекс України": "ПКУ", | |
| "Кодекс адміністративного судочинства України": "КАСУ" | |
| } | |
| short = shorts.get(doc_type, "Закон") | |
| res = f"{short}, ст. {art_num}" | |
| if part_num: res += f", ч. {part_num}" | |
| return res | |
| def format_citation_full(self, doc_name, art_num, part_num): | |
| res = f"{doc_name}, Стаття {art_num}" | |
| if part_num: | |
| res += f", Частина {part_num}" | |
| return res | |
| def generate_id(self, doc_type, art_num, part_num): | |
| shorts = { | |
| "Конституція України": "const", | |
| "Кримінальний кодекс України": "kku", | |
| "Цивільний кодекс України": "cku", | |
| "Господарський кодекс України": "gku", | |
| "Кодекс законів про працю України": "kzpp", | |
| "Сімейний кодекс України": "sku", | |
| "Земельний кодекс України": "zku", | |
| "Податковий кодекс України": "pku", | |
| "Кодекс адміністративного судочинства України": "kasu" | |
| } | |
| short = shorts.get(doc_type, "doc") | |
| base = f"{short}_art_{art_num}" | |
| if part_num: return f"{base}_p_{part_num}" | |
| return base | |
| if __name__ == "__main__": | |
| # Path logic to allow running from scripts/ or root | |
| SCRIPT_DIR = Path(__file__).parent.absolute() | |
| BASE_DIR = SCRIPT_DIR if (SCRIPT_DIR / "docs").exists() else SCRIPT_DIR.parent | |
| parser = LegalDocumentParser() | |
| docs_dir = BASE_DIR / "docs" | |
| data_dir = BASE_DIR / "data" | |
| data_dir.mkdir(exist_ok=True) | |
| if docs_dir.exists(): | |
| for html_file in docs_dir.glob("*.htm"): | |
| parser.parse_document(html_file) | |
| # Statistics | |
| print("\nStatistics:") | |
| for dt, count in parser.statistics.items(): | |
| print(f"{dt}: {count} chunks") | |
| output_file = data_dir / "parsed_chunks.json" | |
| with open(output_file, "w", encoding="utf-8") as f: | |
| json.dump(parser.chunks, f, ensure_ascii=False, indent=2) | |
| print(f"\nSaved {len(parser.chunks)} chunks to {output_file}") | |
| else: | |
| print(f"Error: {docs_dir} directory not found.") | |