kesma

filter_user_db.py

Dec 17th, 2024
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 6.68 KB | None | 0 0
  1. import json
  2. import re
  3. import logging
  4. import os
  5.  
  6. # Configure logging
  7. logging.basicConfig(
  8. level=logging.INFO,
  9. format='%(asctime)s [%(levelname)s] %(message)s',
  10. handlers=[
  11. logging.StreamHandler()
  12. ]
  13. )
  14.  
  15. # Path to your user database JSON file
  16. USER_DATABASE_FILE = 'user_database.json'
  17.  
  18. # Path to the output file for filtered users
  19. FILTERED_USERS_FILE = 'filtered_users.json'
  20.  
  21. # First category keywords (Roles)
  22. FIRST_CATEGORY_KEYWORDS = [
  23.  
  24. ]
  25. # TO DO , 'professor', 'lecturer', 'researcher', 'scientist', 'phd', 'dr\.', 'doctor',
  26. # 'postdoc', 'post-doctoral', 'associate professor', 'assistant professor', 'science communicator', 'reporter', 'journalist'
  27.  
  28.  
  29. # Second category keywords (Fields and Related Terms)
  30. SECOND_CATEGORY_KEYWORDS= [
  31. # 'climatologist', 'meteorologist', 'ecologist', 'biologist', 'physicist',
  32. # 'chemist', 'geologist', 'oceanographer', 'environmentalist', 'sociologist',
  33. # 'anthropologist', 'economist', 'policy analyst',
  34. # 'statistician', 'conservationist', 'environmental scientist',
  35. # 'climate scientist', 'sustainability expert',
  36. # 'climate', 'global warming', 'sustainability', 'renewable energy',
  37. # 'biodiversity', 'ecosystem', 'environment', 'conservation',
  38. # 'sustainable development', 'carbon footprint', 'greenhouse gases',
  39. # 'climate change', 'environmental policy', 'ecology', 'environmental science',
  40. # 'environmental studies'
  41. ]
  42.  
  43. # Excluded phrases (Profiles containing these phrases will be excluded)
  44. EXCLUDED_PHRASES = [
  45. 'researcher', 'scientist', 'professor', 'phd', 'dr.', 'postdoc', 'ph.d.' 'dr',
  46. 'teaching associate', 'fellow', 'lecturer', 'prof.', 'science communicator'
  47. ]
  48.  
  49. # TO DO , , 'researcher', 'reporter', 'journalist'
  50.  
  51. # Function to compile regex patterns for single-word keywords
  52. def compile_single_word_pattern(keywords):
  53. # Escape keywords to handle any special regex characters
  54. escaped_keywords = [re.escape(keyword) for keyword in keywords]
  55. # Add optional 's' or 'es' for plural forms
  56. pattern = r'\b(' + '|'.join(escaped_keywords) + r')(?:s|es)?\b'
  57. return re.compile(pattern, re.IGNORECASE)
  58.  
  59. # Function to compile regex patterns for multi-word phrases
  60. def compile_multi_word_pattern(phrases):
  61. # Escape phrases to handle any special regex characters
  62. escaped_phrases = [re.escape(phrase) for phrase in phrases]
  63. # Join phrases without word boundaries
  64. pattern = r'(' + '|'.join(escaped_phrases) + r')'
  65. return re.compile(pattern, re.IGNORECASE)
  66.  
  67. # Separate single-word keywords and multi-word phrases
  68. def separate_keywords(keywords):
  69. single_word_keywords = []
  70. multi_word_phrases = []
  71. for keyword in keywords:
  72. if ' ' in keyword or '-' in keyword or '.' in keyword or '\\' in keyword:
  73. multi_word_phrases.append(keyword)
  74. else:
  75. single_word_keywords.append(keyword)
  76. return single_word_keywords, multi_word_phrases
  77.  
  78. # Separate first category keywords
  79. first_single_words, first_multi_words = separate_keywords(FIRST_CATEGORY_KEYWORDS)
  80. # Separate second category keywords
  81. second_single_words, second_multi_words = separate_keywords(SECOND_CATEGORY_KEYWORDS)
  82.  
  83. # Compile patterns
  84. first_single_word_pattern = compile_single_word_pattern(first_single_words)
  85. first_multi_word_pattern = compile_multi_word_pattern(first_multi_words)
  86. second_single_word_pattern = compile_single_word_pattern(second_single_words)
  87. second_multi_word_pattern = compile_multi_word_pattern(second_multi_words)
  88. excluded_phrase_pattern = compile_multi_word_pattern(EXCLUDED_PHRASES)
  89.  
  90. def filter_profiles():
  91. try:
  92. # Check if the user database file exists
  93. if not os.path.exists(USER_DATABASE_FILE):
  94. logging.error(f"The file {USER_DATABASE_FILE} does not exist.")
  95. return
  96.  
  97. # Load the user database
  98. with open(USER_DATABASE_FILE, 'r', encoding='utf-8') as f:
  99. user_database = json.load(f)
  100.  
  101. # Ensure that the user_database is a list
  102. if not isinstance(user_database, list):
  103. logging.error(f"The file {USER_DATABASE_FILE} should contain a JSON array of user profiles.")
  104. return
  105.  
  106. logging.info(f'Loaded {len(user_database)} user profiles from {USER_DATABASE_FILE}')
  107.  
  108. filtered_users = []
  109.  
  110. # Iterate over each user profile
  111. for idx, user in enumerate(user_database, start=1):
  112. subject = user.get('subject', user) # Adjusted to handle different data structures
  113. display_name = subject.get('displayName', '')
  114. description = subject.get('description', '')
  115. combined_text = f'{display_name} {description}'
  116.  
  117. # Check for excluded phrases first
  118. if excluded_phrase_pattern.search(combined_text):
  119. continue # Skip this profile
  120.  
  121. # First category matching
  122. first_match = (
  123. first_single_word_pattern.search(combined_text) or
  124. first_multi_word_pattern.search(combined_text)
  125. )
  126.  
  127. # Second category matching
  128. second_match = (
  129. second_single_word_pattern.search(combined_text) or
  130. second_multi_word_pattern.search(combined_text)
  131. )
  132.  
  133. if first_match and second_match:
  134. # Extract only desired fields
  135. filtered_user = {
  136. 'uri': user.get('uri', ''),
  137. 'subject': {
  138. 'did': subject.get('did', ''),
  139. 'handle': subject.get('handle', ''),
  140. 'displayName': display_name,
  141. 'avatar': subject.get('avatar', ''),
  142. 'description': description,
  143. 'createdAt': subject.get('createdAt', ''),
  144. 'indexedAt': subject.get('indexedAt', '')
  145. }
  146. }
  147. filtered_users.append(filtered_user)
  148.  
  149. # Optional: Log progress every 100 profiles
  150. if idx % 100 == 0:
  151. logging.info(f'Processed {idx} profiles...')
  152.  
  153. logging.info(f'Found {len(filtered_users)} matching profiles.')
  154.  
  155. # Save the filtered users to a new JSON file
  156. with open(FILTERED_USERS_FILE, 'w', encoding='utf-8') as f:
  157. json.dump(filtered_users, f, ensure_ascii=False, indent=4)
  158. logging.info(f'Saved filtered profiles to {FILTERED_USERS_FILE}')
  159.  
  160. except json.JSONDecodeError as jde:
  161. logging.error(f'JSON decoding error: {jde}')
  162. except Exception as e:
  163. logging.error(f'An unexpected error occurred: {e}')
  164.  
  165. if __name__ == '__main__':
  166. filter_profiles()
Advertisement
Add Comment
Please, Sign In to add comment