hamtaa-texttools 1.0.1__py3-none-any.whl → 1.1.7__py3-none-any.whl

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.

Potentially problematic release.


This version of hamtaa-texttools might be problematic. Click here for more details.

Files changed (41) hide show
  1. hamtaa_texttools-1.1.7.dist-info/METADATA +228 -0
  2. hamtaa_texttools-1.1.7.dist-info/RECORD +30 -0
  3. {hamtaa_texttools-1.0.1.dist-info → hamtaa_texttools-1.1.7.dist-info}/licenses/LICENSE +20 -20
  4. {hamtaa_texttools-1.0.1.dist-info → hamtaa_texttools-1.1.7.dist-info}/top_level.txt +0 -0
  5. texttools/__init__.py +4 -9
  6. texttools/batch/__init__.py +3 -0
  7. texttools/{utils/batch_manager → batch}/batch_manager.py +226 -240
  8. texttools/batch/batch_runner.py +254 -0
  9. texttools/prompts/README.md +35 -0
  10. texttools/prompts/categorizer.yaml +28 -0
  11. texttools/prompts/extract_entities.yaml +20 -0
  12. texttools/prompts/extract_keywords.yaml +18 -0
  13. texttools/prompts/is_question.yaml +14 -0
  14. texttools/prompts/merge_questions.yaml +46 -0
  15. texttools/prompts/rewrite.yaml +111 -0
  16. texttools/prompts/run_custom.yaml +7 -0
  17. texttools/prompts/subject_to_question.yaml +22 -0
  18. texttools/prompts/summarize.yaml +14 -0
  19. texttools/prompts/text_to_question.yaml +20 -0
  20. texttools/prompts/translate.yaml +15 -0
  21. texttools/tools/__init__.py +4 -3
  22. texttools/tools/async_the_tool.py +435 -0
  23. texttools/tools/internals/async_operator.py +242 -0
  24. texttools/tools/internals/base_operator.py +100 -0
  25. texttools/tools/internals/formatters.py +24 -0
  26. texttools/tools/internals/operator.py +242 -0
  27. texttools/tools/internals/output_models.py +62 -0
  28. texttools/tools/internals/prompt_loader.py +60 -0
  29. texttools/tools/the_tool.py +433 -291
  30. hamtaa_texttools-1.0.1.dist-info/METADATA +0 -129
  31. hamtaa_texttools-1.0.1.dist-info/RECORD +0 -18
  32. texttools/formatters/base_formatter.py +0 -33
  33. texttools/formatters/user_merge_formatter/user_merge_formatter.py +0 -47
  34. texttools/prompts/__init__.py +0 -0
  35. texttools/tools/operator.py +0 -236
  36. texttools/tools/output_models.py +0 -54
  37. texttools/tools/prompt_loader.py +0 -84
  38. texttools/utils/__init__.py +0 -4
  39. texttools/utils/batch_manager/__init__.py +0 -4
  40. texttools/utils/batch_manager/batch_runner.py +0 -212
  41. {hamtaa_texttools-1.0.1.dist-info → hamtaa_texttools-1.1.7.dist-info}/WHEEL +0 -0
@@ -1,212 +0,0 @@
1
- import json
2
- import os
3
- import time
4
- from dataclasses import dataclass
5
- from pathlib import Path
6
- from typing import Any, Callable
7
-
8
- from openai import OpenAI
9
- from pydantic import BaseModel
10
-
11
- from texttools.utils.batch_manager import SimpleBatchManager
12
-
13
-
14
- class Output(BaseModel):
15
- output: str
16
-
17
-
18
- def export_data(data):
19
- """
20
- Produces a structure of the following form from an initial data structure:
21
- [
22
- {"id": str, "content": str},...
23
- ]
24
- """
25
- return data
26
-
27
-
28
- def import_data(data):
29
- """
30
- Takes the output and adds and aggregates it to the original structure.
31
- """
32
- return data
33
-
34
-
35
- @dataclass
36
- class BatchConfig:
37
- """
38
- Configuration for batch job runner.
39
- """
40
-
41
- system_prompt: str = ""
42
- job_name: str = ""
43
- input_data_path: str = ""
44
- output_data_filename: str = ""
45
- model: str = "gpt-4.1-mini"
46
- MAX_BATCH_SIZE: int = 100
47
- MAX_TOTAL_TOKENS: int = 2000000
48
- CHARS_PER_TOKEN: float = 2.7
49
- PROMPT_TOKEN_MULTIPLIER: int = 1000
50
- BASE_OUTPUT_DIR: str = "Data/batch_entity_result"
51
- import_function: Callable = import_data
52
- export_function: Callable = export_data
53
-
54
-
55
- class BatchJobRunner:
56
- """
57
- Orchestrates the execution of batched LLM processing jobs.
58
-
59
- Handles data loading, partitioning, job execution via SimpleBatchManager,
60
- and result saving. Manages the complete workflow from input data to processed outputs,
61
- including retries and progress tracking across multiple batch parts.
62
- """
63
-
64
- def __init__(
65
- self, config: BatchConfig = BatchConfig(), output_model: type = Output
66
- ):
67
- self.config = config
68
- self.system_prompt = config.system_prompt
69
- self.job_name = config.job_name
70
- self.input_data_path = config.input_data_path
71
- self.output_data_filename = config.output_data_filename
72
- self.model = config.model
73
- self.output_model = output_model
74
- self.manager = self._init_manager()
75
- self.data = self._load_data()
76
- self.parts: list[list[dict[str, Any]]] = []
77
- self._partition_data()
78
- Path(self.config.BASE_OUTPUT_DIR).mkdir(parents=True, exist_ok=True)
79
-
80
- def _init_manager(self) -> SimpleBatchManager:
81
- api_key = os.getenv("OPENAI_API_KEY")
82
- client = OpenAI(api_key=api_key)
83
- return SimpleBatchManager(
84
- client=client,
85
- model=self.model,
86
- prompt_template=self.system_prompt,
87
- output_model=self.output_model,
88
- )
89
-
90
- def _load_data(self):
91
- with open(self.input_data_path, "r", encoding="utf-8") as f:
92
- data = json.load(f)
93
- data = self.config.export_function(data)
94
-
95
- # Ensure data is a list of dicts with 'id' and 'content' as strings
96
- if not isinstance(data, list):
97
- raise ValueError(
98
- 'Exported data must be a list in this form: [ {"id": str, "content": str},...]'
99
- )
100
- for item in data:
101
- if not (isinstance(item, dict) and "id" in item and "content" in item):
102
- raise ValueError(
103
- "Each item must be a dict with 'id' and 'content' keys."
104
- )
105
- if not (isinstance(item["id"], str) and isinstance(item["content"], str)):
106
- raise ValueError("'id' and 'content' must be strings.")
107
- return data
108
-
109
- def _partition_data(self):
110
- total_length = sum(len(item["content"]) for item in self.data)
111
- prompt_length = len(self.system_prompt)
112
- total = total_length + (prompt_length * len(self.data))
113
- calculation = total / self.config.CHARS_PER_TOKEN
114
- print(
115
- f"Total chars: {total_length}, Prompt chars: {prompt_length}, Total: {total}, Tokens: {calculation}"
116
- )
117
- if calculation < self.config.MAX_TOTAL_TOKENS:
118
- self.parts = [self.data]
119
- else:
120
- # Partition into chunks of MAX_BATCH_SIZE
121
- self.parts = [
122
- self.data[i : i + self.config.MAX_BATCH_SIZE]
123
- for i in range(0, len(self.data), self.config.MAX_BATCH_SIZE)
124
- ]
125
- print(f"Data split into {len(self.parts)} part(s)")
126
-
127
- def run(self):
128
- for idx, part in enumerate(self.parts):
129
- if self._result_exists(idx):
130
- print(f"Skipping part {idx + 1}: result already exists.")
131
- continue
132
- part_job_name = (
133
- f"{self.job_name}_part_{idx + 1}"
134
- if len(self.parts) > 1
135
- else self.job_name
136
- )
137
- print(
138
- f"\n--- Processing part {idx + 1}/{len(self.parts)}: {part_job_name} ---"
139
- )
140
- self._process_part(part, part_job_name, idx)
141
-
142
- def _process_part(
143
- self, part: list[dict[str, Any]], part_job_name: str, part_idx: int
144
- ):
145
- while True:
146
- print(f"Starting job for part: {part_job_name}")
147
- self.manager.start(part, job_name=part_job_name)
148
- print("Started batch job. Checking status...")
149
- while True:
150
- status = self.manager.check_status(job_name=part_job_name)
151
- print(f"Status: {status}")
152
- if status == "completed":
153
- print("Job completed. Fetching results...")
154
- output_data, log = self.manager.fetch_results(
155
- job_name=part_job_name, remove_cache=False
156
- )
157
- output_data = self.config.import_function(output_data)
158
- self._save_results(output_data, log, part_idx)
159
- print("Fetched and saved results for this part.")
160
- return
161
- elif status == "failed":
162
- print("Job failed. Clearing state, waiting, and retrying...")
163
- self.manager._clear_state(part_job_name)
164
- # Wait before retrying
165
- time.sleep(10)
166
- # Break inner loop to restart the job
167
- break
168
- else:
169
- # Wait before checking again
170
- time.sleep(5)
171
-
172
- def _save_results(
173
- self, output_data: list[dict[str, Any]], log: list[Any], part_idx: int
174
- ):
175
- part_suffix = f"_part_{part_idx + 1}" if len(self.parts) > 1 else ""
176
- result_path = (
177
- Path(self.config.BASE_OUTPUT_DIR)
178
- / f"{Path(self.output_data_filename).stem}{part_suffix}.json"
179
- )
180
- if not output_data:
181
- print("No output data to save. Skipping this part.")
182
- return
183
- else:
184
- with open(result_path, "w", encoding="utf-8") as f:
185
- json.dump(output_data, f, ensure_ascii=False, indent=4)
186
- if log:
187
- log_path = (
188
- Path(self.config.BASE_OUTPUT_DIR)
189
- / f"{Path(self.output_data_filename).stem}{part_suffix}_log.json"
190
- )
191
- with open(log_path, "w", encoding="utf-8") as f:
192
- json.dump(log, f, ensure_ascii=False, indent=4)
193
-
194
- def _result_exists(self, part_idx: int) -> bool:
195
- part_suffix = f"_part_{part_idx + 1}" if len(self.parts) > 1 else ""
196
- result_path = (
197
- Path(self.config.BASE_OUTPUT_DIR)
198
- / f"{Path(self.output_data_path).stem}{part_suffix}.json"
199
- )
200
- return result_path.exists()
201
-
202
-
203
- if __name__ == "__main__":
204
- print("=== Batch Job Runner ===")
205
- config = BatchConfig(
206
- system_prompt="",
207
- job_name="job_name",
208
- input_data_path="Data.json",
209
- output_data_filename="output",
210
- )
211
- runner = BatchJobRunner(config)
212
- runner.run()