buzzCraft commited on
Commit
182f05f
1 Parent(s): 291bc70

Delete extractor.py

Browse files
Files changed (1) hide show
  1. extractor.py +0 -560
extractor.py DELETED
@@ -1,560 +0,0 @@
1
- from typing import Optional
2
-
3
- from langchain.chains import create_extraction_chain_pydantic
4
- from langchain_core.prompts import ChatPromptTemplate
5
- from langchain.chains import create_extraction_chain
6
- from copy import deepcopy
7
- from langchain_openai import ChatOpenAI
8
- from langchain_community.utilities import SQLDatabase
9
- import os
10
- import difflib
11
- import ast
12
- import json
13
- import re
14
- from thefuzz import process
15
- # Set up logging
16
- import logging
17
-
18
- from dotenv import load_dotenv
19
-
20
- load_dotenv(".env")
21
-
22
- logging.basicConfig(level=logging.INFO)
23
- # Save the log to a file
24
- handler = logging.FileHandler('extractor.log')
25
- logger = logging.getLogger(__name__)
26
-
27
- os.environ["OPENAI_API_KEY"] = os.getenv('OPENAI_API_KEY')
28
- # os.environ["ANTHROPIC_API_KEY"] = os.getenv('ANTHROPIC_API_KEY')
29
-
30
- if os.getenv('LANGSMITH'):
31
- os.environ['LANGCHAIN_TRACING_V2'] = 'true'
32
- os.environ['LANGCHAIN_ENDPOINT'] = 'https://api.smith.langchain.com'
33
- os.environ[
34
- 'LANGCHAIN_API_KEY'] = os.getenv("LANGSMITH_API_KEY")
35
- os.environ['LANGCHAIN_PROJECT'] = os.getenv('LANGSMITH_PROJECT')
36
- db_uri = os.getenv('DATABASE_PATH')
37
- db_uri = f"sqlite:///{db_uri}"
38
- db = SQLDatabase.from_uri(db_uri)
39
-
40
- # from langchain_anthropic import ChatAnthropic
41
- class Extractor():
42
- # llm = ChatOpenAI(model_name="gpt-4-0125-preview", temperature=0)
43
- #gpt-3.5-turbo
44
- def __init__(self, model="gpt-3.5-turbo-0125", schema_config=None, custom_extractor_prompt=None):
45
- # model = "gpt-4-0125-preview"
46
- if custom_extractor_prompt:
47
- cust_promt = ChatPromptTemplate.from_template(custom_extractor_prompt)
48
-
49
- self.llm = ChatOpenAI(model=model, temperature=0)
50
- # self.llm = ChatAnthropic(model="claude-3-opus-20240229", temperature=0)
51
- self.schema = schema_config or {}
52
- self.chain = create_extraction_chain(self.schema, self.llm, prompt=cust_promt)
53
-
54
- def extract(self, query):
55
- return self.chain.invoke(query)
56
-
57
-
58
- class Retriever():
59
- def __init__(self, db, config):
60
- self.db = db
61
- self.config = config
62
- self.table = config.get('db_table')
63
- self.column = config.get('db_column')
64
- self.pk_column = config.get('pk_column')
65
- self.numeric = config.get('numeric', False)
66
- self.response = []
67
- self.query = f"SELECT {self.column} FROM {self.table}"
68
- self.augmented_table = config.get('augmented_table', None)
69
- self.augmented_column = config.get('augmented_column', None)
70
- self.augmented_fk = config.get('augmented_fk', None)
71
-
72
- def query_as_list(self):
73
- # Execute the query
74
- response = self.db.run(self.query)
75
- response = [el for sub in ast.literal_eval(response) for el in sub if el]
76
- if not self.numeric:
77
- response = [re.sub(r"\b\d+\b", "", string).strip() for string in response]
78
- self.response = list(set(response))
79
- # print(self.response)
80
- return self.response
81
-
82
- def get_augmented_items(self, prompt):
83
- if self.augmented_table is None:
84
- return None
85
- else:
86
- # Construct the query to search for the prompt in the augmented table
87
- query = f"SELECT {self.augmented_fk} FROM {self.augmented_table} WHERE LOWER({self.augmented_column}) = LOWER('{prompt}')"
88
-
89
- # Execute the query
90
- fk_response = self.db.run(query)
91
- if fk_response:
92
- # Extract the FK value
93
- fk_response = ast.literal_eval(fk_response)
94
- fk_value = fk_response[0][0]
95
- query = f"SELECT {self.column} FROM {self.table} WHERE {self.pk_column} = {fk_value}"
96
- # Execute the query
97
- matching_response = self.db.run(query)
98
- # Extract the matching response
99
- matching_response = ast.literal_eval(matching_response)
100
- matching_response = matching_response[0][0]
101
- return matching_response
102
- else:
103
- return None
104
-
105
- def find_close_matches(self, target_string, n=3, method="difflib", threshold=70):
106
- """
107
- Find and return the top n close matches to target_string in the database query results.
108
-
109
- Args:
110
- - target_string (str): The string to match against the database results.
111
- - n (int): Number of top matches to return.
112
-
113
- Returns:
114
- - list of tuples: Each tuple contains a match and its score.
115
- """
116
- # Ensure we have the response list populated
117
- if not self.response:
118
- self.query_as_list()
119
-
120
- # Find top n close matches
121
- if method == "fuzzy":
122
- # Use the fuzzy_string method to get matches and their scores
123
- # If the threshold is met, return the best match; otherwise, return all matches meeting the threshold
124
- top_matches = self.fuzzy_string(target_string, limit=n, threshold=threshold)
125
-
126
-
127
- else:
128
- # Use difflib's get_close_matches to get the top n matches
129
- top_matches = difflib.get_close_matches(target_string, self.response, n=n, cutoff=0.2)
130
-
131
- return top_matches
132
-
133
- def fuzzy_string(self, prompt, limit, threshold=80, low_threshold=30):
134
-
135
- # Get matches and their scores, limited by the specified 'limit'
136
- matches = process.extract(prompt, self.response, limit=limit)
137
-
138
-
139
- filtered_matches = [match for match in matches if match[1] >= threshold]
140
-
141
- # If no matches meet the threshold, return the list of all matches' strings
142
- if not filtered_matches:
143
- # Return matches above the low_threshold
144
- # Fix for wrong properties being returned
145
- return [match[0] for match in matches if match[1] >= low_threshold]
146
-
147
-
148
- # If there's only one match meeting the threshold, return it as a string
149
- if len(filtered_matches) == 1:
150
- return filtered_matches[0][0] # Return the matched string directly
151
-
152
- # If there's more than one match meeting the threshold or ties, return the list of matches' strings
153
- highest_score = filtered_matches[0][1]
154
- ties = [match for match in filtered_matches if match[1] == highest_score]
155
-
156
- # Return the strings of tied matches directly, ignoring the scores
157
- m = [match[0] for match in ties]
158
- if len(m) == 1:
159
- return m[0]
160
- return [match[0] for match in ties]
161
-
162
- def fetch_pk(self, property_name, property_value):
163
- # Some properties do not have a primary key
164
- # Return the property value if no primary key is specified
165
- pk_list = []
166
-
167
- # Check if the property_value is a list; if not, make it a list for uniform processing
168
- if not isinstance(property_value, list):
169
- property_value = [property_value]
170
-
171
- # Some properties do not have a primary key
172
- # Return None for each property_value if no primary key is specified
173
- if self.pk_column is None:
174
- return [None for _ in property_value]
175
-
176
- for value in property_value:
177
- query = f"SELECT {self.pk_column} FROM {self.table} WHERE {self.column} = '{value}' LIMIT 1"
178
- response = self.db.run(query)
179
-
180
- # Append the response (PK or None) to the pk_list
181
- pk_list.append(response)
182
-
183
- return pk_list
184
-
185
-
186
- def setup_retrievers(db, schema_config):
187
- # retrievers = {}
188
- # for prop, config in schema_config["properties"].items():
189
- # retrievers[prop] = Retriever(db=db, config=config)
190
- # return retrievers
191
-
192
- retrievers = {}
193
- # Iterate over each property in the schema_config's properties
194
- for prop, config in schema_config["properties"].items():
195
- # Access the 'items' dictionary for the configuration of the array's elements
196
- item_config = config['items']
197
- # Create a Retriever instance using the item_config
198
- retrievers[prop] = Retriever(db=db, config=item_config)
199
- return retrievers
200
-
201
-
202
- def extract_properties(prompt, schema_config, custom_extractor_prompt=None):
203
- """Extract properties from the prompt."""
204
- # modify schema_conf to only include the required properties
205
- schema_stripped = {'properties': {}}
206
- for key, value in schema_config['properties'].items():
207
- schema_stripped['properties'][key] = {
208
- 'type': value['type'],
209
- 'items': {'type': value['items']['type']}
210
- }
211
-
212
- extractor = Extractor(schema_config=schema_stripped, custom_extractor_prompt=custom_extractor_prompt)
213
- extraction_result = extractor.extract(prompt)
214
- # print("Extraction Result:", extraction_result)
215
-
216
- if 'text' in extraction_result and extraction_result['text']:
217
- properties = extraction_result['text']
218
- return properties
219
- else:
220
- print("No properties extracted.")
221
- return None
222
-
223
-
224
- def recheck_property_value(properties, property_name, retrievers, input_func):
225
- while True:
226
- new_value = input_func(f"Enter new value for {property_name} or type 'quit' to stop: ")
227
- if new_value.lower() == 'quit':
228
- break # Exit the loop and do not update the property
229
-
230
- new_top_matches = retrievers[property_name].find_close_matches(new_value, n=3)
231
- if new_top_matches:
232
- # Display new top matches and ask for confirmation or re-entry
233
- print("\nNew close matches found:")
234
- for i, match in enumerate(new_top_matches, start=1):
235
- print(f"[{i}] {match}")
236
- print("[4] Re-enter value")
237
- print("[5] Quit without updating")
238
-
239
- selection = input_func("Select the best match (1-3), choose 4 to re-enter value, or 5 to quit: ")
240
- if selection in ['1', '2', '3']:
241
- selected_match = new_top_matches[int(selection) - 1]
242
- properties[property_name] = selected_match # Update the dictionary directly
243
- print(f"Updated {property_name} to {selected_match}")
244
- break # Successfully updated, exit the loop
245
- elif selection == '5':
246
- break # Quit without updating
247
- # Loop will continue if user selects 4 or inputs invalid selection
248
- else:
249
- print("No close matches found. Please try again or type 'quit' to stop.")
250
-
251
-
252
- def check_and_update_properties(properties_list, retrievers, method="fuzzy", input_func=input):
253
- """
254
- Checks and updates the properties in the properties list based on close matches found in the database.
255
- The function iterates through each property in each property dictionary within the list,
256
- finds close matches for it in the database using the retrievers, and updates the property
257
- value based on user selection.
258
-
259
- Args:
260
- properties_list (list of dict): A list of dictionaries, where each dictionary contains properties
261
- to check and potentially update based on database matches.
262
- retrievers (dict): A dictionary of Retriever objects keyed by property name, used to find close matches in the database.
263
- input_func (function, optional): A function to capture user input. Defaults to the built-in input function.
264
-
265
- The function updates the properties_list in place based on user choices for updating property values
266
- with close matches found by the retrievers.
267
- """
268
-
269
- for index, properties in enumerate(properties_list):
270
- for property_name, retriever in retrievers.items(): # Iterate using items to get both key and value
271
- property_values = properties.get(property_name, [])
272
- if not property_values: # Skip if the property is not present or is an empty list
273
- continue
274
-
275
- updated_property_values = [] # To store updated list of values
276
-
277
- for value in property_values:
278
- if retriever.augmented_table:
279
- augmented_value = retriever.get_augmented_items(value)
280
- if augmented_value:
281
- updated_property_values.append(augmented_value)
282
- continue
283
- # Since property_value is now expected to be a list, we handle each value individually
284
- top_matches = retriever.find_close_matches(value, method=method, n=3)
285
-
286
- # Check if the closest match is the same as the current value
287
- if top_matches and top_matches[0] == value:
288
- updated_property_values.append(value)
289
- continue
290
-
291
- if not top_matches:
292
- updated_property_values.append(value) # Keep the original value if no matches found
293
- continue
294
-
295
- if type(top_matches) == str and method == "fuzzy":
296
- # If the top_matches is a string, it means that the threshold was met and only one item was returned
297
- # In this case, we can directly update the property with the top match
298
- updated_property_values.append(top_matches)
299
- properties[property_name] = updated_property_values
300
- continue
301
-
302
- print(f"\nCurrent {property_name}: {value}")
303
- for i, match in enumerate(top_matches, start=1):
304
- print(f"[{i}] {match}")
305
- print("[4] Enter new value")
306
-
307
- # hmm = input_func(f"Fix for Pycharm, press enter to continue")
308
-
309
- choice = input_func(f"Select the best match for {property_name} (1-4): ")
310
- if choice in ['1', '2', '3']:
311
- selected_match = top_matches[int(choice) - 1]
312
- updated_property_values.append(selected_match) # Update with the selected match
313
- print(f"Updated {property_name} to {selected_match}")
314
- elif choice == '4':
315
- # Allow re-entry of value for this specific item
316
- recheck_property_value(properties, property_name, value, retrievers, input_func)
317
- # Note: Implement recheck_property_value to handle individual value updates within the list
318
- else:
319
- print("Invalid selection. Property not updated.")
320
- updated_property_values.append(value) # Keep the original value
321
-
322
- # Update the entire list for the property after processing all values
323
- properties[property_name] = updated_property_values
324
-
325
-
326
- # Function to remove duplicates
327
- def remove_duplicates(dicts):
328
- seen = {} # Dictionary to keep track of seen values for each key
329
- for d in dicts:
330
- for key in list(d.keys()): # Use list to avoid RuntimeError for changing dict size during iteration
331
- value = d[key]
332
- if key in seen and value == seen[key]:
333
- del d[key] # Remove key-value pair if duplicate is found
334
- else:
335
- seen[key] = value # Update seen values for this key
336
- return dicts
337
-
338
-
339
- def fetch_pks(properties_list, retrievers):
340
- all_pk_attributes = [] # Initialize a list to store dictionaries of _pk attributes for each item in properties_list
341
-
342
- # Iterate through each properties dictionary in the list
343
- for properties in properties_list:
344
- pk_attributes = {} # Initialize a dictionary for the current set of properties
345
- for property_name, property_value in properties.items():
346
- if property_name in retrievers:
347
- # Fetch the primary key using the retriever for the current property
348
- pk = retrievers[property_name].fetch_pk(property_name, property_value)
349
- # Store it in the dictionary with a modified key name
350
- pk_attributes[f"{property_name}_pk"] = pk
351
-
352
- # Add the dictionary of _pk attributes for the current set of properties to the list
353
- all_pk_attributes.append(pk_attributes)
354
-
355
- # Return a list of dictionaries, where each dictionary contains _pk attributes for a set of properties
356
- return all_pk_attributes
357
-
358
-
359
- def update_prompt(prompt, properties, pk, properties_original):
360
- # Replace the original prompt with the updated properties and pk
361
- prompt = prompt.replace("{{properties}}", str(properties))
362
- prompt = prompt.replace("{{pk}}", str(pk))
363
- return prompt
364
-
365
-
366
- def update_prompt_enhanced(prompt, properties, pk, properties_original):
367
- updated_info = ""
368
- for prop, pk_info, prop_orig in zip(properties, pk, properties_original):
369
- for key in prop.keys():
370
- # Extract original and updated values
371
- orig_values = prop_orig.get(key, [])
372
- updated_values = prop.get(key, [])
373
-
374
- # Ensure both original and updated values are lists for uniform processing
375
- if not isinstance(orig_values, list):
376
- orig_values = [orig_values]
377
- if not isinstance(updated_values, list):
378
- updated_values = [updated_values]
379
-
380
- # Extract primary key detail for this key, handling various pk formats carefully
381
- pk_key = f"{key}_pk" # Construct pk key name based on the property key
382
- pk_details = pk_info.get(pk_key, [])
383
- if not isinstance(pk_details, list):
384
- pk_details = [pk_details]
385
-
386
- for orig_value, updated_value, pk_detail in zip(orig_values, updated_values, pk_details):
387
- pk_value = None
388
- if isinstance(pk_detail, str):
389
- pk_value = pk_detail.strip("[]()").split(",")[0].replace("'", "").replace('"', '')
390
-
391
- update_statement = ""
392
- # Skip updating if there's no change in value to avoid redundant info
393
- if orig_value != updated_value and pk_value:
394
- update_statement = f"\n- {orig_value} (now referred to as {updated_value}) has a primary key: {pk_value}."
395
- elif orig_value != updated_value:
396
- update_statement = f"\n- {orig_value} (now referred to as {updated_value})."
397
- elif pk_value:
398
- update_statement = f"\n- {orig_value} has a primary key: {pk_value}."
399
-
400
- updated_info += update_statement
401
-
402
- if updated_info:
403
- prompt += "\nUpdated Information:" + updated_info
404
-
405
- return prompt
406
-
407
-
408
- def prompt_cleaner(prompt, db, schema_config):
409
- """Main function to clean the prompt."""
410
-
411
- retrievers = setup_retrievers(db, schema_config)
412
-
413
- properties = extract_properties(prompt, schema_config)
414
- # Keep original properties for later use
415
- properties_original = deepcopy(properties)
416
- # Remove duplicates - Happens when there are more than one player or team in the prompt
417
- properties = remove_duplicates(properties)
418
- if properties:
419
- check_and_update_properties(properties, retrievers)
420
-
421
- pk = fetch_pks(properties, retrievers)
422
- properties = update_prompt_enhanced(prompt, properties, pk, properties_original)
423
-
424
- return properties, pk
425
-
426
-
427
- class PromptCleaner:
428
- """
429
- A class designed to clean and process prompts by extracting properties, removing duplicates,
430
- and updating these properties based on a predefined schema configuration and database interactions.
431
-
432
- Attributes:
433
- db: A database connection object used to execute queries and fetch data.
434
- schema_config: A dictionary defining the schema configuration for the extraction process.
435
- schema_config = {
436
- "properties": {
437
- # Property name
438
- "person_name": {"type": "string", "db_table": "players", "db_column": "name", "pk_column": "hash",
439
- # if mostly numeric, such as 2015-2016 set true
440
- "numeric": False},
441
- "team_name": {"type": "string", "db_table": "teams", "db_column": "name", "pk_column": "id",
442
- "numeric": False},
443
- # Add more as needed
444
- },
445
- # Parameter to extractor, if person_name is required, add it here and the extractor will
446
- # return an error if it is not found
447
- "required": [],
448
- }
449
-
450
- Methods:
451
- clean(prompt): Cleans the given prompt by extracting and updating properties based on the database.
452
- Returns a tuple containing the updated properties and their primary keys.
453
- """
454
-
455
- def __init__(self, db=db, schema_config=None, custom_extractor_prompt=None):
456
- """
457
- Initializes the PromptCleaner with a database connection and a schema configuration.
458
-
459
- Args:
460
- db: The database connection object to be used for querying. (if none, it will use the default db)
461
- schema_config: A dictionary defining properties and their database mappings for extraction and updating.
462
- """
463
- self.db = db
464
- self.schema_config = schema_config
465
- self.retrievers = setup_retrievers(self.db, self.schema_config)
466
- self.cust_extractor_prompt = custom_extractor_prompt
467
-
468
- def clean(self, prompt, return_pk=False, test=False, verbose = False):
469
- """
470
- Processes the given prompt to extract properties, remove duplicates, update the properties
471
- based on close matches within the database, and fetch primary keys for these properties.
472
-
473
- The method first extracts properties from the prompt using the schema configuration,
474
- then checks these properties against the database to find and update close matches.
475
- It also fetches primary keys for the updated properties where applicable.
476
-
477
- Args:
478
- prompt (str): The prompt text to be cleaned and processed.
479
- return_pk (bool): A flag to indicate whether to return primary keys along with the properties.
480
- test (bool): A flag to indicate whether to return the original properties for testing purposes.
481
- verbose (bool): A flag to indicate whether to return the original properties for debugging.
482
-
483
- Returns:
484
- tuple: A tuple containing two elements:
485
- - The first element is the original prompt, with updated information that excist in the db.
486
- - The second element is a list of dictionaries, each containing primary keys for the properties,
487
- where applicable.
488
-
489
- """
490
- if self.cust_extractor_prompt:
491
-
492
- properties = extract_properties(prompt, self.schema_config, self.cust_extractor_prompt)
493
-
494
- else:
495
- properties = extract_properties(prompt, self.schema_config)
496
- # Keep original properties for later use
497
- properties_original = deepcopy(properties)
498
- if test:
499
- return properties_original
500
- # Remove duplicates - Happens when there are more than one player or team in the prompt
501
- # properties = remove_duplicates(properties)
502
- pk = None
503
- if properties:
504
- check_and_update_properties(properties, self.retrievers)
505
- pk = fetch_pks(properties, self.retrievers)
506
- properties = update_prompt_enhanced(prompt, properties, pk, properties_original)
507
-
508
-
509
-
510
- if return_pk:
511
- return properties, pk
512
- elif verbose:
513
- return properties, properties_original
514
- else:
515
- return properties
516
-
517
-
518
- def load_json(file_path: str) -> dict:
519
- with open(file_path, 'r') as file:
520
- return json.load(file)
521
-
522
-
523
- def create_extractor(schema: str = "src/conf/schema.json", db: SQLDatabase = db_uri):
524
- schema_config = load_json(schema)
525
- db = SQLDatabase.from_uri(db)
526
- pre_prompt = """Extract and save the relevant entities mentioned \
527
- in the following passage together with their properties.
528
-
529
- Only extract the properties mentioned in the 'information_extraction' function.
530
-
531
- The questions are soccer related. game_event are things like yellow cards, goals, assists, freekick ect.
532
- Generic properties like, "description", "home team", "away team", "game" ect should NOT be extracted.
533
-
534
- If a property is not present and is not required in the function parameters, do not include it in the output.
535
- If no properties are found, return an empty list.
536
-
537
- Here are some exampels:
538
- 'How many goals did Henry score for Arsnl in the 2015 season?'
539
- person_name': ['Henry'], 'team_name': [Arsnl],'year_season': ['2015'],
540
-
541
- Passage:
542
- {input}
543
- """
544
-
545
- return PromptCleaner(db, schema_config, custom_extractor_prompt=pre_prompt)
546
-
547
-
548
- if __name__ == "__main__":
549
-
550
-
551
- schema_config = load_json("src/conf/schema.json")
552
- # Add game and league to the schema_config
553
-
554
- # prompter = PromptCleaner(db, schema_config, custom_extractor_prompt=extract_prompt)
555
- prompter = create_extractor("src/conf/schema.json", "sqlite:///data/games.db")
556
- prompt= prompter.clean("Give me goals, shots on target, shots off target and corners from the game between ManU and Swansa")
557
-
558
-
559
- print(prompt)
560
-