|
| 1 | +import os |
| 2 | +import tempfile |
| 3 | +from typing import Generator, Union |
| 4 | + |
| 5 | +import tiktoken |
| 6 | +from openai import OpenAI |
| 7 | +from pypdf import PdfReader |
| 8 | + |
| 9 | +from hamilton.htypes import Collect, Parallelizable |
| 10 | + |
| 11 | + |
| 12 | +def openai_client() -> OpenAI: |
| 13 | + return OpenAI(api_key=os.environ["OPENAI_API_KEY"]) |
| 14 | + |
| 15 | + |
| 16 | +def raw_text(pdf_source: Union[str, bytes, tempfile.SpooledTemporaryFile]) -> str: |
| 17 | + """Takes a filepath to a PDF and returns a string of the PDF's contents |
| 18 | + :param pdf_source: the path, or the temporary file, to the PDF. |
| 19 | + :return: the text of the PDF. |
| 20 | + """ |
| 21 | + reader = PdfReader(pdf_source) |
| 22 | + _pdf_text = "" |
| 23 | + page_number = 0 |
| 24 | + for page in reader.pages: |
| 25 | + page_number += 1 |
| 26 | + _pdf_text += page.extract_text() + f"\nPage Number: {page_number}" |
| 27 | + return _pdf_text |
| 28 | + |
| 29 | + |
| 30 | +def tokenizer(tokenizer_encoding: str = "cl100k_base") -> tiktoken.core.Encoding: |
| 31 | + """Get OpenAI tokenizer""" |
| 32 | + return tiktoken.get_encoding(tokenizer_encoding) |
| 33 | + |
| 34 | + |
| 35 | +def _create_chunks( |
| 36 | + text: str, tokenizer: tiktoken.core.Encoding, max_length: int |
| 37 | +) -> Generator[str, None, None]: |
| 38 | + """Return successive chunks of size `max_length` tokens from provided text. |
| 39 | + Split a text into smaller chunks of size n, preferably ending at the end of a sentence |
| 40 | + """ |
| 41 | + tokens = tokenizer.encode(text) |
| 42 | + i = 0 |
| 43 | + while i < len(tokens): |
| 44 | + # Find the nearest end of sentence within a range of 0.5 * n and 1.5 * n tokens |
| 45 | + j = min(i + int(1.5 * max_length), len(tokens)) |
| 46 | + while j > i + int(0.5 * max_length): |
| 47 | + # Decode the tokens and check for full stop or newline |
| 48 | + chunk = tokenizer.decode(tokens[i:j]) |
| 49 | + if chunk.endswith(".") or chunk.endswith("\n"): |
| 50 | + break |
| 51 | + j -= 1 |
| 52 | + # If no end of sentence found, use n tokens as the chunk size |
| 53 | + if j == i + int(0.5 * max_length): |
| 54 | + j = min(i + max_length, len(tokens)) |
| 55 | + yield tokens[i:j] |
| 56 | + i = j |
| 57 | + |
| 58 | + |
| 59 | +def chunked_text( |
| 60 | + raw_text: str, tokenizer: tiktoken.core.Encoding, max_token_length: int = 800 |
| 61 | +) -> list[str]: |
| 62 | + """Tokenize text; create chunks of size `max_token_length`; |
| 63 | + for each chunk, convert tokens back to text string |
| 64 | + """ |
| 65 | + _encoded_chunks = _create_chunks(raw_text, tokenizer, max_token_length) |
| 66 | + _decoded_chunks = [tokenizer.decode(chunk) for chunk in _encoded_chunks] |
| 67 | + return _decoded_chunks |
| 68 | + |
| 69 | + |
| 70 | +def chunk_to_summarize(chunked_text: list[str]) -> Parallelizable[str]: |
| 71 | + """Iterate over chunks that didn't have a stored summary""" |
| 72 | + for chunk in chunked_text: |
| 73 | + yield chunk |
| 74 | + |
| 75 | + |
| 76 | +def _summarize_text__openai(openai_client: OpenAI, prompt: str, openai_gpt_model: str) -> str: |
| 77 | + """Use OpenAI chat API to ask a model to summarize content contained in a prompt""" |
| 78 | + response = openai_client.chat.completions.create( |
| 79 | + model=openai_gpt_model, messages=[{"role": "user", "content": prompt}], temperature=0 |
| 80 | + ) |
| 81 | + return response.choices[0].message.content |
| 82 | + |
| 83 | + |
| 84 | +def prompt_to_summarize_chunk() -> str: |
| 85 | + """Base prompt for summarize a chunk of text""" |
| 86 | + return f"Extract key points with reasoning into a bulleted format.\n\nContent:{{content}}" # noqa: F541 |
| 87 | + |
| 88 | + |
| 89 | +def chunk_summary( |
| 90 | + openai_client: OpenAI, |
| 91 | + chunk_to_summarize: str, |
| 92 | + prompt_to_summarize_chunk: str, |
| 93 | + openai_gpt_model: str, |
| 94 | +) -> str: |
| 95 | + """Fill a base prompt with a chunk's content and summarize it; |
| 96 | + Store the summary in the chunk object |
| 97 | + """ |
| 98 | + filled_prompt = prompt_to_summarize_chunk.format(content=chunk_to_summarize) |
| 99 | + return _summarize_text__openai(openai_client, filled_prompt, openai_gpt_model) |
| 100 | + |
| 101 | + |
| 102 | +def prompt_to_reduce_summaries() -> str: |
| 103 | + """Prompt for a "reduce" operation to summarize a list of summaries into a single text""" |
| 104 | + return f"""Write a summary from this collection of key points. |
| 105 | + First answer the question in two sentences. Then, highlight the core argument, conclusions and evidence. |
| 106 | + User query: {{query}} |
| 107 | + The summary should be structured in bulleted lists following the headings Answer, Core Argument, Evidence, and Conclusions. |
| 108 | + Key points:\n{{chunks_summary}}\nSummary:\n""" # noqa: F541 |
| 109 | + |
| 110 | + |
| 111 | +def chunk_summary_collection(chunk_summary: Collect[str]) -> list[str]: |
| 112 | + """Collect chunks for which a summary was just computed""" |
| 113 | + return chunk_summary |
| 114 | + |
| 115 | + |
| 116 | +def final_summary( |
| 117 | + openai_client: OpenAI, |
| 118 | + query: str, |
| 119 | + chunk_summary_collection: list[str], |
| 120 | + prompt_to_reduce_summaries: str, |
| 121 | + openai_gpt_model: str, |
| 122 | +) -> str: |
| 123 | + """Concatenate the list of chunk summaries into a single text,fill the prompt template, |
| 124 | + and use OpenAI to reduce the content into a single summary; |
| 125 | + """ |
| 126 | + concatenated_summaries = " ".join(chunk_summary_collection) |
| 127 | + filled_prompt = prompt_to_reduce_summaries.format( |
| 128 | + query=query, chunks_summary=concatenated_summaries |
| 129 | + ) |
| 130 | + return _summarize_text__openai(openai_client, filled_prompt, openai_gpt_model) |
| 131 | + |
| 132 | + |
| 133 | +if __name__ == "__main__": |
| 134 | + import summarization |
| 135 | + |
| 136 | + from hamilton import driver |
| 137 | + |
| 138 | + dr = ( |
| 139 | + driver.Builder() |
| 140 | + .enable_dynamic_execution(allow_experimental_mode=True) |
| 141 | + .with_modules(summarization) |
| 142 | + .build() |
| 143 | + ) |
| 144 | + dr.display_all_functions("./docs/summary", {"view": False, "format": "png"}, orient="TB") |
| 145 | + |
| 146 | + inputs = dict( |
| 147 | + pdf_source="./data/hamilton_paper.pdf", |
| 148 | + openai_gpt_model="gpt-3.5-turbo-0613", |
| 149 | + query="What are the main benefits of this tool?", |
| 150 | + ) |
| 151 | + |
| 152 | + results = dr.execute(["final_summary"], inputs=inputs) |
0 commit comments