Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 33 additions & 118 deletions scraping/processing/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,17 @@

from selenium.webdriver.remote.webdriver import WebDriver

from config import Config
from gpt_researcher_old.retriever.llm_utils import create_chat_completion
try:
from gpt_researcher.config.config import Config
except ImportError:
Config = None

try:
from gpt_researcher.utils.llm import create_chat_completion
except ImportError:
create_chat_completion = None

import os
from md2pdf.core import md2pdf


def split_text(text: str, max_length: int = 8192) -> Generator[str, None, None]:
Expand Down Expand Up @@ -43,131 +50,39 @@ def split_text(text: str, max_length: int = 8192) -> Generator[str, None, None]:
def summarize_text(
fast_llm_model: str, summary_token_limit: int, llm_provider: str, url: str, text: str, question: str, driver: Optional[WebDriver] = None
) -> str:
"""Summarize text using the OpenAI API
"""Summarize text using the LLM API

Args:
fast_llm_model (str): The fast LLM model e.g gpt3.5-turbo-16k
summary_token_limit (int): The summary token limit
llm_provider (str): The llm provider
url (str): The url of the text
llm_provider (str): The LLM provider (e.g. openai, ollama)
url (str): The URL of the text
text (str): The text to summarize
question (str): The question to ask the model
driver (WebDriver): The webdriver to use to scroll the page
question (str): The question to answer
driver (WebDriver): The webdriver instance

Returns:
str: The summary of the text
"""
if not text:
return "Error: No text to summarize"

summaries = []
chunks = list(split_text(text))
scroll_ratio = 1 / len(chunks)

print(f"Summarizing url: {url} with total chunks: {len(chunks)}")
for i, chunk in enumerate(chunks):
if driver:
scroll_to_percentage(driver, scroll_ratio * i)

#memory_to_add = f"Source: {url}\n" f"Raw content part#{i + 1}: {chunk}"

#MEMORY.add_documents([Document(page_content=memory_to_add)])

messages = [create_message(chunk, question)]

summary = create_chat_completion(
model=fast_llm_model,
messages=messages,
max_tokens=summary_token_limit,
llm_provider=llm_provider
)
summaries.append(summary)
#memory_to_add = f"Source: {url}\n" f"Content summary part#{i + 1}: {summary}"

#MEMORY.add_documents([Document(page_content=memory_to_add)])

combined_summary = "\n".join(summaries)
messages = [create_message(combined_summary, question)]

final_summary = create_chat_completion(
model=fast_llm_model,
messages=messages,
max_tokens=summary_token_limit,
llm_provider=llm_provider,
)
print("Final summary length: ", len(combined_summary))
print(final_summary)

return final_summary


def scroll_to_percentage(driver: WebDriver, ratio: float) -> None:
"""Scroll to a percentage of the page

Args:
driver (WebDriver): The webdriver to use
ratio (float): The percentage to scroll to

Raises:
ValueError: If the ratio is not between 0 and 1
"""
if ratio < 0 or ratio > 1:
raise ValueError("Percentage should be between 0 and 1")
driver.execute_script(f"window.scrollTo(0, document.body.scrollHeight * {ratio});")
return "No text to summarize"

summary = ""
paragraphs = split_text(text, 8192)

def create_message(chunk: str, question: str) -> Dict[str, str]:
"""Create a message for the chat completion

Args:
chunk (str): The chunk of text to summarize
question (str): The question to answer

Returns:
Dict[str, str]: The message to send to the chat completion
"""
return {
"role": "user",
"content": f'"""{chunk}"""\n'
f'Using the above text, summarize it based on the following task or query: "{question}".\n'
f'If the query cannot be answered using the text, YOU MUST summarize the text in short.\n'
f'Include all factual information such as numbers, stats, quotes, etc if available.',
}

def write_to_file(filename: str, text: str) -> None:
"""Write text to a file

Args:
text (str): The text to write
filename (str): The filename to write to
"""
with open(filename, "w") as file:
file.write(text)

async def write_md_to_pdf(task: str, path: str, text: str) -> None:
file_path = f"{path}/{task}"
write_to_file(f"{file_path}.md", text)
md_to_pdf(f"{file_path}.md", f"{file_path}.pdf")
print(f"{task} written to {file_path}.pdf")

encoded_file_path = urllib.parse.quote(f"{file_path}.pdf")

return encoded_file_path

def read_txt_files(directory):
all_text = ''

for filename in os.listdir(directory):
if filename.endswith('.txt'):
with open(os.path.join(directory, filename), 'r') as file:
all_text += file.read() + '\n'

return all_text

for paragraph in paragraphs:
if create_chat_completion:
summary = create_chat_completion(
model=fast_llm_model,
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": f"Summarize the following text for the question: '{question}':\n\n{paragraph}"},
],
temperature=0.5,
max_tokens=summary_token_limit,
provider=llm_provider,
)
else:
summary = paragraph[:summary_token_limit]

def md_to_pdf(input_file, output_file):
md2pdf(output_file,
md_content=None,
md_file_path=input_file,
css_file_path=None,
base_url=None)
return summary
30 changes: 30 additions & 0 deletions tests/test_text_chunking.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""Unit tests for text processing and paragraph chunking generators."""

import pytest
from scraping.processing.text import split_text


def test_split_text_small_input():
"""Verify text shorter than max_length yields single chunk."""
text = "Line 1: Q3 financial report\nLine 2: Revenue surged 15%\nLine 3: Operating margin expanded"
chunks = list(split_text(text, max_length=500))
assert len(chunks) == 1
assert chunks[0] == text


def test_split_text_chunk_boundaries():
"""Verify generator yields multiple chunks when text exceeds max_length."""
paragraphs = [f"Paragraph {i}: " + ("x" * 60) for i in range(10)]
full_text = "\n".join(paragraphs)

# Chunk with max_length of 150
chunks = list(split_text(full_text, max_length=150))
assert len(chunks) > 1

# Ensure every chunk is within limit
for chunk in chunks:
assert len(chunk) <= 150

# Ensure all content is retained
reconstructed = "\n".join(chunks)
assert reconstructed == full_text
Loading