|
| 1 | +from haystack.components.preprocessors import DocumentCleaner |
| 2 | +from haystack.components.embedders import OpenAIDocumentEmbedder |
| 3 | +from haystack import Pipeline |
| 4 | +from haystack.components.embedders import OpenAIDocumentEmbedder |
| 5 | +from haystack.components.preprocessors import DocumentCleaner |
| 6 | +from haystack.components.preprocessors import DocumentSplitter |
| 7 | +from haystack.components.writers import DocumentWriter |
| 8 | +from haystack.document_stores.types import DuplicatePolicy |
| 9 | +from haystack.document_stores.in_memory import InMemoryDocumentStore |
| 10 | +from haystack.utils import Secret |
| 11 | +from haystack_integrations.document_stores.elasticsearch import ElasticsearchDocumentStore |
| 12 | + |
| 13 | + |
| 14 | +from haystack import component, Document |
| 15 | +from typing import Any, Dict, List, Optional, Union |
| 16 | +from haystack.dataclasses import ByteStream |
| 17 | + |
| 18 | +import json |
| 19 | +from dotenv import load_dotenv |
| 20 | +import os |
| 21 | + |
| 22 | +import re |
| 23 | +from bs4 import BeautifulSoup |
| 24 | +from pathlib import Path |
| 25 | + |
| 26 | +import logging |
| 27 | + |
| 28 | +load_dotenv(".env") |
| 29 | +open_ai_key = os.environ.get("OPENAI_API_KEY") |
| 30 | + |
| 31 | +logging.basicConfig(level=logging.INFO) |
| 32 | +logger = logging.getLogger(__name__) |
| 33 | + |
| 34 | +import json |
| 35 | + |
| 36 | +def read_jsonl_file(file_path): |
| 37 | + """ |
| 38 | + Reads a JSONL (JSON Lines) file and returns a list of dictionaries representing each valid JSON object. |
| 39 | + Lines with JSON decoding errors are skipped. |
| 40 | + |
| 41 | + :param file_path: The path to the JSONL file. |
| 42 | + :return: A list of dictionaries, each representing a parsed JSON object. |
| 43 | + """ |
| 44 | + data = [] |
| 45 | + |
| 46 | + try: |
| 47 | + with open(file_path, 'r') as file: |
| 48 | + for line in file: |
| 49 | + try: |
| 50 | + # Attempt to load the JSON data from the current line |
| 51 | + json_data = json.loads(line) |
| 52 | + data.append(json_data) |
| 53 | + except json.JSONDecodeError as e: |
| 54 | + # Print an error message for any lines that can't be decoded |
| 55 | + print(f"Error decoding JSON on line: {line[:30]}... - {e}") |
| 56 | + except FileNotFoundError as e: |
| 57 | + print(f"File not found: {e}") |
| 58 | + |
| 59 | + return data |
| 60 | + |
| 61 | + |
| 62 | +@component |
| 63 | +class BenzingaNews: |
| 64 | + |
| 65 | + @component.output_types(documents=List[Document]) |
| 66 | + def run(self, sources: Dict[str, Any]) -> None: |
| 67 | + |
| 68 | + documents = [] |
| 69 | + for source in sources: |
| 70 | + |
| 71 | + for key in source: |
| 72 | + if type(source[key]) == str: |
| 73 | + source[key] = self.clean_text(source[key]) |
| 74 | + |
| 75 | + if source['content'] == "": |
| 76 | + continue |
| 77 | + |
| 78 | + #drop content from source dictionary |
| 79 | + content = source['content'] |
| 80 | + document = Document(content=content, meta=source) |
| 81 | + |
| 82 | + documents.append(document) |
| 83 | + |
| 84 | + return {"documents": documents} |
| 85 | + |
| 86 | + def clean_text(self, text): |
| 87 | + # Remove HTML tags using BeautifulSoup |
| 88 | + soup = BeautifulSoup(text, "html.parser") |
| 89 | + text = soup.get_text() |
| 90 | + # Remove extra whitespace |
| 91 | + text = re.sub(r'\s+', ' ', text).strip() |
| 92 | + return text |
| 93 | + |
| 94 | +@component |
| 95 | +class BenzingaEmbeder: |
| 96 | + |
| 97 | + def __init__(self): |
| 98 | + get_news = BenzingaNews() |
| 99 | + document_store = ElasticsearchDocumentStore(embedding_similarity_function="cosine", hosts = "http://localhost:9200") |
| 100 | + document_cleaner = DocumentCleaner( |
| 101 | + remove_empty_lines=True, |
| 102 | + remove_extra_whitespaces=True, |
| 103 | + remove_repeated_substrings=False |
| 104 | + ) |
| 105 | + document_splitter = DocumentSplitter(split_by="passage", split_length=5) |
| 106 | + document_writer = DocumentWriter(document_store=document_store, |
| 107 | + policy = DuplicatePolicy.OVERWRITE) |
| 108 | + embedding = OpenAIDocumentEmbedder(api_key=Secret.from_token(open_ai_key)) |
| 109 | + |
| 110 | + self.pipeline = Pipeline() |
| 111 | + self.pipeline.add_component("get_news", get_news) |
| 112 | + self.pipeline.add_component("document_cleaner", document_cleaner) |
| 113 | + self.pipeline.add_component("document_splitter", document_splitter) |
| 114 | + self.pipeline.add_component("embedding", embedding) |
| 115 | + self.pipeline.add_component("document_writer", document_writer) |
| 116 | + |
| 117 | + self.pipeline.connect("get_news", "document_cleaner") |
| 118 | + self.pipeline.connect("document_cleaner", "document_splitter") |
| 119 | + self.pipeline.connect("document_splitter", "embedding") |
| 120 | + self.pipeline.connect("embedding", "document_writer") |
| 121 | + |
| 122 | + |
| 123 | + @component.output_types(documents=List[Document]) |
| 124 | + def run(self, event: List[Union[str, Path, ByteStream]]): |
| 125 | + |
| 126 | + documents = self.pipeline.run({"get_news": {"sources": [event]}}) |
| 127 | + |
| 128 | + self.pipeline.draw("benzinga_pipeline.png") |
| 129 | + return documents |
| 130 | + |
| 131 | + |
| 132 | +document_embedder = BenzingaEmbeder() |
| 133 | +data = read_jsonl_file("./news_out.jsonl") |
| 134 | + |
| 135 | + |
| 136 | +for ite in data: |
| 137 | + print(document_embedder.run(ite)) |
0 commit comments