backend.lib.search
1import hashlib 2import zipfile 3import secrets 4import random 5import json 6import math 7import csv 8import os 9 10from pathlib import Path 11from abc import ABC, abstractmethod 12 13from backend.lib.processor import BasicProcessor 14from common.lib.helpers import strip_tags, dict_search_and_update, remove_nuls, HashCache 15from common.lib.exceptions import WorkerInterruptedException, ProcessorInterruptedException, MapItemException 16 17 18class Search(BasicProcessor, ABC): 19 """ 20 Process search queries from the front-end 21 22 This class can be descended from to define a 'search worker', which 23 collects items from a given data source to create a dataset according to 24 parameters provided by the user via the web interface. 25 26 Each data source defines a search worker that contains code to interface 27 with e.g. an API or a database server. The search worker also contains a 28 definition of the parameters that can be configured by the user, via the 29 `options` attribute and/or the `get_options()` class method. 30 """ 31 #: Search worker identifier - should end with 'search' for 32 #: backwards-compatibility reasons. For example, `instagram-search`. 33 type = "abstract-search" 34 35 #: Amount of workers of this type that can run in parallel. Be careful with 36 #: this, because values higher than 1 will mean that e.g. API rate limits 37 #: are easily violated. 38 max_workers = 1 39 40 #: This attribute is only used by search workers that collect data from a 41 #: local database, to determine the name of the table to collect the data 42 #: from. If this is `4chan`, for example, items are read from 43 #: `posts_4chan`. 44 prefix = "" 45 46 # Columns to return in csv 47 # Mandatory columns: ['thread_id', 'body', 'subject', 'timestamp'] 48 return_cols = ['thread_id', 'body', 'subject', 'timestamp'] 49 50 import_error_count = 0 51 import_warning_count = 0 52 53 def process(self): 54 """ 55 Create 4CAT dataset from a data source 56 57 Gets query details, passes them on to the object's search method, and 58 writes the results to a file. If that all went well, the query and job 59 are marked as finished. 60 """ 61 62 query_parameters = self.dataset.get_parameters() 63 results_file = self.dataset.get_results_path() 64 65 self.log.info("Querying: %s" % str({k: v for k, v in query_parameters.items() if not self.get_options( 66 config=self.config).get(k, {}).get("sensitive", False)})) 67 68 # Execute the relevant query (string-based, random, countryflag-based) 69 try: 70 if query_parameters.get("file"): 71 items = self.import_from_file(query_parameters.get("file")) 72 else: 73 items = self.search(query_parameters) 74 except WorkerInterruptedException: 75 raise ProcessorInterruptedException("Interrupted while collecting data, trying again later.") 76 77 # Write items to file and update the DataBase status to finished 78 num_items = 0 79 if items: 80 self.dataset.update_status("Writing collected data to dataset file") 81 if self.extension == "csv": 82 num_items = self.items_to_csv(items, results_file) 83 elif self.extension == "ndjson": 84 num_items = self.items_to_ndjson(items, results_file) 85 elif self.extension == "zip": 86 num_items = self.items_to_archive(items, results_file) 87 else: 88 raise NotImplementedError("Datasource query cannot be saved as %s file" % results_file.suffix) 89 90 self.dataset.update_status("Query finished, results are available.") 91 elif items is not None: 92 self.dataset.update_status("Query finished, no results found.") 93 94 if self.import_warning_count != 0 or self.import_error_count != 0: 95 # This may not update if `update_status(is_final=True)` has already been called (e.g., via `finish_with_error`) 96 self.dataset.update_status(f"All data imported. {str(self.import_error_count) + ' item(s) had an unexpected format and cannot be used in 4CAT processors. ' if self.import_error_count != 0 else ''}{str(self.import_warning_count) + ' item(s) missing some data fields. ' if self.import_warning_count != 0 else ''}\n\nMissing data is noted in the `missing_fields` column of this dataset's CSV file; see also the dataset log for details.", is_final=True) 97 98 if not self.dataset.is_finished(): 99 self.dataset.finish(num_rows=num_items) 100 101 def search(self, query): 102 """ 103 Search for items matching the given query 104 105 The real work is done by the get_items() method of the descending 106 class. This method just provides some scaffolding and processing 107 of results via `after_search()`, if it is defined. 108 109 :param dict query: Query parameters 110 :return: Iterable of matching items, or None if there are no results. 111 """ 112 items = self.get_items(query) 113 114 if not items: 115 return None 116 117 # search workers may define an 'after_search' hook that is called after 118 # the query is first completed 119 if hasattr(self, "after_search") and callable(self.after_search): 120 items = self.after_search(items) 121 122 return items 123 124 @abstractmethod 125 def get_items(self, query): 126 """ 127 Method to fetch items with for a given query 128 129 To be implemented by descending classes! 130 131 :param dict query: Query parameters 132 :return Generator: A generator or iterable that returns items 133 collected according to the provided parameters. 134 """ 135 pass 136 137 def import_from_file(self, path): 138 """ 139 Import items from an external file 140 141 By default, this reads a file and parses each line as JSON, returning 142 the parsed object as an item. This works for NDJSON files. Data sources 143 that require importing from other or multiple file types can overwrite 144 this method. 145 146 This method has a generic implementation, but in most cases would be 147 redefined in descending classes to account for nuances in incoming data 148 for a given data source. 149 150 The file is considered disposable and deleted after importing. 151 152 :param str path: Path to read from 153 :return Generator: Yields all items in the file, item for item. 154 """ 155 if type(path) is not Path: 156 path = Path(path) 157 if not path.exists(): 158 return [] 159 160 import_warnings = {} 161 162 # Check if processor and dataset can use map_item 163 check_map_item = self.map_item_method_available(dataset=self.dataset) 164 if not check_map_item: 165 self.log.warning( 166 f"Processor {self.type} importing item without map_item method for Dataset {self.dataset.type} - {self.dataset.key}") 167 168 with path.open(encoding="utf-8") as infile: 169 unmapped_items = False 170 for i, line in enumerate(infile): 171 if self.interrupted: 172 raise WorkerInterruptedException() 173 174 try: 175 # remove NUL bytes here because they trip up a lot of other 176 # things 177 # also include import metadata in item 178 item = json.loads(line.replace("\0", "")) 179 except json.JSONDecodeError: 180 warning = (f"An item on line {i:,} of the imported file could not be parsed as JSON - this may " 181 f"indicate that the file you uploaded was incomplete and you need to try uploading it " 182 f"again. The item will be ignored.") 183 184 if warning not in import_warnings: 185 import_warnings[warning] = 0 186 import_warnings[warning] += 1 187 continue 188 189 190 new_item = { 191 **item["data"], 192 "__import_meta": {k: v for k, v in item.items() if k != "data"} 193 } 194 195 # Check map item here! 196 if check_map_item: 197 try: 198 mapped_item = self.get_mapped_item(new_item) 199 200 # keep track of items that raised a warning 201 # this means the item could be mapped, but there is 202 # some information the user should take note of 203 warning = mapped_item.get_message() 204 if not warning and mapped_item.get_missing_fields(): 205 # usually this would have an explicit warning, but 206 # if not it's still useful to know 207 warning = f"The following fields are missing for this item and will be replaced with a default value: {', '.join(mapped_item.get_missing_fields())}" 208 209 if warning: 210 if warning not in import_warnings: 211 import_warnings[warning] = 0 212 import_warnings[warning] += 1 213 self.import_warning_count += 1 214 215 except MapItemException as e: 216 # NOTE: we still yield the unmappable item; perhaps we need to update a processor's map_item method to account for this new item 217 self.import_error_count += 1 218 self.dataset.warn_unmappable_item(item_count=i, processor=self, error_message=e, warn_admins=unmapped_items is False) 219 unmapped_items = True 220 221 yield new_item 222 223 # warnings were raised about some items 224 # log these, with the number of items each warning applied to 225 if sum(import_warnings.values()) > 0: 226 self.dataset.log("While importing, the following issues were raised:") 227 for warning, num_items in import_warnings.items(): 228 self.dataset.log(f" {warning} (for {num_items:,} item(s))") 229 230 path.unlink() 231 self.dataset.delete_parameter("file") 232 233 def items_to_csv(self, results, filepath): 234 """ 235 Takes a dictionary of results, converts it to a csv, and writes it to the 236 given location. This is mostly a generic dictionary-to-CSV processor but 237 some specific processing is done on the "body" key to strip HTML from it, 238 and a human-readable timestamp is provided next to the UNIX timestamp. 239 240 :param Iterable results: List of dict rows from data source. 241 :param Path filepath: Filepath for the resulting csv 242 243 :return int: Amount of items that were processed 244 245 """ 246 if not filepath: 247 raise ResourceWarning("No result file for query") 248 249 # write the dictionary to a csv 250 if not isinstance(filepath, Path): 251 filepath = Path(filepath) 252 253 # cache hashed author names, so the hashing function (which is 254 # relatively expensive) is not run too often 255 pseudonymise_author = self.parameters.get("pseudonymise", None) == "pseudonymise" 256 anonymise_author = self.parameters.get("pseudonymise", None) == "anonymise" 257 258 # prepare hasher (which we may or may not need) 259 # we use BLAKE2 for its (so far!) resistance against cryptanalysis and 260 # speed, since we will potentially need to calculate a large amount of 261 # hashes 262 salt = secrets.token_bytes(16) 263 hasher = hashlib.blake2b(digest_size=24, salt=salt) 264 hash_cache = HashCache(hasher) 265 266 processed = 0 267 header_written = False 268 with filepath.open("w", encoding="utf-8") as csvfile: 269 # Parsing: remove the HTML tags, but keep the <br> as a newline 270 # Takes around 1.5 times longer 271 for row in results: 272 if self.interrupted: 273 raise ProcessorInterruptedException("Interrupted while writing results to file") 274 275 if not header_written: 276 fieldnames = list(row.keys()) 277 fieldnames.append("unix_timestamp") 278 writer = csv.DictWriter(csvfile, fieldnames=fieldnames, lineterminator='\n') 279 writer.writeheader() 280 header_written = True 281 282 processed += 1 283 284 # Create human dates from timestamp 285 from datetime import datetime, timezone 286 287 if "timestamp" in row: 288 # Data sources should have "timestamp" as a unix epoch integer, 289 # but do some conversion if this is not the case. 290 timestamp = row["timestamp"] 291 if not isinstance(timestamp, int): 292 if isinstance(timestamp, 293 str) and "-" not in timestamp: # String representation of epoch timestamp 294 timestamp = int(timestamp) 295 elif isinstance(timestamp, str) and "-" in timestamp: # Date string 296 try: 297 timestamp = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S").replace( 298 tzinfo=timezone.utc).timestamp() 299 except ValueError: 300 timestamp = "undefined" 301 else: 302 timestamp = "undefined" 303 304 # Add a human-readable date format as well, if we have a valid timestamp. 305 row["unix_timestamp"] = timestamp 306 if timestamp != "undefined": 307 row["timestamp"] = datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') 308 else: 309 row["timestamp"] = timestamp 310 else: 311 row["timestamp"] = "undefined" 312 313 # Parse html to text 314 if row["body"]: 315 row["body"] = strip_tags(row["body"]) 316 317 # replace author column with salted hash of the author name, if 318 # pseudonymisation is enabled 319 if pseudonymise_author: 320 author_fields = [field for field in row.keys() if field.startswith("author")] 321 for author_field in author_fields: 322 row[author_field] = hash_cache.update_cache(row[author_field]) 323 324 # or remove data altogether, if it's anonymisation instead 325 elif anonymise_author: 326 for field in row.keys(): 327 if field.startswith("author"): 328 row[field] = "REDACTED" 329 330 row = remove_nuls(row) 331 writer.writerow(row) 332 333 return processed 334 335 def items_to_ndjson(self, items, filepath): 336 """ 337 Save retrieved items as an ndjson file 338 339 NDJSON is a file with one valid JSON value per line, in this case each 340 of these JSON values represents a retrieved item. This is useful if the 341 retrieved data cannot easily be completely stored as a flat CSV file 342 and we want to leave the choice of how to flatten it to the user. Note 343 that no conversion (e.g. html stripping or pseudonymisation) is done 344 here - the items are saved as-is. 345 346 :param Iterator items: Items to save 347 :param Path filepath: Location to save results file 348 """ 349 if not filepath: 350 raise ResourceWarning("No valid results path supplied") 351 352 # figure out if we need to filter the data somehow 353 hash_cache = None 354 if self.parameters.get("pseudonymise") == "pseudonymise": 355 # cache hashed author names, so the hashing function (which is 356 # relatively expensive) is not run too often 357 hasher = hashlib.blake2b(digest_size=24) 358 hasher.update(str(self.config.get('ANONYMISATION_SALT')).encode("utf-8")) 359 hash_cache = HashCache(hasher) 360 361 processed = 0 362 with filepath.open("w", encoding="utf-8", newline="") as outfile: 363 for item in items: 364 if self.interrupted: 365 raise ProcessorInterruptedException("Interrupted while writing results to file") 366 367 # if pseudo/anonymising, filter data recursively 368 if self.parameters.get("pseudonymise") == "pseudonymise": 369 item = dict_search_and_update(item, ["author*"], hash_cache.update_cache) 370 elif self.parameters.get("anonymise") == "anonymise": 371 item = dict_search_and_update(item, ["author*"], lambda v: "REDACTED") 372 373 outfile.write(json.dumps(item) + "\n") 374 processed += 1 375 376 return processed 377 378 def items_to_archive(self, items, filepath): 379 """ 380 Save retrieved items as an archive 381 382 Assumes that items is an iterable with one item, a Path object 383 referring to a folder containing files to be archived. The folder will 384 be removed afterwards. 385 386 :param items: 387 :param filepath: Where to store the archive 388 :return int: Number of items 389 """ 390 num_items = len(os.listdir(items)) 391 self.write_archive_and_finish(items, None, zipfile.ZIP_STORED, False) 392 return num_items 393 394 395class SearchWithScope(Search, ABC): 396 """ 397 Search class with more complex search pathways 398 399 Some datasources may afford more complex search modes besides simply 400 returning all items matching a given set of parameters. In particular, 401 they may allow for expanding the search scope to the thread in which a 402 given matching item occurs. This subclass allows for the following 403 additional search modes: 404 405 - All items in a thread containing a matching item 406 - All items in a thread containing at least x% matching items 407 """ 408 409 def search(self, query): 410 """ 411 Complex search 412 413 Allows for two separate search pathways, one of which is chosen based 414 on the search query. Additionally, extra items are added to the results 415 if a wider search scope is requested. 416 417 :param dict query: Query parameters 418 :return: Matching items, as iterable, or None if no items match. 419 """ 420 mode = self.get_search_mode(query) 421 422 if mode == "simple": 423 items = self.get_items_simple(query) 424 else: 425 items = self.get_items_complex(query) 426 427 if not items: 428 return None 429 430 # handle the various search scope options after retrieving initial item 431 # list 432 if query.get("search_scope", None) == "dense-threads": 433 # dense threads - all items in all threads in which the requested 434 # proportion of items matches 435 # first, get amount of items for all threads in which matching 436 # items occur and that are long enough 437 thread_ids = tuple([item["thread_id"] for item in items]) 438 self.dataset.update_status("Retrieving thread metadata for %i threads" % len(thread_ids)) 439 try: 440 min_length = int(query.get("scope_length", 30)) 441 except ValueError: 442 min_length = 30 443 444 thread_sizes = self.get_thread_sizes(thread_ids, min_length) 445 446 # determine how many matching items occur per thread in the initial 447 # data set 448 items_per_thread = {} 449 for item in items: 450 if item["thread_id"] not in items_per_thread: 451 items_per_thread[item["thread_id"]] = 0 452 453 items_per_thread[item["thread_id"]] += 1 454 455 # keep all thread IDs where that amount is more than the requested 456 # density 457 qualifying_thread_ids = set() 458 459 self.dataset.update_status("Filtering dense threads") 460 try: 461 percentage = int(query.get("scope_density")) / 100 462 except (ValueError, TypeError): 463 percentage = 0.15 464 465 for thread_id in items_per_thread: 466 if thread_id not in thread_sizes: 467 # thread not long enough 468 continue 469 required_items = math.ceil(percentage * thread_sizes[thread_id]) 470 if items_per_thread[thread_id] >= required_items: 471 qualifying_thread_ids.add(thread_id) 472 473 if len(qualifying_thread_ids) > 25000: 474 self.dataset.update_status( 475 "Too many matching threads (%i) to get full thread data for, aborting. Please try again with a narrower query." % len( 476 qualifying_thread_ids)) 477 return None 478 479 if qualifying_thread_ids: 480 self.dataset.update_status("Fetching all items in %i threads" % len(qualifying_thread_ids)) 481 items = self.fetch_threads(tuple(qualifying_thread_ids)) 482 else: 483 self.dataset.update_status("No threads matched the full thread search parameters.") 484 return None 485 486 elif query.get("search_scope", None) == "full-threads": 487 # get all items in threads containing at least one matching item 488 thread_ids = tuple(set([item["thread_id"] for item in items])) 489 if len(thread_ids) > 25000: 490 self.dataset.update_status( 491 "Too many matching threads (%i) to get full thread data for, aborting. Please try again with a narrower query." % len( 492 thread_ids)) 493 return None 494 495 self.dataset.update_status("Retrieving all items from %i threads" % len(thread_ids)) 496 items = self.fetch_threads(thread_ids) 497 498 elif mode == "complex": 499 # create a random sample subset of all items if requested. for 500 # complex queries, this can usually only be done at this point; 501 # for simple queries, this is handled in get_items_simple 502 if query.get("search_scope", None) == "random-sample": 503 try: 504 self.dataset.update_status("Creating random sample") 505 sample_size = int(query.get("sample_size", 5000)) 506 items = list(items) 507 random.shuffle(items) 508 return items[0:sample_size] 509 except ValueError: 510 pass 511 512 # search workers may define an 'after_search' hook that is called after 513 # the query is first completed 514 if hasattr(self, "after_search") and callable(self.after_search): 515 items = self.after_search(items) 516 517 return items 518 519 def get_items(self, query): 520 """ 521 Not available in this subclass 522 """ 523 raise NotImplementedError("Cannot use get_items() directly in SearchWithScope") 524 525 def get_search_mode(self, query): 526 """ 527 Determine what search mode to use 528 529 Can be overridden by child classes! 530 531 :param dict query: Query parameters 532 :return str: 'simple' or 'complex' 533 """ 534 if query.get("body_match", None) or query.get("subject_match", None): 535 mode = "complex" 536 else: 537 mode = "simple" 538 539 return mode 540 541 @abstractmethod 542 def get_items_simple(self, query): 543 """ 544 Get items via the simple pathway 545 546 If `get_search_mode()` returned `"simple"`, this method is used to 547 retrieve items. What this method does exactly is up to the descending 548 class. 549 550 :param dict query: Query parameters 551 :return Iterable: Items that match the parameters 552 """ 553 pass 554 555 @abstractmethod 556 def get_items_complex(self, query): 557 """ 558 Get items via the complex pathway 559 560 If `get_search_mode()` returned `"complex"`, this method is used to 561 retrieve items. What this method does exactly is up to the descending 562 class. 563 564 :param dict query: Query parameters 565 :return Iterable: Items that match the parameters 566 """ 567 pass 568 569 @abstractmethod 570 def fetch_posts(self, post_ids, where=None, replacements=None): 571 """ 572 Get items for given IDs 573 574 :param Iterable post_ids: Post IDs to e.g. match against a database 575 :param where: Deprecated, do not use 576 :param replacements: Deprecated, do not use 577 :return Iterable[dict]: Post objects 578 """ 579 pass 580 581 @abstractmethod 582 def fetch_threads(self, thread_ids): 583 """ 584 Get items for given thread IDs 585 586 :param Iterable thread_ids: Thread IDs to e.g. match against a database 587 :return Iterable[dict]: Post objects 588 """ 589 pass 590 591 @abstractmethod 592 def get_thread_sizes(self, thread_ids, min_length): 593 """ 594 Get thread lengths for all threads 595 596 :param tuple thread_ids: List of thread IDs to fetch lengths for 597 :param int min_length: Min length for a thread to be included in the 598 results 599 :return dict: Threads sizes, with thread IDs as keys 600 """ 601 pass
19class Search(BasicProcessor, ABC): 20 """ 21 Process search queries from the front-end 22 23 This class can be descended from to define a 'search worker', which 24 collects items from a given data source to create a dataset according to 25 parameters provided by the user via the web interface. 26 27 Each data source defines a search worker that contains code to interface 28 with e.g. an API or a database server. The search worker also contains a 29 definition of the parameters that can be configured by the user, via the 30 `options` attribute and/or the `get_options()` class method. 31 """ 32 #: Search worker identifier - should end with 'search' for 33 #: backwards-compatibility reasons. For example, `instagram-search`. 34 type = "abstract-search" 35 36 #: Amount of workers of this type that can run in parallel. Be careful with 37 #: this, because values higher than 1 will mean that e.g. API rate limits 38 #: are easily violated. 39 max_workers = 1 40 41 #: This attribute is only used by search workers that collect data from a 42 #: local database, to determine the name of the table to collect the data 43 #: from. If this is `4chan`, for example, items are read from 44 #: `posts_4chan`. 45 prefix = "" 46 47 # Columns to return in csv 48 # Mandatory columns: ['thread_id', 'body', 'subject', 'timestamp'] 49 return_cols = ['thread_id', 'body', 'subject', 'timestamp'] 50 51 import_error_count = 0 52 import_warning_count = 0 53 54 def process(self): 55 """ 56 Create 4CAT dataset from a data source 57 58 Gets query details, passes them on to the object's search method, and 59 writes the results to a file. If that all went well, the query and job 60 are marked as finished. 61 """ 62 63 query_parameters = self.dataset.get_parameters() 64 results_file = self.dataset.get_results_path() 65 66 self.log.info("Querying: %s" % str({k: v for k, v in query_parameters.items() if not self.get_options( 67 config=self.config).get(k, {}).get("sensitive", False)})) 68 69 # Execute the relevant query (string-based, random, countryflag-based) 70 try: 71 if query_parameters.get("file"): 72 items = self.import_from_file(query_parameters.get("file")) 73 else: 74 items = self.search(query_parameters) 75 except WorkerInterruptedException: 76 raise ProcessorInterruptedException("Interrupted while collecting data, trying again later.") 77 78 # Write items to file and update the DataBase status to finished 79 num_items = 0 80 if items: 81 self.dataset.update_status("Writing collected data to dataset file") 82 if self.extension == "csv": 83 num_items = self.items_to_csv(items, results_file) 84 elif self.extension == "ndjson": 85 num_items = self.items_to_ndjson(items, results_file) 86 elif self.extension == "zip": 87 num_items = self.items_to_archive(items, results_file) 88 else: 89 raise NotImplementedError("Datasource query cannot be saved as %s file" % results_file.suffix) 90 91 self.dataset.update_status("Query finished, results are available.") 92 elif items is not None: 93 self.dataset.update_status("Query finished, no results found.") 94 95 if self.import_warning_count != 0 or self.import_error_count != 0: 96 # This may not update if `update_status(is_final=True)` has already been called (e.g., via `finish_with_error`) 97 self.dataset.update_status(f"All data imported. {str(self.import_error_count) + ' item(s) had an unexpected format and cannot be used in 4CAT processors. ' if self.import_error_count != 0 else ''}{str(self.import_warning_count) + ' item(s) missing some data fields. ' if self.import_warning_count != 0 else ''}\n\nMissing data is noted in the `missing_fields` column of this dataset's CSV file; see also the dataset log for details.", is_final=True) 98 99 if not self.dataset.is_finished(): 100 self.dataset.finish(num_rows=num_items) 101 102 def search(self, query): 103 """ 104 Search for items matching the given query 105 106 The real work is done by the get_items() method of the descending 107 class. This method just provides some scaffolding and processing 108 of results via `after_search()`, if it is defined. 109 110 :param dict query: Query parameters 111 :return: Iterable of matching items, or None if there are no results. 112 """ 113 items = self.get_items(query) 114 115 if not items: 116 return None 117 118 # search workers may define an 'after_search' hook that is called after 119 # the query is first completed 120 if hasattr(self, "after_search") and callable(self.after_search): 121 items = self.after_search(items) 122 123 return items 124 125 @abstractmethod 126 def get_items(self, query): 127 """ 128 Method to fetch items with for a given query 129 130 To be implemented by descending classes! 131 132 :param dict query: Query parameters 133 :return Generator: A generator or iterable that returns items 134 collected according to the provided parameters. 135 """ 136 pass 137 138 def import_from_file(self, path): 139 """ 140 Import items from an external file 141 142 By default, this reads a file and parses each line as JSON, returning 143 the parsed object as an item. This works for NDJSON files. Data sources 144 that require importing from other or multiple file types can overwrite 145 this method. 146 147 This method has a generic implementation, but in most cases would be 148 redefined in descending classes to account for nuances in incoming data 149 for a given data source. 150 151 The file is considered disposable and deleted after importing. 152 153 :param str path: Path to read from 154 :return Generator: Yields all items in the file, item for item. 155 """ 156 if type(path) is not Path: 157 path = Path(path) 158 if not path.exists(): 159 return [] 160 161 import_warnings = {} 162 163 # Check if processor and dataset can use map_item 164 check_map_item = self.map_item_method_available(dataset=self.dataset) 165 if not check_map_item: 166 self.log.warning( 167 f"Processor {self.type} importing item without map_item method for Dataset {self.dataset.type} - {self.dataset.key}") 168 169 with path.open(encoding="utf-8") as infile: 170 unmapped_items = False 171 for i, line in enumerate(infile): 172 if self.interrupted: 173 raise WorkerInterruptedException() 174 175 try: 176 # remove NUL bytes here because they trip up a lot of other 177 # things 178 # also include import metadata in item 179 item = json.loads(line.replace("\0", "")) 180 except json.JSONDecodeError: 181 warning = (f"An item on line {i:,} of the imported file could not be parsed as JSON - this may " 182 f"indicate that the file you uploaded was incomplete and you need to try uploading it " 183 f"again. The item will be ignored.") 184 185 if warning not in import_warnings: 186 import_warnings[warning] = 0 187 import_warnings[warning] += 1 188 continue 189 190 191 new_item = { 192 **item["data"], 193 "__import_meta": {k: v for k, v in item.items() if k != "data"} 194 } 195 196 # Check map item here! 197 if check_map_item: 198 try: 199 mapped_item = self.get_mapped_item(new_item) 200 201 # keep track of items that raised a warning 202 # this means the item could be mapped, but there is 203 # some information the user should take note of 204 warning = mapped_item.get_message() 205 if not warning and mapped_item.get_missing_fields(): 206 # usually this would have an explicit warning, but 207 # if not it's still useful to know 208 warning = f"The following fields are missing for this item and will be replaced with a default value: {', '.join(mapped_item.get_missing_fields())}" 209 210 if warning: 211 if warning not in import_warnings: 212 import_warnings[warning] = 0 213 import_warnings[warning] += 1 214 self.import_warning_count += 1 215 216 except MapItemException as e: 217 # NOTE: we still yield the unmappable item; perhaps we need to update a processor's map_item method to account for this new item 218 self.import_error_count += 1 219 self.dataset.warn_unmappable_item(item_count=i, processor=self, error_message=e, warn_admins=unmapped_items is False) 220 unmapped_items = True 221 222 yield new_item 223 224 # warnings were raised about some items 225 # log these, with the number of items each warning applied to 226 if sum(import_warnings.values()) > 0: 227 self.dataset.log("While importing, the following issues were raised:") 228 for warning, num_items in import_warnings.items(): 229 self.dataset.log(f" {warning} (for {num_items:,} item(s))") 230 231 path.unlink() 232 self.dataset.delete_parameter("file") 233 234 def items_to_csv(self, results, filepath): 235 """ 236 Takes a dictionary of results, converts it to a csv, and writes it to the 237 given location. This is mostly a generic dictionary-to-CSV processor but 238 some specific processing is done on the "body" key to strip HTML from it, 239 and a human-readable timestamp is provided next to the UNIX timestamp. 240 241 :param Iterable results: List of dict rows from data source. 242 :param Path filepath: Filepath for the resulting csv 243 244 :return int: Amount of items that were processed 245 246 """ 247 if not filepath: 248 raise ResourceWarning("No result file for query") 249 250 # write the dictionary to a csv 251 if not isinstance(filepath, Path): 252 filepath = Path(filepath) 253 254 # cache hashed author names, so the hashing function (which is 255 # relatively expensive) is not run too often 256 pseudonymise_author = self.parameters.get("pseudonymise", None) == "pseudonymise" 257 anonymise_author = self.parameters.get("pseudonymise", None) == "anonymise" 258 259 # prepare hasher (which we may or may not need) 260 # we use BLAKE2 for its (so far!) resistance against cryptanalysis and 261 # speed, since we will potentially need to calculate a large amount of 262 # hashes 263 salt = secrets.token_bytes(16) 264 hasher = hashlib.blake2b(digest_size=24, salt=salt) 265 hash_cache = HashCache(hasher) 266 267 processed = 0 268 header_written = False 269 with filepath.open("w", encoding="utf-8") as csvfile: 270 # Parsing: remove the HTML tags, but keep the <br> as a newline 271 # Takes around 1.5 times longer 272 for row in results: 273 if self.interrupted: 274 raise ProcessorInterruptedException("Interrupted while writing results to file") 275 276 if not header_written: 277 fieldnames = list(row.keys()) 278 fieldnames.append("unix_timestamp") 279 writer = csv.DictWriter(csvfile, fieldnames=fieldnames, lineterminator='\n') 280 writer.writeheader() 281 header_written = True 282 283 processed += 1 284 285 # Create human dates from timestamp 286 from datetime import datetime, timezone 287 288 if "timestamp" in row: 289 # Data sources should have "timestamp" as a unix epoch integer, 290 # but do some conversion if this is not the case. 291 timestamp = row["timestamp"] 292 if not isinstance(timestamp, int): 293 if isinstance(timestamp, 294 str) and "-" not in timestamp: # String representation of epoch timestamp 295 timestamp = int(timestamp) 296 elif isinstance(timestamp, str) and "-" in timestamp: # Date string 297 try: 298 timestamp = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S").replace( 299 tzinfo=timezone.utc).timestamp() 300 except ValueError: 301 timestamp = "undefined" 302 else: 303 timestamp = "undefined" 304 305 # Add a human-readable date format as well, if we have a valid timestamp. 306 row["unix_timestamp"] = timestamp 307 if timestamp != "undefined": 308 row["timestamp"] = datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') 309 else: 310 row["timestamp"] = timestamp 311 else: 312 row["timestamp"] = "undefined" 313 314 # Parse html to text 315 if row["body"]: 316 row["body"] = strip_tags(row["body"]) 317 318 # replace author column with salted hash of the author name, if 319 # pseudonymisation is enabled 320 if pseudonymise_author: 321 author_fields = [field for field in row.keys() if field.startswith("author")] 322 for author_field in author_fields: 323 row[author_field] = hash_cache.update_cache(row[author_field]) 324 325 # or remove data altogether, if it's anonymisation instead 326 elif anonymise_author: 327 for field in row.keys(): 328 if field.startswith("author"): 329 row[field] = "REDACTED" 330 331 row = remove_nuls(row) 332 writer.writerow(row) 333 334 return processed 335 336 def items_to_ndjson(self, items, filepath): 337 """ 338 Save retrieved items as an ndjson file 339 340 NDJSON is a file with one valid JSON value per line, in this case each 341 of these JSON values represents a retrieved item. This is useful if the 342 retrieved data cannot easily be completely stored as a flat CSV file 343 and we want to leave the choice of how to flatten it to the user. Note 344 that no conversion (e.g. html stripping or pseudonymisation) is done 345 here - the items are saved as-is. 346 347 :param Iterator items: Items to save 348 :param Path filepath: Location to save results file 349 """ 350 if not filepath: 351 raise ResourceWarning("No valid results path supplied") 352 353 # figure out if we need to filter the data somehow 354 hash_cache = None 355 if self.parameters.get("pseudonymise") == "pseudonymise": 356 # cache hashed author names, so the hashing function (which is 357 # relatively expensive) is not run too often 358 hasher = hashlib.blake2b(digest_size=24) 359 hasher.update(str(self.config.get('ANONYMISATION_SALT')).encode("utf-8")) 360 hash_cache = HashCache(hasher) 361 362 processed = 0 363 with filepath.open("w", encoding="utf-8", newline="") as outfile: 364 for item in items: 365 if self.interrupted: 366 raise ProcessorInterruptedException("Interrupted while writing results to file") 367 368 # if pseudo/anonymising, filter data recursively 369 if self.parameters.get("pseudonymise") == "pseudonymise": 370 item = dict_search_and_update(item, ["author*"], hash_cache.update_cache) 371 elif self.parameters.get("anonymise") == "anonymise": 372 item = dict_search_and_update(item, ["author*"], lambda v: "REDACTED") 373 374 outfile.write(json.dumps(item) + "\n") 375 processed += 1 376 377 return processed 378 379 def items_to_archive(self, items, filepath): 380 """ 381 Save retrieved items as an archive 382 383 Assumes that items is an iterable with one item, a Path object 384 referring to a folder containing files to be archived. The folder will 385 be removed afterwards. 386 387 :param items: 388 :param filepath: Where to store the archive 389 :return int: Number of items 390 """ 391 num_items = len(os.listdir(items)) 392 self.write_archive_and_finish(items, None, zipfile.ZIP_STORED, False) 393 return num_items
Process search queries from the front-end
This class can be descended from to define a 'search worker', which collects items from a given data source to create a dataset according to parameters provided by the user via the web interface.
Each data source defines a search worker that contains code to interface
with e.g. an API or a database server. The search worker also contains a
definition of the parameters that can be configured by the user, via the
options attribute and/or the get_options() class method.
54 def process(self): 55 """ 56 Create 4CAT dataset from a data source 57 58 Gets query details, passes them on to the object's search method, and 59 writes the results to a file. If that all went well, the query and job 60 are marked as finished. 61 """ 62 63 query_parameters = self.dataset.get_parameters() 64 results_file = self.dataset.get_results_path() 65 66 self.log.info("Querying: %s" % str({k: v for k, v in query_parameters.items() if not self.get_options( 67 config=self.config).get(k, {}).get("sensitive", False)})) 68 69 # Execute the relevant query (string-based, random, countryflag-based) 70 try: 71 if query_parameters.get("file"): 72 items = self.import_from_file(query_parameters.get("file")) 73 else: 74 items = self.search(query_parameters) 75 except WorkerInterruptedException: 76 raise ProcessorInterruptedException("Interrupted while collecting data, trying again later.") 77 78 # Write items to file and update the DataBase status to finished 79 num_items = 0 80 if items: 81 self.dataset.update_status("Writing collected data to dataset file") 82 if self.extension == "csv": 83 num_items = self.items_to_csv(items, results_file) 84 elif self.extension == "ndjson": 85 num_items = self.items_to_ndjson(items, results_file) 86 elif self.extension == "zip": 87 num_items = self.items_to_archive(items, results_file) 88 else: 89 raise NotImplementedError("Datasource query cannot be saved as %s file" % results_file.suffix) 90 91 self.dataset.update_status("Query finished, results are available.") 92 elif items is not None: 93 self.dataset.update_status("Query finished, no results found.") 94 95 if self.import_warning_count != 0 or self.import_error_count != 0: 96 # This may not update if `update_status(is_final=True)` has already been called (e.g., via `finish_with_error`) 97 self.dataset.update_status(f"All data imported. {str(self.import_error_count) + ' item(s) had an unexpected format and cannot be used in 4CAT processors. ' if self.import_error_count != 0 else ''}{str(self.import_warning_count) + ' item(s) missing some data fields. ' if self.import_warning_count != 0 else ''}\n\nMissing data is noted in the `missing_fields` column of this dataset's CSV file; see also the dataset log for details.", is_final=True) 98 99 if not self.dataset.is_finished(): 100 self.dataset.finish(num_rows=num_items)
Create 4CAT dataset from a data source
Gets query details, passes them on to the object's search method, and writes the results to a file. If that all went well, the query and job are marked as finished.
102 def search(self, query): 103 """ 104 Search for items matching the given query 105 106 The real work is done by the get_items() method of the descending 107 class. This method just provides some scaffolding and processing 108 of results via `after_search()`, if it is defined. 109 110 :param dict query: Query parameters 111 :return: Iterable of matching items, or None if there are no results. 112 """ 113 items = self.get_items(query) 114 115 if not items: 116 return None 117 118 # search workers may define an 'after_search' hook that is called after 119 # the query is first completed 120 if hasattr(self, "after_search") and callable(self.after_search): 121 items = self.after_search(items) 122 123 return items
Search for items matching the given query
The real work is done by the get_items() method of the descending
class. This method just provides some scaffolding and processing
of results via after_search(), if it is defined.
Parameters
- dict query: Query parameters
Returns
Iterable of matching items, or None if there are no results.
125 @abstractmethod 126 def get_items(self, query): 127 """ 128 Method to fetch items with for a given query 129 130 To be implemented by descending classes! 131 132 :param dict query: Query parameters 133 :return Generator: A generator or iterable that returns items 134 collected according to the provided parameters. 135 """ 136 pass
Method to fetch items with for a given query
To be implemented by descending classes!
Parameters
- dict query: Query parameters
Returns
A generator or iterable that returns items collected according to the provided parameters.
138 def import_from_file(self, path): 139 """ 140 Import items from an external file 141 142 By default, this reads a file and parses each line as JSON, returning 143 the parsed object as an item. This works for NDJSON files. Data sources 144 that require importing from other or multiple file types can overwrite 145 this method. 146 147 This method has a generic implementation, but in most cases would be 148 redefined in descending classes to account for nuances in incoming data 149 for a given data source. 150 151 The file is considered disposable and deleted after importing. 152 153 :param str path: Path to read from 154 :return Generator: Yields all items in the file, item for item. 155 """ 156 if type(path) is not Path: 157 path = Path(path) 158 if not path.exists(): 159 return [] 160 161 import_warnings = {} 162 163 # Check if processor and dataset can use map_item 164 check_map_item = self.map_item_method_available(dataset=self.dataset) 165 if not check_map_item: 166 self.log.warning( 167 f"Processor {self.type} importing item without map_item method for Dataset {self.dataset.type} - {self.dataset.key}") 168 169 with path.open(encoding="utf-8") as infile: 170 unmapped_items = False 171 for i, line in enumerate(infile): 172 if self.interrupted: 173 raise WorkerInterruptedException() 174 175 try: 176 # remove NUL bytes here because they trip up a lot of other 177 # things 178 # also include import metadata in item 179 item = json.loads(line.replace("\0", "")) 180 except json.JSONDecodeError: 181 warning = (f"An item on line {i:,} of the imported file could not be parsed as JSON - this may " 182 f"indicate that the file you uploaded was incomplete and you need to try uploading it " 183 f"again. The item will be ignored.") 184 185 if warning not in import_warnings: 186 import_warnings[warning] = 0 187 import_warnings[warning] += 1 188 continue 189 190 191 new_item = { 192 **item["data"], 193 "__import_meta": {k: v for k, v in item.items() if k != "data"} 194 } 195 196 # Check map item here! 197 if check_map_item: 198 try: 199 mapped_item = self.get_mapped_item(new_item) 200 201 # keep track of items that raised a warning 202 # this means the item could be mapped, but there is 203 # some information the user should take note of 204 warning = mapped_item.get_message() 205 if not warning and mapped_item.get_missing_fields(): 206 # usually this would have an explicit warning, but 207 # if not it's still useful to know 208 warning = f"The following fields are missing for this item and will be replaced with a default value: {', '.join(mapped_item.get_missing_fields())}" 209 210 if warning: 211 if warning not in import_warnings: 212 import_warnings[warning] = 0 213 import_warnings[warning] += 1 214 self.import_warning_count += 1 215 216 except MapItemException as e: 217 # NOTE: we still yield the unmappable item; perhaps we need to update a processor's map_item method to account for this new item 218 self.import_error_count += 1 219 self.dataset.warn_unmappable_item(item_count=i, processor=self, error_message=e, warn_admins=unmapped_items is False) 220 unmapped_items = True 221 222 yield new_item 223 224 # warnings were raised about some items 225 # log these, with the number of items each warning applied to 226 if sum(import_warnings.values()) > 0: 227 self.dataset.log("While importing, the following issues were raised:") 228 for warning, num_items in import_warnings.items(): 229 self.dataset.log(f" {warning} (for {num_items:,} item(s))") 230 231 path.unlink() 232 self.dataset.delete_parameter("file")
Import items from an external file
By default, this reads a file and parses each line as JSON, returning the parsed object as an item. This works for NDJSON files. Data sources that require importing from other or multiple file types can overwrite this method.
This method has a generic implementation, but in most cases would be redefined in descending classes to account for nuances in incoming data for a given data source.
The file is considered disposable and deleted after importing.
Parameters
- str path: Path to read from
Returns
Yields all items in the file, item for item.
234 def items_to_csv(self, results, filepath): 235 """ 236 Takes a dictionary of results, converts it to a csv, and writes it to the 237 given location. This is mostly a generic dictionary-to-CSV processor but 238 some specific processing is done on the "body" key to strip HTML from it, 239 and a human-readable timestamp is provided next to the UNIX timestamp. 240 241 :param Iterable results: List of dict rows from data source. 242 :param Path filepath: Filepath for the resulting csv 243 244 :return int: Amount of items that were processed 245 246 """ 247 if not filepath: 248 raise ResourceWarning("No result file for query") 249 250 # write the dictionary to a csv 251 if not isinstance(filepath, Path): 252 filepath = Path(filepath) 253 254 # cache hashed author names, so the hashing function (which is 255 # relatively expensive) is not run too often 256 pseudonymise_author = self.parameters.get("pseudonymise", None) == "pseudonymise" 257 anonymise_author = self.parameters.get("pseudonymise", None) == "anonymise" 258 259 # prepare hasher (which we may or may not need) 260 # we use BLAKE2 for its (so far!) resistance against cryptanalysis and 261 # speed, since we will potentially need to calculate a large amount of 262 # hashes 263 salt = secrets.token_bytes(16) 264 hasher = hashlib.blake2b(digest_size=24, salt=salt) 265 hash_cache = HashCache(hasher) 266 267 processed = 0 268 header_written = False 269 with filepath.open("w", encoding="utf-8") as csvfile: 270 # Parsing: remove the HTML tags, but keep the <br> as a newline 271 # Takes around 1.5 times longer 272 for row in results: 273 if self.interrupted: 274 raise ProcessorInterruptedException("Interrupted while writing results to file") 275 276 if not header_written: 277 fieldnames = list(row.keys()) 278 fieldnames.append("unix_timestamp") 279 writer = csv.DictWriter(csvfile, fieldnames=fieldnames, lineterminator='\n') 280 writer.writeheader() 281 header_written = True 282 283 processed += 1 284 285 # Create human dates from timestamp 286 from datetime import datetime, timezone 287 288 if "timestamp" in row: 289 # Data sources should have "timestamp" as a unix epoch integer, 290 # but do some conversion if this is not the case. 291 timestamp = row["timestamp"] 292 if not isinstance(timestamp, int): 293 if isinstance(timestamp, 294 str) and "-" not in timestamp: # String representation of epoch timestamp 295 timestamp = int(timestamp) 296 elif isinstance(timestamp, str) and "-" in timestamp: # Date string 297 try: 298 timestamp = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S").replace( 299 tzinfo=timezone.utc).timestamp() 300 except ValueError: 301 timestamp = "undefined" 302 else: 303 timestamp = "undefined" 304 305 # Add a human-readable date format as well, if we have a valid timestamp. 306 row["unix_timestamp"] = timestamp 307 if timestamp != "undefined": 308 row["timestamp"] = datetime.utcfromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S') 309 else: 310 row["timestamp"] = timestamp 311 else: 312 row["timestamp"] = "undefined" 313 314 # Parse html to text 315 if row["body"]: 316 row["body"] = strip_tags(row["body"]) 317 318 # replace author column with salted hash of the author name, if 319 # pseudonymisation is enabled 320 if pseudonymise_author: 321 author_fields = [field for field in row.keys() if field.startswith("author")] 322 for author_field in author_fields: 323 row[author_field] = hash_cache.update_cache(row[author_field]) 324 325 # or remove data altogether, if it's anonymisation instead 326 elif anonymise_author: 327 for field in row.keys(): 328 if field.startswith("author"): 329 row[field] = "REDACTED" 330 331 row = remove_nuls(row) 332 writer.writerow(row) 333 334 return processed
Takes a dictionary of results, converts it to a csv, and writes it to the given location. This is mostly a generic dictionary-to-CSV processor but some specific processing is done on the "body" key to strip HTML from it, and a human-readable timestamp is provided next to the UNIX timestamp.
Parameters
- Iterable results: List of dict rows from data source.
- Path filepath: Filepath for the resulting csv
Returns
Amount of items that were processed
336 def items_to_ndjson(self, items, filepath): 337 """ 338 Save retrieved items as an ndjson file 339 340 NDJSON is a file with one valid JSON value per line, in this case each 341 of these JSON values represents a retrieved item. This is useful if the 342 retrieved data cannot easily be completely stored as a flat CSV file 343 and we want to leave the choice of how to flatten it to the user. Note 344 that no conversion (e.g. html stripping or pseudonymisation) is done 345 here - the items are saved as-is. 346 347 :param Iterator items: Items to save 348 :param Path filepath: Location to save results file 349 """ 350 if not filepath: 351 raise ResourceWarning("No valid results path supplied") 352 353 # figure out if we need to filter the data somehow 354 hash_cache = None 355 if self.parameters.get("pseudonymise") == "pseudonymise": 356 # cache hashed author names, so the hashing function (which is 357 # relatively expensive) is not run too often 358 hasher = hashlib.blake2b(digest_size=24) 359 hasher.update(str(self.config.get('ANONYMISATION_SALT')).encode("utf-8")) 360 hash_cache = HashCache(hasher) 361 362 processed = 0 363 with filepath.open("w", encoding="utf-8", newline="") as outfile: 364 for item in items: 365 if self.interrupted: 366 raise ProcessorInterruptedException("Interrupted while writing results to file") 367 368 # if pseudo/anonymising, filter data recursively 369 if self.parameters.get("pseudonymise") == "pseudonymise": 370 item = dict_search_and_update(item, ["author*"], hash_cache.update_cache) 371 elif self.parameters.get("anonymise") == "anonymise": 372 item = dict_search_and_update(item, ["author*"], lambda v: "REDACTED") 373 374 outfile.write(json.dumps(item) + "\n") 375 processed += 1 376 377 return processed
Save retrieved items as an ndjson file
NDJSON is a file with one valid JSON value per line, in this case each of these JSON values represents a retrieved item. This is useful if the retrieved data cannot easily be completely stored as a flat CSV file and we want to leave the choice of how to flatten it to the user. Note that no conversion (e.g. html stripping or pseudonymisation) is done here - the items are saved as-is.
Parameters
- Iterator items: Items to save
- Path filepath: Location to save results file
379 def items_to_archive(self, items, filepath): 380 """ 381 Save retrieved items as an archive 382 383 Assumes that items is an iterable with one item, a Path object 384 referring to a folder containing files to be archived. The folder will 385 be removed afterwards. 386 387 :param items: 388 :param filepath: Where to store the archive 389 :return int: Number of items 390 """ 391 num_items = len(os.listdir(items)) 392 self.write_archive_and_finish(items, None, zipfile.ZIP_STORED, False) 393 return num_items
Save retrieved items as an archive
Assumes that items is an iterable with one item, a Path object referring to a folder containing files to be archived. The folder will be removed afterwards.
Parameters
- items:
- filepath: Where to store the archive
Returns
Number of items
Inherited Members
- backend.lib.worker.BasicWorker
- BasicWorker
- INTERRUPT_NONE
- INTERRUPT_RETRY
- INTERRUPT_CANCEL
- queue
- log
- manager
- interrupted
- modules
- init_time
- name
- run
- clean_up
- request_interrupt
- run_interruptable_process
- get_queue_id
- is_4cat_class
- backend.lib.processor.BasicProcessor
- db
- job
- dataset
- owner
- source_dataset
- source_file
- description
- category
- extension
- config
- is_running_in_preset
- filepath
- for_cleanup
- work
- after_process
- clean_up_on_error
- abort
- iterate_proxied_requests
- push_proxied_request
- flush_proxied_requests
- unpack_archive_contents
- extract_archived_file_by_name
- write_csv_items_and_finish
- write_archive_and_finish
- create_standalone
- save_annotations
- map_item_method_available
- get_mapped_item
- is_filter
- get_options
- get_status
- is_top_dataset
- is_from_collector
- get_extension
- is_rankable
- exclude_followup_processors
- is_4cat_processor
396class SearchWithScope(Search, ABC): 397 """ 398 Search class with more complex search pathways 399 400 Some datasources may afford more complex search modes besides simply 401 returning all items matching a given set of parameters. In particular, 402 they may allow for expanding the search scope to the thread in which a 403 given matching item occurs. This subclass allows for the following 404 additional search modes: 405 406 - All items in a thread containing a matching item 407 - All items in a thread containing at least x% matching items 408 """ 409 410 def search(self, query): 411 """ 412 Complex search 413 414 Allows for two separate search pathways, one of which is chosen based 415 on the search query. Additionally, extra items are added to the results 416 if a wider search scope is requested. 417 418 :param dict query: Query parameters 419 :return: Matching items, as iterable, or None if no items match. 420 """ 421 mode = self.get_search_mode(query) 422 423 if mode == "simple": 424 items = self.get_items_simple(query) 425 else: 426 items = self.get_items_complex(query) 427 428 if not items: 429 return None 430 431 # handle the various search scope options after retrieving initial item 432 # list 433 if query.get("search_scope", None) == "dense-threads": 434 # dense threads - all items in all threads in which the requested 435 # proportion of items matches 436 # first, get amount of items for all threads in which matching 437 # items occur and that are long enough 438 thread_ids = tuple([item["thread_id"] for item in items]) 439 self.dataset.update_status("Retrieving thread metadata for %i threads" % len(thread_ids)) 440 try: 441 min_length = int(query.get("scope_length", 30)) 442 except ValueError: 443 min_length = 30 444 445 thread_sizes = self.get_thread_sizes(thread_ids, min_length) 446 447 # determine how many matching items occur per thread in the initial 448 # data set 449 items_per_thread = {} 450 for item in items: 451 if item["thread_id"] not in items_per_thread: 452 items_per_thread[item["thread_id"]] = 0 453 454 items_per_thread[item["thread_id"]] += 1 455 456 # keep all thread IDs where that amount is more than the requested 457 # density 458 qualifying_thread_ids = set() 459 460 self.dataset.update_status("Filtering dense threads") 461 try: 462 percentage = int(query.get("scope_density")) / 100 463 except (ValueError, TypeError): 464 percentage = 0.15 465 466 for thread_id in items_per_thread: 467 if thread_id not in thread_sizes: 468 # thread not long enough 469 continue 470 required_items = math.ceil(percentage * thread_sizes[thread_id]) 471 if items_per_thread[thread_id] >= required_items: 472 qualifying_thread_ids.add(thread_id) 473 474 if len(qualifying_thread_ids) > 25000: 475 self.dataset.update_status( 476 "Too many matching threads (%i) to get full thread data for, aborting. Please try again with a narrower query." % len( 477 qualifying_thread_ids)) 478 return None 479 480 if qualifying_thread_ids: 481 self.dataset.update_status("Fetching all items in %i threads" % len(qualifying_thread_ids)) 482 items = self.fetch_threads(tuple(qualifying_thread_ids)) 483 else: 484 self.dataset.update_status("No threads matched the full thread search parameters.") 485 return None 486 487 elif query.get("search_scope", None) == "full-threads": 488 # get all items in threads containing at least one matching item 489 thread_ids = tuple(set([item["thread_id"] for item in items])) 490 if len(thread_ids) > 25000: 491 self.dataset.update_status( 492 "Too many matching threads (%i) to get full thread data for, aborting. Please try again with a narrower query." % len( 493 thread_ids)) 494 return None 495 496 self.dataset.update_status("Retrieving all items from %i threads" % len(thread_ids)) 497 items = self.fetch_threads(thread_ids) 498 499 elif mode == "complex": 500 # create a random sample subset of all items if requested. for 501 # complex queries, this can usually only be done at this point; 502 # for simple queries, this is handled in get_items_simple 503 if query.get("search_scope", None) == "random-sample": 504 try: 505 self.dataset.update_status("Creating random sample") 506 sample_size = int(query.get("sample_size", 5000)) 507 items = list(items) 508 random.shuffle(items) 509 return items[0:sample_size] 510 except ValueError: 511 pass 512 513 # search workers may define an 'after_search' hook that is called after 514 # the query is first completed 515 if hasattr(self, "after_search") and callable(self.after_search): 516 items = self.after_search(items) 517 518 return items 519 520 def get_items(self, query): 521 """ 522 Not available in this subclass 523 """ 524 raise NotImplementedError("Cannot use get_items() directly in SearchWithScope") 525 526 def get_search_mode(self, query): 527 """ 528 Determine what search mode to use 529 530 Can be overridden by child classes! 531 532 :param dict query: Query parameters 533 :return str: 'simple' or 'complex' 534 """ 535 if query.get("body_match", None) or query.get("subject_match", None): 536 mode = "complex" 537 else: 538 mode = "simple" 539 540 return mode 541 542 @abstractmethod 543 def get_items_simple(self, query): 544 """ 545 Get items via the simple pathway 546 547 If `get_search_mode()` returned `"simple"`, this method is used to 548 retrieve items. What this method does exactly is up to the descending 549 class. 550 551 :param dict query: Query parameters 552 :return Iterable: Items that match the parameters 553 """ 554 pass 555 556 @abstractmethod 557 def get_items_complex(self, query): 558 """ 559 Get items via the complex pathway 560 561 If `get_search_mode()` returned `"complex"`, this method is used to 562 retrieve items. What this method does exactly is up to the descending 563 class. 564 565 :param dict query: Query parameters 566 :return Iterable: Items that match the parameters 567 """ 568 pass 569 570 @abstractmethod 571 def fetch_posts(self, post_ids, where=None, replacements=None): 572 """ 573 Get items for given IDs 574 575 :param Iterable post_ids: Post IDs to e.g. match against a database 576 :param where: Deprecated, do not use 577 :param replacements: Deprecated, do not use 578 :return Iterable[dict]: Post objects 579 """ 580 pass 581 582 @abstractmethod 583 def fetch_threads(self, thread_ids): 584 """ 585 Get items for given thread IDs 586 587 :param Iterable thread_ids: Thread IDs to e.g. match against a database 588 :return Iterable[dict]: Post objects 589 """ 590 pass 591 592 @abstractmethod 593 def get_thread_sizes(self, thread_ids, min_length): 594 """ 595 Get thread lengths for all threads 596 597 :param tuple thread_ids: List of thread IDs to fetch lengths for 598 :param int min_length: Min length for a thread to be included in the 599 results 600 :return dict: Threads sizes, with thread IDs as keys 601 """ 602 pass
Search class with more complex search pathways
Some datasources may afford more complex search modes besides simply returning all items matching a given set of parameters. In particular, they may allow for expanding the search scope to the thread in which a given matching item occurs. This subclass allows for the following additional search modes:
- All items in a thread containing a matching item
- All items in a thread containing at least x% matching items
410 def search(self, query): 411 """ 412 Complex search 413 414 Allows for two separate search pathways, one of which is chosen based 415 on the search query. Additionally, extra items are added to the results 416 if a wider search scope is requested. 417 418 :param dict query: Query parameters 419 :return: Matching items, as iterable, or None if no items match. 420 """ 421 mode = self.get_search_mode(query) 422 423 if mode == "simple": 424 items = self.get_items_simple(query) 425 else: 426 items = self.get_items_complex(query) 427 428 if not items: 429 return None 430 431 # handle the various search scope options after retrieving initial item 432 # list 433 if query.get("search_scope", None) == "dense-threads": 434 # dense threads - all items in all threads in which the requested 435 # proportion of items matches 436 # first, get amount of items for all threads in which matching 437 # items occur and that are long enough 438 thread_ids = tuple([item["thread_id"] for item in items]) 439 self.dataset.update_status("Retrieving thread metadata for %i threads" % len(thread_ids)) 440 try: 441 min_length = int(query.get("scope_length", 30)) 442 except ValueError: 443 min_length = 30 444 445 thread_sizes = self.get_thread_sizes(thread_ids, min_length) 446 447 # determine how many matching items occur per thread in the initial 448 # data set 449 items_per_thread = {} 450 for item in items: 451 if item["thread_id"] not in items_per_thread: 452 items_per_thread[item["thread_id"]] = 0 453 454 items_per_thread[item["thread_id"]] += 1 455 456 # keep all thread IDs where that amount is more than the requested 457 # density 458 qualifying_thread_ids = set() 459 460 self.dataset.update_status("Filtering dense threads") 461 try: 462 percentage = int(query.get("scope_density")) / 100 463 except (ValueError, TypeError): 464 percentage = 0.15 465 466 for thread_id in items_per_thread: 467 if thread_id not in thread_sizes: 468 # thread not long enough 469 continue 470 required_items = math.ceil(percentage * thread_sizes[thread_id]) 471 if items_per_thread[thread_id] >= required_items: 472 qualifying_thread_ids.add(thread_id) 473 474 if len(qualifying_thread_ids) > 25000: 475 self.dataset.update_status( 476 "Too many matching threads (%i) to get full thread data for, aborting. Please try again with a narrower query." % len( 477 qualifying_thread_ids)) 478 return None 479 480 if qualifying_thread_ids: 481 self.dataset.update_status("Fetching all items in %i threads" % len(qualifying_thread_ids)) 482 items = self.fetch_threads(tuple(qualifying_thread_ids)) 483 else: 484 self.dataset.update_status("No threads matched the full thread search parameters.") 485 return None 486 487 elif query.get("search_scope", None) == "full-threads": 488 # get all items in threads containing at least one matching item 489 thread_ids = tuple(set([item["thread_id"] for item in items])) 490 if len(thread_ids) > 25000: 491 self.dataset.update_status( 492 "Too many matching threads (%i) to get full thread data for, aborting. Please try again with a narrower query." % len( 493 thread_ids)) 494 return None 495 496 self.dataset.update_status("Retrieving all items from %i threads" % len(thread_ids)) 497 items = self.fetch_threads(thread_ids) 498 499 elif mode == "complex": 500 # create a random sample subset of all items if requested. for 501 # complex queries, this can usually only be done at this point; 502 # for simple queries, this is handled in get_items_simple 503 if query.get("search_scope", None) == "random-sample": 504 try: 505 self.dataset.update_status("Creating random sample") 506 sample_size = int(query.get("sample_size", 5000)) 507 items = list(items) 508 random.shuffle(items) 509 return items[0:sample_size] 510 except ValueError: 511 pass 512 513 # search workers may define an 'after_search' hook that is called after 514 # the query is first completed 515 if hasattr(self, "after_search") and callable(self.after_search): 516 items = self.after_search(items) 517 518 return items
Complex search
Allows for two separate search pathways, one of which is chosen based on the search query. Additionally, extra items are added to the results if a wider search scope is requested.
Parameters
- dict query: Query parameters
Returns
Matching items, as iterable, or None if no items match.
520 def get_items(self, query): 521 """ 522 Not available in this subclass 523 """ 524 raise NotImplementedError("Cannot use get_items() directly in SearchWithScope")
Not available in this subclass
526 def get_search_mode(self, query): 527 """ 528 Determine what search mode to use 529 530 Can be overridden by child classes! 531 532 :param dict query: Query parameters 533 :return str: 'simple' or 'complex' 534 """ 535 if query.get("body_match", None) or query.get("subject_match", None): 536 mode = "complex" 537 else: 538 mode = "simple" 539 540 return mode
Determine what search mode to use
Can be overridden by child classes!
Parameters
- dict query: Query parameters
Returns
'simple' or 'complex'
542 @abstractmethod 543 def get_items_simple(self, query): 544 """ 545 Get items via the simple pathway 546 547 If `get_search_mode()` returned `"simple"`, this method is used to 548 retrieve items. What this method does exactly is up to the descending 549 class. 550 551 :param dict query: Query parameters 552 :return Iterable: Items that match the parameters 553 """ 554 pass
Get items via the simple pathway
If get_search_mode() returned "simple", this method is used to
retrieve items. What this method does exactly is up to the descending
class.
Parameters
- dict query: Query parameters
Returns
Items that match the parameters
556 @abstractmethod 557 def get_items_complex(self, query): 558 """ 559 Get items via the complex pathway 560 561 If `get_search_mode()` returned `"complex"`, this method is used to 562 retrieve items. What this method does exactly is up to the descending 563 class. 564 565 :param dict query: Query parameters 566 :return Iterable: Items that match the parameters 567 """ 568 pass
Get items via the complex pathway
If get_search_mode() returned "complex", this method is used to
retrieve items. What this method does exactly is up to the descending
class.
Parameters
- dict query: Query parameters
Returns
Items that match the parameters
570 @abstractmethod 571 def fetch_posts(self, post_ids, where=None, replacements=None): 572 """ 573 Get items for given IDs 574 575 :param Iterable post_ids: Post IDs to e.g. match against a database 576 :param where: Deprecated, do not use 577 :param replacements: Deprecated, do not use 578 :return Iterable[dict]: Post objects 579 """ 580 pass
Get items for given IDs
Parameters
- Iterable post_ids: Post IDs to e.g. match against a database
- where: Deprecated, do not use
- replacements: Deprecated, do not use
Returns
Post objects
582 @abstractmethod 583 def fetch_threads(self, thread_ids): 584 """ 585 Get items for given thread IDs 586 587 :param Iterable thread_ids: Thread IDs to e.g. match against a database 588 :return Iterable[dict]: Post objects 589 """ 590 pass
Get items for given thread IDs
Parameters
- Iterable thread_ids: Thread IDs to e.g. match against a database
Returns
Post objects
592 @abstractmethod 593 def get_thread_sizes(self, thread_ids, min_length): 594 """ 595 Get thread lengths for all threads 596 597 :param tuple thread_ids: List of thread IDs to fetch lengths for 598 :param int min_length: Min length for a thread to be included in the 599 results 600 :return dict: Threads sizes, with thread IDs as keys 601 """ 602 pass
Get thread lengths for all threads
Parameters
- tuple thread_ids: List of thread IDs to fetch lengths for
- int min_length: Min length for a thread to be included in the results
Returns
Threads sizes, with thread IDs as keys
Inherited Members
- backend.lib.worker.BasicWorker
- BasicWorker
- INTERRUPT_NONE
- INTERRUPT_RETRY
- INTERRUPT_CANCEL
- queue
- log
- manager
- interrupted
- modules
- init_time
- name
- run
- clean_up
- request_interrupt
- run_interruptable_process
- get_queue_id
- is_4cat_class
- Search
- type
- max_workers
- prefix
- return_cols
- import_error_count
- import_warning_count
- process
- import_from_file
- items_to_csv
- items_to_ndjson
- items_to_archive
- backend.lib.processor.BasicProcessor
- db
- job
- dataset
- owner
- source_dataset
- source_file
- description
- category
- extension
- config
- is_running_in_preset
- filepath
- for_cleanup
- work
- after_process
- clean_up_on_error
- abort
- iterate_proxied_requests
- push_proxied_request
- flush_proxied_requests
- unpack_archive_contents
- extract_archived_file_by_name
- write_csv_items_and_finish
- write_archive_and_finish
- create_standalone
- save_annotations
- map_item_method_available
- get_mapped_item
- is_filter
- get_options
- get_status
- is_top_dataset
- is_from_collector
- get_extension
- is_rankable
- exclude_followup_processors
- is_4cat_processor