import os import json from pathlib import Path from typing import List, Dict class KBArticleProcessor: def __init__(self, kb_folder: str = "data/kb_articles"): self.kb_folder = kb_folder self.articles = [] def parse_article_txt(self, file_path: str) -> Dict: """Parse a single KB article .txt file""" try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # Extract title (first line after "Title:") lines = content.split('\n') title = "" url = "" article_content = [] for i, line in enumerate(lines): if line.startswith("Title:"): title = line.replace("Title:", "").strip() elif line.startswith("URL:"): url = line.replace("URL:", "").strip() elif "=" * 20 in line: # Skip separator line # Content starts after this line article_content = lines[i+1:] break # Join content and clean up content_text = '\n'.join(article_content).strip() # Extract article ID from filename (e.g., article_290.txt -> 290) article_id = Path(file_path).stem.replace('article_', '') return { 'title': title, 'url': url, 'content': content_text, 'article_id': article_id, 'type': 'kb_article' } except Exception as e: print(f"Error processing {file_path}: {str(e)}") return None def process_all_articles(self) -> List[Dict]: """Process all .txt KB articles in the folder""" txt_files = list(Path(self.kb_folder).glob("article_*.txt")) print(f"Found {len(txt_files)} KB article files in {self.kb_folder}\n") for txt_file in txt_files: print(f"Processing: {txt_file.name}") article = self.parse_article_txt(str(txt_file)) if article: self.articles.append(article) print(f" ✓ {article['title'][:60]}... ({len(article['content'])} chars)\n") return self.articles def save_to_json(self, output_file: str = "data/kb_articles.json"): """Save processed KB articles to JSON""" with open(output_file, 'w', encoding='utf-8') as f: json.dump(self.articles, f, indent=2, ensure_ascii=False) print(f"✓ Saved {len(self.articles)} KB articles to {output_file}") # Print summary print("\nKB Articles Summary:") total_chars = sum(len(a['content']) for a in self.articles) print(f" Total articles: {len(self.articles)}") print(f" Total content: {total_chars:,} characters\n") for article in self.articles: print(f" - [{article['article_id']}] {article['title'][:60]}...") def merge_all_documents(self, existing_file: str = "data/all_arlo_docs.json", output_file: str = "data/complete_arlo_docs.json"): """Merge KB articles with existing docs (PDFs + scraped pages)""" # Load existing docs if os.path.exists(existing_file): with open(existing_file, 'r', encoding='utf-8') as f: existing_docs = json.load(f) else: existing_docs = [] # Combine all documents all_docs = existing_docs + self.articles # Save combined with open(output_file, 'w', encoding='utf-8') as f: json.dump(all_docs, f, indent=2, ensure_ascii=False) print(f"\n{'='*60}") print(f"✓ COMPLETE DATASET READY!") print(f"{'='*60}") print(f"Saved to: {output_file}") print(f"\nTotal documents: {len(all_docs)}") print(f" - Scraped web pages: 2") print(f" - PDF documents: 3") print(f" - KB articles: {len(self.articles)}") print(f"\nTotal content: {sum(len(d.get('content', '')) for d in all_docs):,} characters") print(f"{'='*60}\n") return all_docs # Run the processor if __name__ == "__main__": processor = KBArticleProcessor(kb_folder="data/kb_articles") # Process all KB article .txt files articles = processor.process_all_articles() # Save KB articles to JSON processor.save_to_json("data/kb_articles.json") # Merge everything: PDFs + scraped pages + KB articles complete_dataset = processor.merge_all_documents( existing_file="data/all_arlo_docs.json", output_file="data/complete_arlo_docs.json" ) print("✅ Ready to build RAG pipeline!")