poma 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- poma-0.1.0/LICENSE +177 -0
- poma-0.1.0/PKG-INFO +68 -0
- poma-0.1.0/README.md +38 -0
- poma-0.1.0/poma/__init__.py +15 -0
- poma-0.1.0/poma/client.py +353 -0
- poma-0.1.0/poma/exceptions.py +20 -0
- poma-0.1.0/poma/integrations/__init__.py +20 -0
- poma-0.1.0/poma/integrations/langchain_poma.py +358 -0
- poma-0.1.0/poma/integrations/llamaindex_poma.py +361 -0
- poma-0.1.0/poma/retrieval.py +176 -0
- poma-0.1.0/poma.egg-info/PKG-INFO +68 -0
- poma-0.1.0/poma.egg-info/SOURCES.txt +15 -0
- poma-0.1.0/poma.egg-info/dependency_links.txt +1 -0
- poma-0.1.0/poma.egg-info/requires.txt +21 -0
- poma-0.1.0/poma.egg-info/top_level.txt +1 -0
- poma-0.1.0/pyproject.toml +47 -0
- poma-0.1.0/setup.cfg +4 -0
poma-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
|
|
2
|
+
Mozilla Public License - Version 2.0
|
|
3
|
+
====================================
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
1. Definitions
|
|
7
|
+
--------------
|
|
8
|
+
1.1. “Contributor”
|
|
9
|
+
means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software.
|
|
10
|
+
|
|
11
|
+
1.2. “Contributor Version”
|
|
12
|
+
means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor’s Contribution.
|
|
13
|
+
|
|
14
|
+
1.3. “Contribution”
|
|
15
|
+
means Covered Software of a particular Contributor.
|
|
16
|
+
|
|
17
|
+
1.4. “Covered Software”
|
|
18
|
+
means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof.
|
|
19
|
+
|
|
20
|
+
1.5. “Incompatible With Secondary Licenses”
|
|
21
|
+
means
|
|
22
|
+
that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or
|
|
23
|
+
that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License.
|
|
24
|
+
|
|
25
|
+
1.6. “Executable Form”
|
|
26
|
+
means any form of the work other than Source Code Form.
|
|
27
|
+
|
|
28
|
+
1.7. “Larger Work”
|
|
29
|
+
means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software.
|
|
30
|
+
|
|
31
|
+
1.8. “License”
|
|
32
|
+
means this document.
|
|
33
|
+
|
|
34
|
+
1.9. “Licensable”
|
|
35
|
+
means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License.
|
|
36
|
+
|
|
37
|
+
1.10. “Modifications”
|
|
38
|
+
means any of the following:
|
|
39
|
+
any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or
|
|
40
|
+
any new file in Source Code Form that contains any Covered Software.
|
|
41
|
+
|
|
42
|
+
1.11. “Patent Claims” of a Contributor
|
|
43
|
+
means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version.
|
|
44
|
+
|
|
45
|
+
1.12. “Secondary License”
|
|
46
|
+
means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses.
|
|
47
|
+
|
|
48
|
+
1.13. “Source Code Form”
|
|
49
|
+
means the form of the work preferred for making modifications.
|
|
50
|
+
|
|
51
|
+
1.14. “You” (or “Your”)
|
|
52
|
+
means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity.
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
2. License Grants and Conditions
|
|
56
|
+
--------------------------------
|
|
57
|
+
2.1. Grants
|
|
58
|
+
Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license:
|
|
59
|
+
|
|
60
|
+
under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and
|
|
61
|
+
under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version.
|
|
62
|
+
|
|
63
|
+
2.2. Effective Date
|
|
64
|
+
The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution.
|
|
65
|
+
|
|
66
|
+
2.3. Limitations on Grant Scope
|
|
67
|
+
The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor:
|
|
68
|
+
|
|
69
|
+
for any code that a Contributor has removed from Covered Software; or
|
|
70
|
+
for infringements caused by: (i) Your and any other third party’s modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or
|
|
71
|
+
under Patent Claims infringed by Covered Software in the absence of its Contributions.
|
|
72
|
+
This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4).
|
|
73
|
+
|
|
74
|
+
2.4. Subsequent Licenses
|
|
75
|
+
No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3).
|
|
76
|
+
|
|
77
|
+
2.5. Representation
|
|
78
|
+
Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License.
|
|
79
|
+
|
|
80
|
+
2.6. Fair Use
|
|
81
|
+
This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents.
|
|
82
|
+
|
|
83
|
+
2.7. Conditions
|
|
84
|
+
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1.
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
3. Responsibilities
|
|
88
|
+
-------------------
|
|
89
|
+
3.1. Distribution of Source Form
|
|
90
|
+
All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients’ rights in the Source Code Form.
|
|
91
|
+
|
|
92
|
+
3.2. Distribution of Executable Form
|
|
93
|
+
If You distribute Covered Software in Executable Form then:
|
|
94
|
+
|
|
95
|
+
such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and
|
|
96
|
+
You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License.
|
|
97
|
+
|
|
98
|
+
3.3. Distribution of a Larger Work
|
|
99
|
+
You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s).
|
|
100
|
+
|
|
101
|
+
3.4. Notices
|
|
102
|
+
You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies.
|
|
103
|
+
|
|
104
|
+
3.5. Application of Additional Terms
|
|
105
|
+
You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction.
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
4. Inability to Comply Due to Statute or Regulation
|
|
109
|
+
---------------------------------------------------
|
|
110
|
+
If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it.
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
5. Termination
|
|
114
|
+
--------------
|
|
115
|
+
5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice.
|
|
116
|
+
|
|
117
|
+
5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate.
|
|
118
|
+
|
|
119
|
+
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination.
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
6. Disclaimer of Warranty
|
|
123
|
+
-------------------------
|
|
124
|
+
Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer.
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
7. Limitation of Liability
|
|
128
|
+
--------------------------
|
|
129
|
+
Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party’s negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
8. Litigation
|
|
133
|
+
-------------
|
|
134
|
+
Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party’s ability to bring cross-claims or counter-claims.
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
9. Miscellaneous
|
|
138
|
+
----------------
|
|
139
|
+
This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor.
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
10. Versions of the License
|
|
143
|
+
---------------------------
|
|
144
|
+
10.1. New Versions
|
|
145
|
+
Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number.
|
|
146
|
+
|
|
147
|
+
10.2. Effect of New Versions
|
|
148
|
+
You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward.
|
|
149
|
+
|
|
150
|
+
10.3. Modified Versions
|
|
151
|
+
If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License).
|
|
152
|
+
|
|
153
|
+
10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
|
|
154
|
+
If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached.
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
Exhibit A – Source Code Form License Notice
|
|
158
|
+
-------------------------------------------
|
|
159
|
+
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
160
|
+
|
|
161
|
+
If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice.
|
|
162
|
+
|
|
163
|
+
You may add additional accurate notices of copyright ownership.
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
Exhibit B – “Incompatible With Secondary Licenses” Notice
|
|
167
|
+
---------------------------------------------------------
|
|
168
|
+
This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0.
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
|
poma-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: poma
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for the Poma document-processing API
|
|
5
|
+
Author-email: "POMA AI GmbH, Berlin" <sdk@poma-ai.com>
|
|
6
|
+
License-Expression: MPL-2.0
|
|
7
|
+
Keywords: chunking,structure,rag,poma,documents,ai
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Requires-Dist: httpx==0.28.1
|
|
12
|
+
Requires-Dist: pydantic==2.11.7
|
|
13
|
+
Provides-Extra: integrations
|
|
14
|
+
Requires-Dist: langchain==0.3.27; extra == "integrations"
|
|
15
|
+
Requires-Dist: langchain-text-splitters==0.3.9; extra == "integrations"
|
|
16
|
+
Requires-Dist: llama-index==0.13.0; extra == "integrations"
|
|
17
|
+
Provides-Extra: integration-examples
|
|
18
|
+
Requires-Dist: langchain==0.3.27; extra == "integration-examples"
|
|
19
|
+
Requires-Dist: langchain-text-splitters==0.3.9; extra == "integration-examples"
|
|
20
|
+
Requires-Dist: llama-index==0.13.0; extra == "integration-examples"
|
|
21
|
+
Requires-Dist: llama-index-vector-stores-faiss==0.5.0; extra == "integration-examples"
|
|
22
|
+
Requires-Dist: faiss-cpu==1.10.0; extra == "integration-examples"
|
|
23
|
+
Requires-Dist: langchain_openai==0.3.28; extra == "integration-examples"
|
|
24
|
+
Requires-Dist: langchain_community==0.3.27; extra == "integration-examples"
|
|
25
|
+
Requires-Dist: llama-index-embeddings-langchain==0.4.0; extra == "integration-examples"
|
|
26
|
+
Requires-Dist: dotenv; extra == "integration-examples"
|
|
27
|
+
Provides-Extra: examples
|
|
28
|
+
Requires-Dist: dotenv; extra == "examples"
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+

|
|
32
|
+
# 📚 POMA: Preserving Optimal Markdown Architecture
|
|
33
|
+
|
|
34
|
+
## 🚀Quick-Start Guide
|
|
35
|
+
|
|
36
|
+
### Installation
|
|
37
|
+
|
|
38
|
+
Requires Python 3.10+. Install the core packages:
|
|
39
|
+
```bash
|
|
40
|
+
pip install poma
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
For integrations into LangChain and LlamaIndex:
|
|
44
|
+
```bash
|
|
45
|
+
pip install poma[integrations]
|
|
46
|
+
# Or LangChain/LlamaIndex including example extras:
|
|
47
|
+
pip install poma[integration-examples]
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
- You may also want: `pip install python-dotenv` to load API keys from a .env file.
|
|
52
|
+
- API keys required (POMA_API_KEY) for the POMA AI client via environment variables.
|
|
53
|
+
- **To request a POMA_API_KEY, please contact us at api@poma-ai.com**
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
### Example Implementations — all examples, integrations, and additional information can be found in our GitHub repository: [poma-ai/poma](https://github.com/poma-ai/poma)
|
|
57
|
+
|
|
58
|
+
We provide four example implementations to help you get started with POMA AI:
|
|
59
|
+
- example.py — A standalone implementation for documents, showing the basic POMA AI workflow with simple keyword-based retrieval
|
|
60
|
+
- example_langchain.py — Integration with LangChain, demonstrating how easy it is to use POMA AI with LangChain
|
|
61
|
+
- example_llamaindex.py — Integration with LlamaIndex, showing how simple it is to use POMA AI with LlamaIndex
|
|
62
|
+
|
|
63
|
+
*Note: The integration examples use OpenAI embeddings. Make sure to set your OPENAI_API_KEY environment variable, or replace the embeddings with your preferred ones.*
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
All examples follow the same two-phase process (ingest → retrieve) but demonstrate different integration options for your RAG pipeline.
|
|
67
|
+
|
|
68
|
+
! Please do NOT send any sensitive and/or personal information to POMA AI endpoints without having a signed contract & DPA !
|
poma-0.1.0/README.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+

|
|
2
|
+
# 📚 POMA: Preserving Optimal Markdown Architecture
|
|
3
|
+
|
|
4
|
+
## 🚀Quick-Start Guide
|
|
5
|
+
|
|
6
|
+
### Installation
|
|
7
|
+
|
|
8
|
+
Requires Python 3.10+. Install the core packages:
|
|
9
|
+
```bash
|
|
10
|
+
pip install poma
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
For integrations into LangChain and LlamaIndex:
|
|
14
|
+
```bash
|
|
15
|
+
pip install poma[integrations]
|
|
16
|
+
# Or LangChain/LlamaIndex including example extras:
|
|
17
|
+
pip install poma[integration-examples]
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
- You may also want: `pip install python-dotenv` to load API keys from a .env file.
|
|
22
|
+
- API keys required (POMA_API_KEY) for the POMA AI client via environment variables.
|
|
23
|
+
- **To request a POMA_API_KEY, please contact us at api@poma-ai.com**
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
### Example Implementations — all examples, integrations, and additional information can be found in our GitHub repository: [poma-ai/poma](https://github.com/poma-ai/poma)
|
|
27
|
+
|
|
28
|
+
We provide four example implementations to help you get started with POMA AI:
|
|
29
|
+
- example.py — A standalone implementation for documents, showing the basic POMA AI workflow with simple keyword-based retrieval
|
|
30
|
+
- example_langchain.py — Integration with LangChain, demonstrating how easy it is to use POMA AI with LangChain
|
|
31
|
+
- example_llamaindex.py — Integration with LlamaIndex, showing how simple it is to use POMA AI with LlamaIndex
|
|
32
|
+
|
|
33
|
+
*Note: The integration examples use OpenAI embeddings. Make sure to set your OPENAI_API_KEY environment variable, or replace the embeddings with your preferred ones.*
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
All examples follow the same two-phase process (ingest → retrieve) but demonstrate different integration options for your RAG pipeline.
|
|
37
|
+
|
|
38
|
+
! Please do NOT send any sensitive and/or personal information to POMA AI endpoints without having a signed contract & DPA !
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from .client import Poma
|
|
2
|
+
from .exceptions import (
|
|
3
|
+
PomaSDKError,
|
|
4
|
+
AuthenticationError,
|
|
5
|
+
RemoteServerError,
|
|
6
|
+
InvalidInputError,
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"Poma",
|
|
11
|
+
"PomaSDKError",
|
|
12
|
+
"AuthenticationError",
|
|
13
|
+
"RemoteServerError",
|
|
14
|
+
"InvalidInputError",
|
|
15
|
+
]
|
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
# client.py
|
|
2
|
+
import os
|
|
3
|
+
import httpx
|
|
4
|
+
import zipfile
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import time
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from poma.exceptions import AuthenticationError, InvalidInputError, RemoteServerError, InvalidResponseError
|
|
12
|
+
from poma.retrieval import generate_cheatsheets, generate_single_cheatsheet
|
|
13
|
+
|
|
14
|
+
USER_AGENT = "poma-ai-sdk/0.1.0"
|
|
15
|
+
|
|
16
|
+
ALLOWED_FILE_EXTENSIONS: set[str] = {
|
|
17
|
+
".txt",
|
|
18
|
+
".md",
|
|
19
|
+
".html",
|
|
20
|
+
".htm",
|
|
21
|
+
".pdf",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
API_BASE_URL = "https://api.poma-ai.com/api/v1"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Poma:
|
|
28
|
+
"""
|
|
29
|
+
Client for interacting with the POMA API.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
api_key: str | None = None,
|
|
35
|
+
*,
|
|
36
|
+
timeout: float = 600.0,
|
|
37
|
+
client: httpx.Client | None = None,
|
|
38
|
+
):
|
|
39
|
+
"""
|
|
40
|
+
Initialize the POMA client.
|
|
41
|
+
Args:
|
|
42
|
+
api_key (str, optional):
|
|
43
|
+
API key for authenticating with POMA. If not provided,
|
|
44
|
+
the value is read from the environment variable `POMA_API_KEY`.
|
|
45
|
+
timeout (float, default=600.0):
|
|
46
|
+
Timeout (in seconds) for all HTTP requests.
|
|
47
|
+
client (httpx.Client, optional):
|
|
48
|
+
Custom HTTP client. If not provided, a default client is created.
|
|
49
|
+
"""
|
|
50
|
+
api_base_url = API_BASE_URL
|
|
51
|
+
# Override API base URL if environment variable is set
|
|
52
|
+
if os.environ.get("API_BASE_URL"):
|
|
53
|
+
api_base_url = os.environ.get("API_BASE_URL")
|
|
54
|
+
|
|
55
|
+
self.base_api_url = api_base_url.rstrip("/")
|
|
56
|
+
self._client = client or httpx.Client(timeout=timeout,
|
|
57
|
+
headers={"user-agent": USER_AGENT})
|
|
58
|
+
if not (api_key := api_key or os.environ.get("POMA_API_KEY", "")):
|
|
59
|
+
raise Exception("POMA_API_KEY environment variable not set.")
|
|
60
|
+
self._client.headers.update({"Authorization": f"Bearer {api_key}"})
|
|
61
|
+
|
|
62
|
+
def start_chunk_file(
|
|
63
|
+
self,
|
|
64
|
+
file_path: os.PathLike[str],
|
|
65
|
+
*,
|
|
66
|
+
base_url: str | None = None,
|
|
67
|
+
) -> dict[str, Any]:
|
|
68
|
+
"""
|
|
69
|
+
Submit a file with text to POMA for chunking.
|
|
70
|
+
Args:
|
|
71
|
+
file_path (os.PathLike[str]):
|
|
72
|
+
Path to the input file. Must have an allowed file extension.
|
|
73
|
+
base_url (str, optional):
|
|
74
|
+
Optional base URL to resolve relative links within the file.
|
|
75
|
+
Returns:
|
|
76
|
+
A dictionary containing a unique job identifier for the submitted job.
|
|
77
|
+
"""
|
|
78
|
+
if not file_path or not isinstance(file_path, os.PathLike):
|
|
79
|
+
raise ValueError("file_path must be a non-empty os.PathLike.")
|
|
80
|
+
file_extension = Path(file_path).suffix.lower()
|
|
81
|
+
if file_extension not in ALLOWED_FILE_EXTENSIONS:
|
|
82
|
+
raise InvalidInputError(
|
|
83
|
+
f"File extension of {file_path} is not allowed; use one of the following types: {', '.join(sorted(ALLOWED_FILE_EXTENSIONS))}."
|
|
84
|
+
)
|
|
85
|
+
payload = {}
|
|
86
|
+
if base_url:
|
|
87
|
+
payload["base_url"] = base_url
|
|
88
|
+
try:
|
|
89
|
+
response = self._client.post(
|
|
90
|
+
f"{self.base_api_url}/process",
|
|
91
|
+
data=payload,
|
|
92
|
+
files={
|
|
93
|
+
"file": (Path(file_path).name, Path(file_path).read_bytes()),
|
|
94
|
+
},
|
|
95
|
+
)
|
|
96
|
+
response.raise_for_status()
|
|
97
|
+
except httpx.HTTPStatusError as error:
|
|
98
|
+
status = error.response.status_code
|
|
99
|
+
if status in (401, 403):
|
|
100
|
+
raise AuthenticationError(response.text) from error
|
|
101
|
+
raise RemoteServerError(f"{status}: {response.text}") from error
|
|
102
|
+
try:
|
|
103
|
+
data = response.json()
|
|
104
|
+
except ValueError as error:
|
|
105
|
+
raise InvalidResponseError("Server returned non-JSON or empty body") from error
|
|
106
|
+
return data
|
|
107
|
+
|
|
108
|
+
def get_chunk_result(
|
|
109
|
+
self,
|
|
110
|
+
job_id: str,
|
|
111
|
+
*,
|
|
112
|
+
initial_delay: float = 5.0,
|
|
113
|
+
poll_interval: float = 3.0,
|
|
114
|
+
max_interval: float = 15.0,
|
|
115
|
+
show_progress: bool = False,
|
|
116
|
+
download_dir: str | os.PathLike[str] | None = None,
|
|
117
|
+
) -> dict[str, Any]:
|
|
118
|
+
"""
|
|
119
|
+
Poll POMA for the result of a chunking job until completion.
|
|
120
|
+
Args:
|
|
121
|
+
job_id (str):
|
|
122
|
+
The unique identifier of the submitted job.
|
|
123
|
+
initial_delay (float, default=5.0):
|
|
124
|
+
Initial delay (in seconds) before the first poll request.
|
|
125
|
+
poll_interval (float, default=1.0):
|
|
126
|
+
Starting interval (in seconds) between polling requests.
|
|
127
|
+
max_interval (float, default=15.0):
|
|
128
|
+
Maximum interval (in seconds) between polling requests.
|
|
129
|
+
show_progress (bool, default=False):
|
|
130
|
+
If True, logs progress messages during polling.
|
|
131
|
+
download_dir (str | os.PathLike[str], optional):
|
|
132
|
+
Directory to save the downloaded file in. Required if return_bytes=False.
|
|
133
|
+
return_bytes (bool, default=False):
|
|
134
|
+
If True, returns the file content as bytes instead of saving to disk.
|
|
135
|
+
Returns:
|
|
136
|
+
The JSON result containing at least the keys `chunks` and `chunksets`.
|
|
137
|
+
|
|
138
|
+
"""
|
|
139
|
+
time.sleep(initial_delay)
|
|
140
|
+
current_interval = poll_interval
|
|
141
|
+
while True:
|
|
142
|
+
time.sleep(current_interval)
|
|
143
|
+
try:
|
|
144
|
+
response = self._client.get(f"{self.base_api_url}/jobs/{job_id}/status")
|
|
145
|
+
response.raise_for_status()
|
|
146
|
+
data = response.json()
|
|
147
|
+
status = data.get("status", "")
|
|
148
|
+
if status == "done":
|
|
149
|
+
download = data.get("download", {})
|
|
150
|
+
download_url = download.get("download_url", "")
|
|
151
|
+
if not download_url:
|
|
152
|
+
raise RuntimeError("Failed to receive download URL from server.")
|
|
153
|
+
|
|
154
|
+
if download_dir is None:
|
|
155
|
+
# Return bytes content instead of saving to file
|
|
156
|
+
file_bytes = self.download_bytes(download_url)
|
|
157
|
+
return self.extract_chunks_and_chunksets_from_poma_archive(poma_archive_data=file_bytes)
|
|
158
|
+
else:
|
|
159
|
+
# Save downloaded file to directory
|
|
160
|
+
filename = download.get("filename", "downloaded_file.poma")
|
|
161
|
+
downloaded_file_path = self.download_file(download_url,
|
|
162
|
+
filename,
|
|
163
|
+
save_directory=download_dir)
|
|
164
|
+
return self.extract_chunks_and_chunksets_from_poma_archive(poma_archive_path=downloaded_file_path)
|
|
165
|
+
elif status == "failed":
|
|
166
|
+
error_code = data.get("code", "unknown")
|
|
167
|
+
error_details = data.get("error", "No details provided.")
|
|
168
|
+
error_message = (
|
|
169
|
+
f"Job failed with code {error_code}: {error_details}"
|
|
170
|
+
)
|
|
171
|
+
raise RemoteServerError(
|
|
172
|
+
f"Job failed: {data.get('error', error_message)}"
|
|
173
|
+
)
|
|
174
|
+
elif status == "processing":
|
|
175
|
+
if show_progress:
|
|
176
|
+
print(f"Job {job_id} is still processing...")
|
|
177
|
+
current_interval = min(current_interval * 1.5, max_interval)
|
|
178
|
+
else:
|
|
179
|
+
raise InvalidResponseError(f"Unexpected job status: {status}")
|
|
180
|
+
except httpx.HTTPStatusError as error:
|
|
181
|
+
raise RemoteServerError(
|
|
182
|
+
f"HTTP error: {error.response.status_code} {error.response.text}"
|
|
183
|
+
) from error
|
|
184
|
+
except Exception as error:
|
|
185
|
+
raise RuntimeError(f"POMA-AI job polling failed: {error}") from error
|
|
186
|
+
|
|
187
|
+
def extract_chunks_and_chunksets_from_poma_archive(
|
|
188
|
+
self,
|
|
189
|
+
poma_archive_data: bytes | None = None,
|
|
190
|
+
poma_archive_path: str | os.PathLike[str] | None = None,
|
|
191
|
+
) -> dict[str, Any]:
|
|
192
|
+
"""
|
|
193
|
+
Extract POMA archive file.
|
|
194
|
+
POMA archive file is a zip file containing the chunks.json and chunksets.json files.
|
|
195
|
+
Args:
|
|
196
|
+
poma_archive (bytes): The POMA archive file.
|
|
197
|
+
Returns:
|
|
198
|
+
dict: A dictionary containing the chunks and chunksets.
|
|
199
|
+
"""
|
|
200
|
+
# Sanity check for parameters
|
|
201
|
+
if not poma_archive_data and not poma_archive_path:
|
|
202
|
+
raise ValueError("Either poma_archive_data or poma_archive_path must be provided.")
|
|
203
|
+
|
|
204
|
+
# Load the chunks and chunksets from POMA archive
|
|
205
|
+
chunks = None
|
|
206
|
+
chunksets = None
|
|
207
|
+
if poma_archive_path:
|
|
208
|
+
with zipfile.ZipFile(poma_archive_path, "r") as zip_ref:
|
|
209
|
+
chunks = zip_ref.read('chunks.json')
|
|
210
|
+
chunksets = zip_ref.read('chunksets.json')
|
|
211
|
+
else:
|
|
212
|
+
with zipfile.ZipFile(io.BytesIO(poma_archive_data), "r") as zip_ref:
|
|
213
|
+
chunks = zip_ref.read('chunks.json')
|
|
214
|
+
chunksets = zip_ref.read('chunksets.json')
|
|
215
|
+
|
|
216
|
+
# Sanity check
|
|
217
|
+
if not chunks or not chunksets:
|
|
218
|
+
raise KeyError(
|
|
219
|
+
"Result must contain 'chunks' and 'chunksets' keys."
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
# Load the chunks and chunksets
|
|
223
|
+
json_result = {
|
|
224
|
+
"chunks": json.loads(chunks),
|
|
225
|
+
"chunksets": json.loads(chunksets)
|
|
226
|
+
}
|
|
227
|
+
return json_result
|
|
228
|
+
|
|
229
|
+
def create_cheatsheet(
|
|
230
|
+
self,
|
|
231
|
+
relevant_chunksets: list[dict[str, Any]],
|
|
232
|
+
all_chunks: list[dict[str, Any]],
|
|
233
|
+
) -> str:
|
|
234
|
+
"""
|
|
235
|
+
Generates a single cheatsheet for one single document
|
|
236
|
+
from relevant chunksets (relevant for a certain query)
|
|
237
|
+
and from all available chunks (which must contain the textual content).
|
|
238
|
+
Args:
|
|
239
|
+
relevant_chunksets (list[dict]): A list of chunksets, each containing a "chunks" key with a list of chunk IDs.
|
|
240
|
+
all_chunks (list[dict]): A list of all available chunk dictionaries, each representing a chunk of content.
|
|
241
|
+
Returns:
|
|
242
|
+
str: The textual content of the generated cheatsheet.
|
|
243
|
+
"""
|
|
244
|
+
return generate_single_cheatsheet(relevant_chunksets, all_chunks)
|
|
245
|
+
|
|
246
|
+
def create_cheatsheets(
|
|
247
|
+
self,
|
|
248
|
+
relevant_chunksets: list[dict[str, Any]],
|
|
249
|
+
all_chunks: list[dict[str, Any]],
|
|
250
|
+
) -> list[dict[str, Any]]:
|
|
251
|
+
"""
|
|
252
|
+
Generates cheatsheets from relevant chunksets (relevant for a certain query)
|
|
253
|
+
and from all available chunks (which must contain the textual content).
|
|
254
|
+
One cheatsheet is created for each document tag found in the chunks.
|
|
255
|
+
Args:
|
|
256
|
+
relevant_chunksets (list[dict]): A list of chunksets, each containing a "chunks" key with a list of chunk IDs.
|
|
257
|
+
all_chunks (list[dict]): A list of all available chunk dictionaries, each representing a chunk of content.
|
|
258
|
+
Returns:
|
|
259
|
+
list[dict]: A list of dictionaries representing the generated cheatsheets, each containing:
|
|
260
|
+
- 'tag': The tag associated with the respective document.
|
|
261
|
+
- 'content': The textual content of the generated cheatsheet.
|
|
262
|
+
"""
|
|
263
|
+
return generate_cheatsheets(relevant_chunksets, all_chunks)
|
|
264
|
+
|
|
265
|
+
def download_file(
|
|
266
|
+
self,
|
|
267
|
+
download_url: str,
|
|
268
|
+
filename: str | None = None,
|
|
269
|
+
*,
|
|
270
|
+
save_directory: str | os.PathLike[str] | None = None,
|
|
271
|
+
) -> str:
|
|
272
|
+
"""
|
|
273
|
+
Download a file from the given download URL.
|
|
274
|
+
Args:
|
|
275
|
+
download_url (str):
|
|
276
|
+
The URL to download the file from.
|
|
277
|
+
filename (str, optional):
|
|
278
|
+
The filename to save the file as. If not provided, will be extracted from URL.
|
|
279
|
+
save_directory (str | os.PathLike[str], optional):
|
|
280
|
+
Directory to save the file in. If not provided, saves to current directory.
|
|
281
|
+
Returns:
|
|
282
|
+
str: The path to the downloaded file.
|
|
283
|
+
"""
|
|
284
|
+
if not download_url:
|
|
285
|
+
raise ValueError("download_url cannot be empty")
|
|
286
|
+
|
|
287
|
+
# Determine filename
|
|
288
|
+
if not filename:
|
|
289
|
+
filename = Path(download_url).name or "downloaded_file"
|
|
290
|
+
|
|
291
|
+
# Determine save directory
|
|
292
|
+
if save_directory:
|
|
293
|
+
save_path = Path(save_directory) / filename
|
|
294
|
+
else:
|
|
295
|
+
save_path = Path(filename)
|
|
296
|
+
|
|
297
|
+
# Create the directory if it doesn't exist
|
|
298
|
+
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
|
299
|
+
|
|
300
|
+
# Download the file data
|
|
301
|
+
content = self.download_bytes(download_url)
|
|
302
|
+
|
|
303
|
+
# Save the file
|
|
304
|
+
with open(save_path, "wb") as f:
|
|
305
|
+
f.write(content)
|
|
306
|
+
return save_path
|
|
307
|
+
|
|
308
|
+
def download_bytes(
|
|
309
|
+
self,
|
|
310
|
+
download_url: str,
|
|
311
|
+
) -> bytes:
|
|
312
|
+
"""
|
|
313
|
+
Download a file from the given download URL and return the bytes content.
|
|
314
|
+
Args:
|
|
315
|
+
download_url (str):
|
|
316
|
+
The URL to download the file from.
|
|
317
|
+
Returns:
|
|
318
|
+
bytes: The content of the downloaded file as bytes.
|
|
319
|
+
"""
|
|
320
|
+
if not download_url:
|
|
321
|
+
raise ValueError("download_url cannot be empty")
|
|
322
|
+
|
|
323
|
+
# Construct the full URL if it's a relative path
|
|
324
|
+
if download_url.startswith("/"):
|
|
325
|
+
full_url = f"{self.base_api_url}{download_url}"
|
|
326
|
+
else:
|
|
327
|
+
full_url = download_url
|
|
328
|
+
|
|
329
|
+
print("Downloading file from:", full_url)
|
|
330
|
+
try:
|
|
331
|
+
# Download the file
|
|
332
|
+
response = self._client.get(full_url)
|
|
333
|
+
response.raise_for_status()
|
|
334
|
+
|
|
335
|
+
# Return the bytes content
|
|
336
|
+
return response.content
|
|
337
|
+
|
|
338
|
+
except httpx.HTTPStatusError as error:
|
|
339
|
+
status = error.response.status_code
|
|
340
|
+
if status in (401, 403):
|
|
341
|
+
raise AuthenticationError(f"Authentication failed when downloading file: {response.text}") from error
|
|
342
|
+
raise RemoteServerError(f"Failed to download file: {status} {response.text}") from error
|
|
343
|
+
except Exception as error:
|
|
344
|
+
raise RuntimeError(f"File download failed: {error}") from error
|
|
345
|
+
|
|
346
|
+
def close(self):
|
|
347
|
+
self._client.close()
|
|
348
|
+
|
|
349
|
+
def __enter__(self) -> "Poma":
|
|
350
|
+
return self
|
|
351
|
+
|
|
352
|
+
def __exit__(self, *exc):
|
|
353
|
+
self.close()
|