|
| 1 | +import tempfile |
| 2 | +import os |
| 3 | + |
| 4 | +from dotenv import load_dotenv |
| 5 | +from google.cloud import documentai_v1 as documentai |
| 6 | +from google.api_core.client_options import ClientOptions |
| 7 | + |
| 8 | +import cocoindex |
| 9 | + |
| 10 | +class ToMarkdown(cocoindex.op.FunctionSpec): |
| 11 | + """Convert a PDF to markdown using Google Document AI.""" |
| 12 | + |
| 13 | +@cocoindex.op.executor_class(cache=True, behavior_version=1) |
| 14 | +class DocumentAIExecutor: |
| 15 | + """Executor for Google Document AI to parse files. |
| 16 | + Supported file types: https://cloud.google.com/document-ai/docs/file-types |
| 17 | + """ |
| 18 | + |
| 19 | + spec: ToMarkdown |
| 20 | + _client: documentai.DocumentProcessorServiceClient |
| 21 | + _processor_name: str |
| 22 | + |
| 23 | + def prepare(self): |
| 24 | + # Initialize Document AI |
| 25 | + # You need to set GOOGLE_APPLICATION_CREDENTIALS environment variable |
| 26 | + # or explicitly create credentials and set project_id |
| 27 | + project_id = os.environ.get("GOOGLE_CLOUD_PROJECT_ID") |
| 28 | + location = os.environ.get("GOOGLE_CLOUD_LOCATION", "us") |
| 29 | + processor_id = os.environ.get("GOOGLE_CLOUD_PROCESSOR_ID") |
| 30 | + |
| 31 | + # You must set the api_endpoint if you use a location other than 'us', e.g.: |
| 32 | + opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com") |
| 33 | + self._client = documentai.DocumentProcessorServiceClient(client_options=opts) |
| 34 | + self._processor_name = self._client.processor_path(project_id, location, processor_id) |
| 35 | + |
| 36 | + async def __call__(self, content: bytes) -> str: |
| 37 | + # Create the document object |
| 38 | + document = documentai.Document( |
| 39 | + content=content, |
| 40 | + mime_type="application/pdf" |
| 41 | + ) |
| 42 | + |
| 43 | + # Process the document |
| 44 | + request = documentai.ProcessRequest( |
| 45 | + name=self._processor_name, |
| 46 | + raw_document=documentai.RawDocument(content=content, mime_type="application/pdf") |
| 47 | + ) |
| 48 | + |
| 49 | + response = self._client.process_document(request=request) |
| 50 | + document = response.document |
| 51 | + |
| 52 | + # Extract the text from the document |
| 53 | + text = document.text |
| 54 | + |
| 55 | + # Convert to markdown format |
| 56 | + # This is a simple conversion - you might want to enhance this based on your needs |
| 57 | + # by using document.pages, entities, etc. for more structured markdown |
| 58 | + return text |
| 59 | + |
| 60 | + |
| 61 | +def text_to_embedding(text: cocoindex.DataSlice) -> cocoindex.DataSlice: |
| 62 | + """ |
| 63 | + Embed the text using a SentenceTransformer model. |
| 64 | + """ |
| 65 | + return text.transform( |
| 66 | + cocoindex.functions.SentenceTransformerEmbed( |
| 67 | + model="sentence-transformers/all-MiniLM-L6-v2")) |
| 68 | + |
| 69 | +@cocoindex.flow_def(name="PdfEmbedding") |
| 70 | +def pdf_embedding_flow(flow_builder: cocoindex.FlowBuilder, data_scope: cocoindex.DataScope): |
| 71 | + """ |
| 72 | + Define an example flow that embeds files into a vector database. |
| 73 | + """ |
| 74 | + data_scope["documents"] = flow_builder.add_source(cocoindex.sources.LocalFile(path="pdf_files", binary=True)) |
| 75 | + |
| 76 | + doc_embeddings = data_scope.add_collector() |
| 77 | + |
| 78 | + with data_scope["documents"].row() as doc: |
| 79 | + doc["markdown"] = doc["content"].transform(ToMarkdown()) |
| 80 | + doc["chunks"] = doc["markdown"].transform( |
| 81 | + cocoindex.functions.SplitRecursively(), |
| 82 | + language="markdown", chunk_size=2000, chunk_overlap=500) |
| 83 | + |
| 84 | + with doc["chunks"].row() as chunk: |
| 85 | + chunk["embedding"] = chunk["text"].call(text_to_embedding) |
| 86 | + doc_embeddings.collect(id=cocoindex.GeneratedField.UUID, |
| 87 | + filename=doc["filename"], location=chunk["location"], |
| 88 | + text=chunk["text"], embedding=chunk["embedding"]) |
| 89 | + |
| 90 | + doc_embeddings.export( |
| 91 | + "doc_embeddings", |
| 92 | + cocoindex.storages.Postgres(), |
| 93 | + primary_key_fields=["id"], |
| 94 | + vector_indexes=[ |
| 95 | + cocoindex.VectorIndexDef( |
| 96 | + field_name="embedding", |
| 97 | + metric=cocoindex.VectorSimilarityMetric.COSINE_SIMILARITY)]) |
| 98 | + |
| 99 | +query_handler = cocoindex.query.SimpleSemanticsQueryHandler( |
| 100 | + name="SemanticsSearch", |
| 101 | + flow=pdf_embedding_flow, |
| 102 | + target_name="doc_embeddings", |
| 103 | + query_transform_flow=text_to_embedding, |
| 104 | + default_similarity_metric=cocoindex.VectorSimilarityMetric.COSINE_SIMILARITY) |
| 105 | + |
| 106 | +@cocoindex.main_fn() |
| 107 | +def _run(): |
| 108 | + # Run queries in a loop to demonstrate the query capabilities. |
| 109 | + while True: |
| 110 | + try: |
| 111 | + query = input("Enter search query (or Enter to quit): ") |
| 112 | + if query == '': |
| 113 | + break |
| 114 | + results, _ = query_handler.search(query, 10) |
| 115 | + print("\nSearch results:") |
| 116 | + for result in results: |
| 117 | + print(f"[{result.score:.3f}] {result.data['filename']}") |
| 118 | + print(f" {result.data['text']}") |
| 119 | + print("---") |
| 120 | + print() |
| 121 | + except KeyboardInterrupt: |
| 122 | + break |
| 123 | + |
| 124 | +if __name__ == "__main__": |
| 125 | + load_dotenv(override=True) |
| 126 | + _run() |
0 commit comments