added orgminer pipeline to backkground jobs
This commit is contained in:
@@ -16,3 +16,8 @@ service/scripts/multipliers
|
||||
**/.env
|
||||
**/.env.*
|
||||
**/out
|
||||
.git
|
||||
|
||||
# Ignore the LLM cache, which can be large and is not needed in the job image.
|
||||
**/.llm_cache
|
||||
service/scripts/jobs-image/orgminer_pipeline/
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import warcio
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import json
|
||||
import argparse
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
|
||||
from pipeline_utils import load_config, get_entity, out_path, add_common_args
|
||||
|
||||
redirect_lookup = {}
|
||||
|
||||
|
||||
def process_file(filename):
|
||||
print("Searching file", filename)
|
||||
with open(filename, 'rb') as stream:
|
||||
for record in warcio.ArchiveIterator(stream):
|
||||
if record.rec_type == 'response':
|
||||
status = int(record.http_headers.get_statuscode())
|
||||
# get all redirected responses
|
||||
if 300 <= status < 400:
|
||||
location = record.http_headers.get_header('Location')
|
||||
uri = record.rec_headers.get_header('WARC-Target-URI')
|
||||
if location:
|
||||
print(location)
|
||||
redirect_lookup.setdefault(location, []).append(uri)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description="Build a redirection lookup table from WARC files.")
|
||||
parser.add_argument("warc_dir", help="Directory containing WARC files to scan")
|
||||
add_common_args(parser)
|
||||
args = parser.parse_args()
|
||||
|
||||
config = load_config(args.config)
|
||||
get_entity(config, args.entity) # validates the entity exists, fails fast otherwise
|
||||
output_file = out_path(config, args.entity, "redirections_file")
|
||||
|
||||
print(f"Building redirection lookup from the WARC files for entity '{args.entity}'")
|
||||
start_time = time.time()
|
||||
|
||||
for directory, subdirectories, files in os.walk(args.warc_dir):
|
||||
for file in files:
|
||||
full_file_dir = os.path.join(directory, file)
|
||||
print("+++++++DIR: ", full_file_dir)
|
||||
process_file(full_file_dir)
|
||||
|
||||
os.makedirs(os.path.dirname(output_file), exist_ok=True)
|
||||
with open(output_file, 'w') as rl:
|
||||
json.dump(redirect_lookup, rl)
|
||||
print(redirect_lookup)
|
||||
|
||||
runtime_hours = (time.time() - start_time) / 3600
|
||||
print(f"Runtime: {runtime_hours:.2f} hours")
|
||||
print(f"Created redirection lookup file: {output_file}")
|
||||
@@ -0,0 +1,239 @@
|
||||
import warcio
|
||||
import sys
|
||||
import langdetect
|
||||
import trafilatura
|
||||
import os
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import datetime
|
||||
import html
|
||||
import argparse
|
||||
import yake
|
||||
import tldextract
|
||||
from urllib.parse import urlparse
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
|
||||
from pipeline_utils import load_config, get_entity, entity_input_path, out_path, get_es_client, add_common_args
|
||||
|
||||
date_time = datetime.datetime.now()
|
||||
unix_timestamp = round(time.mktime(date_time.timetuple()))
|
||||
|
||||
|
||||
def check_elastic_status():
|
||||
if not es.ping():
|
||||
print("Elasticsearch connection not found")
|
||||
return False
|
||||
|
||||
settings = {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"customanalyzer": {
|
||||
"type": "custom",
|
||||
"tokenizer": "standard",
|
||||
"filter": ["lowercase", "asciifolding"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mappings = {
|
||||
"properties": {
|
||||
"uri": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
|
||||
"scheme": {"type": "keyword"},
|
||||
"domain": {"type": "keyword"},
|
||||
"subdomain": {"type": "keyword"},
|
||||
"path": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
|
||||
"query": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
|
||||
"hostname": {"type": "keyword"},
|
||||
"body": {
|
||||
"type": "text",
|
||||
"analyzer": "customanalyzer",
|
||||
"search_analyzer": "customanalyzer"
|
||||
},
|
||||
"lang": {"type": "keyword"},
|
||||
"tags": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"value": {"type": "keyword"},
|
||||
"score": {"type": "double"}
|
||||
}
|
||||
},
|
||||
"redirected_by": {"type": "keyword"},
|
||||
"timestamp_created": {"type": "date", "format": "epoch_second"},
|
||||
"timestamp_updated": {"type": "date", "format": "epoch_second"}
|
||||
}
|
||||
}
|
||||
try:
|
||||
if not es.indices.exists(index=index_name):
|
||||
es.indices.create(index=index_name, mappings=mappings, settings=settings)
|
||||
print(f"INDEX {index_name} created...")
|
||||
else:
|
||||
print(f"INDEX {index_name} already exists...")
|
||||
|
||||
except Exception as e:
|
||||
print("failed to create index mapping")
|
||||
print(e)
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def process_file(filename, uploaded_so_far, limit=None):
|
||||
"""Process one WARC file. Stops as soon as `limit` total uploads (across
|
||||
all files, tracked via uploaded_so_far) have succeeded, if a limit is set."""
|
||||
print("Searching file", filename)
|
||||
records = 0
|
||||
successes = 0
|
||||
with open(filename, 'rb') as stream:
|
||||
for record in warcio.ArchiveIterator(stream):
|
||||
if limit is not None and uploaded_so_far + successes >= limit:
|
||||
print(f"Reached upload limit of {limit}. Stopping.")
|
||||
break
|
||||
|
||||
if record.rec_type == 'response':
|
||||
records += 1
|
||||
status = int(record.http_headers.get_statuscode())
|
||||
# Handle 300,600-level statuses
|
||||
if 300 <= status < 600:
|
||||
print(f"Invalid Status ({status}) of the page. Skipped.")
|
||||
continue # Skip further processing of redirected content
|
||||
content_type = record.http_headers.get_header('Content-Type')
|
||||
if not bool(content_type):
|
||||
continue
|
||||
if 'text/html' in content_type.lower():
|
||||
tokens = content_type.split(";")
|
||||
encoding = "iso-8859-1"
|
||||
for token in tokens:
|
||||
trimmed = token.strip()
|
||||
if trimmed.startswith("charset="):
|
||||
encoding = trimmed[8:].lower()
|
||||
|
||||
try:
|
||||
decoded = record.content_stream().read().decode(encoding)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
text = trafilatura.extract(decoded, output_format="txt")
|
||||
try:
|
||||
lang = langdetect.detect(text)
|
||||
except Exception:
|
||||
lang = ''
|
||||
try:
|
||||
title = html.unescape(re.search(r"<title>(.*?)<\/title>", decoded).group(1))
|
||||
except Exception:
|
||||
title = ''
|
||||
keywords = []
|
||||
if lang == "de":
|
||||
keyword_extractor = yake.KeywordExtractor(dedupFunc="seqm", dedupLim=0.9, top=15, lan="de")
|
||||
yake_keywords = keyword_extractor.extract_keywords(text)
|
||||
else:
|
||||
keyword_extractor = yake.KeywordExtractor(dedupFunc="seqm", dedupLim=0.9, top=15, lan="en")
|
||||
yake_keywords = keyword_extractor.extract_keywords(text)
|
||||
keywords = [{'value': x[0], 'score': x[1]} for x in yake_keywords]
|
||||
if lang == "en" or lang == 'de':
|
||||
print("#######################################")
|
||||
|
||||
lower = text.lower()
|
||||
uri = record.rec_headers.get_header('WARC-Target-URI')
|
||||
|
||||
extracted = tldextract.extract(uri)
|
||||
subdomain = extracted.subdomain.replace('www', '')
|
||||
domain = extracted.domain
|
||||
|
||||
parsed = urlparse(uri)
|
||||
scheme = parsed.scheme
|
||||
path = parsed.path
|
||||
query = parsed.query
|
||||
hostname = parsed.hostname
|
||||
|
||||
lower = lower.replace('\r', '')
|
||||
lower = lower.rstrip()
|
||||
|
||||
print("persisting...")
|
||||
|
||||
element = {}
|
||||
element['uri'] = uri
|
||||
element['scheme'] = scheme
|
||||
element['host'] = hostname
|
||||
element['subdomain'] = subdomain
|
||||
element['domain'] = domain
|
||||
element['path'] = path
|
||||
element['query'] = query
|
||||
element['title'] = title
|
||||
element['body'] = lower
|
||||
element['lang'] = lang
|
||||
element['keywords'] = keywords
|
||||
element['timestamp_created'] = unix_timestamp
|
||||
element['timestamp_updated'] = -1
|
||||
element['redirected_by'] = []
|
||||
|
||||
if uri in redirections:
|
||||
element['redirected_by'] = redirections[uri]
|
||||
|
||||
json_obj = json.dumps(element)
|
||||
try:
|
||||
es.index(index=index_name, body=json_obj)
|
||||
successes += 1
|
||||
except Exception as e:
|
||||
print("upload failed....")
|
||||
print(e)
|
||||
continue
|
||||
|
||||
else:
|
||||
print(content_type)
|
||||
print(record.content_stream().read())
|
||||
print('')
|
||||
return successes, records
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description="Upload extracted WARC page content to Elasticsearch.")
|
||||
parser.add_argument("warc_dir", help="Directory containing WARC files to scan")
|
||||
parser.add_argument("redirections_file", nargs="?", default=None,
|
||||
help="Override path to redirections_lookup.json (default: this entity's run output)")
|
||||
add_common_args(parser)
|
||||
parser.add_argument("--limit", type=int, default=None,
|
||||
help="Only upload the first N successfully processed entries, then stop "
|
||||
"(useful for a quick smoke test before running the full crawl upload)")
|
||||
args = parser.parse_args()
|
||||
|
||||
print("Starting WARC file processing and upload to Elasticsearch")
|
||||
start_time = time.time()
|
||||
|
||||
config = load_config(args.config)
|
||||
entity = get_entity(config, args.entity)
|
||||
|
||||
es = get_es_client(config)
|
||||
index_name = entity["elasticsearch"]["raw_index"]
|
||||
|
||||
redirections_file = args.redirections_file or out_path(config, args.entity, "redirections_file")
|
||||
|
||||
if check_elastic_status():
|
||||
with open(redirections_file, 'r') as reds:
|
||||
redirections = json.load(reds)
|
||||
|
||||
total_records = 0
|
||||
total_successes = 0
|
||||
limit_hit = False
|
||||
|
||||
for directory, subdirectories, files in os.walk(args.warc_dir):
|
||||
if limit_hit:
|
||||
break
|
||||
for file in files:
|
||||
if args.limit is not None and total_successes >= args.limit:
|
||||
limit_hit = True
|
||||
break
|
||||
|
||||
full_file_dir = os.path.join(directory, file)
|
||||
print("+++++++DIR: ", full_file_dir)
|
||||
successes, records = process_file(full_file_dir, uploaded_so_far=total_successes, limit=args.limit)
|
||||
total_successes += successes
|
||||
total_records += records
|
||||
|
||||
print(f"Total successes: {total_successes} of {total_records}")
|
||||
if args.limit is not None:
|
||||
print(f"(Upload was capped at --limit {args.limit})")
|
||||
|
||||
runtime_hours = (time.time() - start_time) / 3600
|
||||
print(f"Runtime: {runtime_hours:.2f} hours")
|
||||
print("Finished processing WARC files and uploading to Elasticsearch")
|
||||
@@ -0,0 +1,178 @@
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import argparse
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
|
||||
from pipeline_utils import load_config, get_entity, entity_input_path, out_path, add_common_args
|
||||
|
||||
|
||||
def goDeep(d, faculty_de, faculty_en):
|
||||
res = {"faculty_de": faculty_de,
|
||||
"faculty_en": faculty_en}
|
||||
|
||||
for key, value in d.items():
|
||||
# Handle name/link keys
|
||||
if isinstance(value, str) and "aggregator" not in key:
|
||||
key_without_lang = key[0:-3]
|
||||
if "de" in key:
|
||||
res[key] = value if value != "None" else d.get(key_without_lang + "_en")
|
||||
elif "en" in key:
|
||||
res[key] = value if value != "None" else d.get(key_without_lang + "_de")
|
||||
else:
|
||||
res[key] = value if value else ""
|
||||
|
||||
if "link" in key:
|
||||
res[key] = clean_uri(res[key])
|
||||
|
||||
# Handle children lists
|
||||
elif isinstance(value, list) and "aggregator" not in key:
|
||||
children = []
|
||||
existing_names = set()
|
||||
for subdict in value:
|
||||
subdict['type'] = "leaf"
|
||||
child_res = goDeep(subdict, faculty_en=faculty_en, faculty_de=faculty_de)
|
||||
if child_res is not None:
|
||||
# only unique names must appear in hierarchy
|
||||
current_name_de = child_res.get('name_de')
|
||||
current_name_en = child_res.get('name_en')
|
||||
if current_name_en not in existing_names and current_name_de not in existing_names:
|
||||
existing_names.add(current_name_en)
|
||||
existing_names.add(current_name_de)
|
||||
children.append(child_res)
|
||||
children.sort(key=lambda child: child.get("name_de", "").lower())
|
||||
if children:
|
||||
child_node = {
|
||||
"name_de": "Lehrstühle" if "chairs" in key else "Instituten",
|
||||
"name_en": "Chairs" if "chairs" in key else "Institutes",
|
||||
"color": "#FF5733" if "chairs" in key else "#3388FF",
|
||||
'type': "chairs" if "chairs" in key else "institutes",
|
||||
"children": children,
|
||||
"value": len(children),
|
||||
"faculty_en": faculty_en,
|
||||
"faculty_de": faculty_de
|
||||
}
|
||||
res.setdefault('children', []).append(child_node)
|
||||
res['value'] = sum([d['value'] for d in res['children']])
|
||||
|
||||
elif "aggregator" in key:
|
||||
res[key] = value
|
||||
|
||||
# Fallback defaults
|
||||
if 'type' not in res:
|
||||
res['type'] = "faculty"
|
||||
if 'color' not in res:
|
||||
res['color'] = "green"
|
||||
|
||||
# Validity check
|
||||
name_de = res.get('name_de')
|
||||
name_en = res.get('name_en')
|
||||
link_de = res.get('link_de')
|
||||
link_en = res.get('link_en')
|
||||
|
||||
if not (isValid(name_de) and isValid(name_en)) or not (isValid(link_de) and isValid(link_en)):
|
||||
return None
|
||||
|
||||
# Add links for analysis
|
||||
if res.get('type') == 'leaf':
|
||||
if 'children' in res:
|
||||
d = {'link': res['link_de'], 'children': []}
|
||||
for aggr in res['children']:
|
||||
for child in aggr['children']:
|
||||
d['children'].append({'link': child['link_de']})
|
||||
uniqueLinks.add(child['link_de'])
|
||||
parent_leafs.append(d)
|
||||
elif res['link_de'] not in uniqueLinks:
|
||||
child_leafs.append({'link': res['link_de']})
|
||||
uniqueLinks.add(res['link_de'])
|
||||
|
||||
return res
|
||||
|
||||
|
||||
def isValid(key):
|
||||
return not (key is None or (isinstance(key, str) and key.strip().lower() == 'none'))
|
||||
|
||||
|
||||
def writeToFile(data, filename):
|
||||
os.makedirs(os.path.dirname(filename), exist_ok=True)
|
||||
with open(filename, 'w', encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False)
|
||||
|
||||
|
||||
def clean_uri(uri):
|
||||
parts = uri.rstrip('/').split('/')
|
||||
if 'index' in parts[-1]:
|
||||
parts = parts[:-1]
|
||||
new_uri = '/'.join(parts)
|
||||
|
||||
return new_uri[:-1] if new_uri.endswith('/') else new_uri
|
||||
|
||||
|
||||
def filter_parents(parents, problem_orgs):
|
||||
if problem_orgs:
|
||||
for parent in parents:
|
||||
if parent['link'] in problem_orgs:
|
||||
parent['link'] = problem_orgs[parent['link']]
|
||||
for child in parent['children']:
|
||||
if child['link'] in problem_orgs:
|
||||
child['link'] = problem_orgs[child['link']]
|
||||
return parents
|
||||
|
||||
|
||||
def filter_children(children, problem_orgs):
|
||||
if problem_orgs:
|
||||
for child in children:
|
||||
if child['link'] in problem_orgs:
|
||||
child['link'] = problem_orgs[child['link']]
|
||||
return children
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description="Create organization hierarchy from an entity's ground-truth JSON.")
|
||||
add_common_args(parser)
|
||||
parser.add_argument("--ground-truth", default=None,
|
||||
help="Override the ground_truth_file configured for this entity")
|
||||
parser.add_argument("--problem-orgs", default=None,
|
||||
help="Override the problem_orgs_file configured for this entity")
|
||||
args = parser.parse_args()
|
||||
|
||||
config = load_config(args.config)
|
||||
entity = get_entity(config, args.entity)
|
||||
|
||||
print(f"Starting to create hierarchy for entity '{args.entity}'")
|
||||
|
||||
path_to_truth = args.ground_truth or entity_input_path(config, args.entity, "ground_truth_file")
|
||||
path_to_problem_orgs = args.problem_orgs or (
|
||||
entity_input_path(config, args.entity, "problem_orgs_file") if entity.get("problem_orgs_file") else None
|
||||
)
|
||||
|
||||
problem_orgs = None
|
||||
if path_to_problem_orgs:
|
||||
try:
|
||||
with open(path_to_problem_orgs, encoding="utf-8") as file:
|
||||
problem_orgs = json.load(file)
|
||||
except Exception:
|
||||
print(f'Could not open the problem_orgs file at {path_to_problem_orgs}.')
|
||||
|
||||
with open(path_to_truth, encoding="utf-8") as json_file:
|
||||
hierarchy = json.load(json_file)
|
||||
|
||||
parent_leafs = []
|
||||
child_leafs = []
|
||||
filtered_tree = []
|
||||
uniqueLinks = set()
|
||||
for faculty in hierarchy['faculties']:
|
||||
filtered_tree.append(goDeep(faculty, faculty_de=faculty.get('name_de'), faculty_en=faculty.get('name_en')))
|
||||
|
||||
linksToAnalyze = {
|
||||
'parent_leafs': filter_parents(parent_leafs, problem_orgs=problem_orgs),
|
||||
'child_leafs': filter_children(child_leafs, problem_orgs=problem_orgs),
|
||||
}
|
||||
|
||||
links_to_analyze_file = out_path(config, args.entity, 'links_to_analyze_file')
|
||||
hierarchy_file = out_path(config, args.entity, 'hierarchy_file')
|
||||
|
||||
writeToFile(linksToAnalyze, links_to_analyze_file)
|
||||
writeToFile(filtered_tree, hierarchy_file)
|
||||
print(f"Finished creating {hierarchy_file} and {links_to_analyze_file}")
|
||||
print("Number of unique links to analyze:", len(uniqueLinks))
|
||||
@@ -0,0 +1,531 @@
|
||||
import json
|
||||
import sys
|
||||
import os
|
||||
import time
|
||||
import traceback
|
||||
import re
|
||||
import hashlib
|
||||
import argparse
|
||||
from enum import Enum
|
||||
from json import JSONDecodeError
|
||||
from elasticsearch import helpers
|
||||
from urllib.parse import urlparse
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
|
||||
from pipeline_utils import load_config, get_entity, entity_input_path, out_path, get_es_client, get_llm_client, add_common_args
|
||||
from pydantic import BaseModel
|
||||
|
||||
uniqueUrls = {}
|
||||
total_urls = 0
|
||||
total_updates = 0
|
||||
failures = 0
|
||||
|
||||
|
||||
def make_id_from_url(url):
|
||||
return hashlib.sha256(url.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def getParentsChildrenUrlCount(parents, children):
|
||||
print('Counting total url number...\n')
|
||||
url_counter = 0
|
||||
for i, parent in enumerate(parents):
|
||||
for child in parent['children']:
|
||||
child['sublinks'] = getSubLinks(child['link'])
|
||||
url_counter += len(child['sublinks'])
|
||||
|
||||
for i, child in enumerate(children):
|
||||
child['sublinks'] = getSubLinks(child['link'])
|
||||
url_counter += len(child['sublinks'])
|
||||
print(f'Total URLs: {url_counter}')
|
||||
return parents, children, url_counter
|
||||
|
||||
|
||||
def clean_uri(uri):
|
||||
parts = uri.rstrip('/').split('/')
|
||||
if 'index' in parts[-1]:
|
||||
parts = parts[:-1]
|
||||
new_uri = '/'.join(parts).replace(" ", "")
|
||||
|
||||
return new_uri[:-1] if new_uri.endswith('/') else new_uri
|
||||
|
||||
|
||||
def get_direct_links(link):
|
||||
body = {
|
||||
"size": 10000,
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"uri": link}}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
},
|
||||
"collapse": {
|
||||
"field": "uri.keyword"
|
||||
}
|
||||
}
|
||||
|
||||
result = es.search(index=raw_index, body=body)['hits']['hits']
|
||||
result = add_sources(result, link)
|
||||
print(f'Found {len(result)} by direct search.')
|
||||
return result
|
||||
|
||||
|
||||
def get_links_from_redirects(link):
|
||||
total_result = []
|
||||
link2 = link[:-1] if link.endswith('/') else link + '/'
|
||||
body = {
|
||||
"size": 10000,
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"redirected_by": link}},
|
||||
{"match_phrase": {"redirected_by": link2}}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
},
|
||||
"collapse": {
|
||||
"field": "uri.keyword"
|
||||
}
|
||||
}
|
||||
|
||||
result = es.search(index=raw_index, body=body)['hits']['hits']
|
||||
redirects = [r['_source']['uri'] for r in result]
|
||||
|
||||
# get corresponded sublinks from redirections
|
||||
if len(redirects) > 0:
|
||||
for url in redirects:
|
||||
print(link + '->' + url)
|
||||
body = {
|
||||
"size": 10000,
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"uri": url}}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
},
|
||||
"collapse": {
|
||||
"field": "uri.keyword"
|
||||
}
|
||||
}
|
||||
result = es.search(index=raw_index, body=body)['hits']['hits']
|
||||
total_result += add_sources(result, url)
|
||||
print(f'Found {len(total_result)} from redirects.')
|
||||
return total_result
|
||||
|
||||
|
||||
def get_links_by_hostname(link, hostname):
|
||||
parsed = urlparse(link)
|
||||
scheme = parsed.scheme
|
||||
body = {
|
||||
"size": 10000,
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match_phrase": {"uri": scheme + "://" + hostname}}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
},
|
||||
"collapse": {
|
||||
"field": "uri.keyword"
|
||||
}
|
||||
}
|
||||
|
||||
result = es.search(index=raw_index, body=body)['hits']['hits']
|
||||
result = add_sources(result, scheme + "://" + hostname)
|
||||
print(f'Found {len(result)} by hostname search.')
|
||||
return result
|
||||
|
||||
|
||||
def toggle_www(url):
|
||||
scheme_match = re.match(r'^(https?://)', url, re.IGNORECASE)
|
||||
|
||||
if scheme_match:
|
||||
scheme = scheme_match.group(0)
|
||||
rest_of_url = url[len(scheme):]
|
||||
else:
|
||||
if url.startswith("www."):
|
||||
return "http://" + url
|
||||
return "http://www." + url
|
||||
|
||||
if rest_of_url.startswith("www."):
|
||||
return scheme + rest_of_url[4:]
|
||||
else:
|
||||
return scheme + "www." + rest_of_url
|
||||
|
||||
|
||||
def getSubLinks(link):
|
||||
updated_sublinks = [] # only collect new/changed docs in this call
|
||||
total_results = []
|
||||
total_toggle_results = []
|
||||
|
||||
parsed = urlparse(link)
|
||||
hostname = parsed.hostname
|
||||
print('\n' + '[ORIGINAL] Working on ' + link + '\n')
|
||||
total_results += get_direct_links(link)
|
||||
|
||||
if hostname not in BANNED_HOSTNAMES:
|
||||
total_results += get_links_by_hostname(link, hostname)
|
||||
|
||||
total_results += get_links_from_redirects(link)
|
||||
|
||||
total_results = add_sources(total_results, link)
|
||||
|
||||
# TOGGLED links
|
||||
toggled_link = toggle_www(link)
|
||||
toggle_parsed = urlparse(toggled_link)
|
||||
toggle_hostname = toggle_parsed.hostname
|
||||
print('\n' + '[TOGGLED] Working on ' + toggled_link + '\n')
|
||||
total_results += get_direct_links(toggled_link)
|
||||
|
||||
if toggle_hostname not in BANNED_HOSTNAMES:
|
||||
total_toggle_results += get_links_by_hostname(toggled_link, toggle_hostname)
|
||||
|
||||
total_toggle_results += get_links_from_redirects(toggled_link)
|
||||
total_toggle_results = add_sources(total_toggle_results, toggled_link)
|
||||
|
||||
# Merge into global dict but only return changed ones
|
||||
for hit in (total_results + total_toggle_results):
|
||||
hit['_source']['uri'] = clean_uri(hit['_source']['uri'])
|
||||
uri = hit['_source']['uri']
|
||||
|
||||
if uri not in uniqueUrls:
|
||||
uniqueUrls[uri] = hit['_source']
|
||||
updated_sublinks.append(uniqueUrls[uri]) # NEW urls
|
||||
else:
|
||||
existing = uniqueUrls[uri]
|
||||
new_sources = hit['_source'].get('sources', [])
|
||||
added = False
|
||||
for src in new_sources:
|
||||
if src not in existing['sources']:
|
||||
existing['sources'].append(src)
|
||||
added = True
|
||||
if added:
|
||||
updated_sublinks.append(existing) # UPDATED
|
||||
|
||||
return updated_sublinks
|
||||
|
||||
|
||||
def add_sources(chunk, url):
|
||||
for page in chunk:
|
||||
if 'sources' not in page['_source']:
|
||||
page['_source']['sources'] = []
|
||||
if url not in page['_source']['sources']:
|
||||
page['_source']['sources'].append(url)
|
||||
if problem_orgs: # add missing sources from problem_orgs.json
|
||||
for key, value in problem_orgs.items():
|
||||
if value == url:
|
||||
if key not in page['_source']['sources']:
|
||||
page['_source']['sources'].append(key)
|
||||
|
||||
return chunk
|
||||
|
||||
|
||||
def check_elastic_status(index_name):
|
||||
if not es.ping():
|
||||
print("Elasticsearch connection not found")
|
||||
return False
|
||||
|
||||
settings = {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"customanalyzer": {
|
||||
"type": "custom",
|
||||
"tokenizer": "standard",
|
||||
"filter": [
|
||||
"lowercase",
|
||||
"asciifolding"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mappings = {
|
||||
"properties": {
|
||||
"uri": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {"type": "keyword"}
|
||||
}
|
||||
},
|
||||
"domain": {"type": "keyword"},
|
||||
"subdomain": {"type": "keyword"},
|
||||
"path": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {"type": "keyword"}
|
||||
}
|
||||
},
|
||||
"query": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {"type": "keyword"}
|
||||
}
|
||||
},
|
||||
"host": {"type": "keyword"},
|
||||
"category": {
|
||||
"type": "keyword",
|
||||
"null_value": "NULL"
|
||||
},
|
||||
"body": {
|
||||
"type": "text",
|
||||
"analyzer": "customanalyzer",
|
||||
"search_analyzer": "customanalyzer"
|
||||
},
|
||||
"lang": {"type": "keyword"},
|
||||
"tags": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"value": {"type": "keyword"},
|
||||
"score": {"type": "double"}
|
||||
}
|
||||
},
|
||||
"sources": {"type": "keyword"},
|
||||
"timestamp_created": {
|
||||
"type": "date",
|
||||
"format": "epoch_second"
|
||||
},
|
||||
"timestamp_updated": {
|
||||
"type": "date",
|
||||
"format": "epoch_second"
|
||||
}
|
||||
}
|
||||
}
|
||||
try:
|
||||
if not es.indices.exists(index=index_name):
|
||||
es.indices.create(index=index_name, mappings=mappings, settings=settings)
|
||||
print(f"INDEX {index_name} created...")
|
||||
else:
|
||||
print(f"INDEX {index_name} already exists...")
|
||||
|
||||
except Exception as e:
|
||||
print("failed to create index mapping")
|
||||
print(e)
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def getCleanUri(uri):
|
||||
pos = uri.find('?')
|
||||
return uri[:pos] if pos > 0 else uri
|
||||
|
||||
|
||||
def startCategorizing(links_array, index_name, max_rate=30, max_retries=5):
|
||||
print(f"Starting to categorize {len(links_array)} urls with max_rate={max_rate} and max_retries={max_retries}")
|
||||
success_counter = 0
|
||||
fail_counter = 0
|
||||
response_schema = {
|
||||
"name": "classified_url",
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"category": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Teaching",
|
||||
"Research",
|
||||
"Projects",
|
||||
"Staff",
|
||||
"News",
|
||||
"Other",
|
||||
],
|
||||
}
|
||||
},
|
||||
"required": ["category"],
|
||||
"additionalProperties": False,
|
||||
},
|
||||
}
|
||||
|
||||
prompt = ("You are a URL classifier for university-related URLs."
|
||||
f"The allowed categories are: {', '.join(CATEGORIES)}. "
|
||||
"You will receive a URL. Respond ONLY with a valid JSON object, which contains "
|
||||
'assigned category to the URL in this exact format: {"category": CATEGORY}. '
|
||||
"Do not include any other text. Use only the provided categories. "
|
||||
"Important:1) The URL must be assigned to a category. "
|
||||
'2) If you are not sure enough if the category is right, assign the URL to "Other" category')
|
||||
|
||||
for i in range(0, len(links_array), max_rate):
|
||||
chunk = links_array[i:i + max_rate]
|
||||
|
||||
chunk_to_feed = []
|
||||
chunk_to_skip = []
|
||||
for link in chunk:
|
||||
clean = getCleanUri(link['uri'])
|
||||
if clean in categorizedUrls:
|
||||
link['category'] = categorizedUrls[clean]
|
||||
chunk_to_skip.append(link)
|
||||
else:
|
||||
chunk_to_feed.append(link)
|
||||
|
||||
print(f'Number of NEW urls:{len(chunk_to_feed)}\nNumber of already categorized urls: {len(chunk_to_skip)}')
|
||||
|
||||
if chunk_to_feed:
|
||||
for link in chunk_to_feed:
|
||||
tries = 0
|
||||
while True:
|
||||
if tries > max_retries:
|
||||
print(f"Couldnt categorize URL: {link['uri']} ... Skipping it...")
|
||||
break
|
||||
try:
|
||||
messages = [
|
||||
{"role": "system", "content": prompt},
|
||||
{"role": "user", "content": link['uri']}
|
||||
]
|
||||
|
||||
chat_completion = llm_client.chat.completions.create(
|
||||
messages=messages,
|
||||
model=MODEL_NAME,
|
||||
response_format={
|
||||
"type": "json_schema",
|
||||
"json_schema": response_schema,
|
||||
},
|
||||
)
|
||||
content = chat_completion.choices[0].message.content
|
||||
print(f"Response from LLM: {content}")
|
||||
|
||||
try:
|
||||
category_obj = json.loads(content)
|
||||
except JSONDecodeError:
|
||||
print("Invalid JSON format. Retrying...")
|
||||
time.sleep(1)
|
||||
continue
|
||||
category = category_obj.get('category')
|
||||
if category and category in CATEGORIES:
|
||||
link['category'] = category
|
||||
clean = getCleanUri(link['uri'])
|
||||
categorizedUrls[clean] = link['category']
|
||||
else:
|
||||
print(f"Invalid category... Retrying... {content, link['uri']}")
|
||||
tries += 1
|
||||
time.sleep(1)
|
||||
continue
|
||||
|
||||
break # break on success
|
||||
except Exception:
|
||||
print(f"Exception occurred: {traceback.format_exc()}. Retrying...")
|
||||
time.sleep(1)
|
||||
for link in (chunk_to_skip + chunk_to_feed):
|
||||
print(f"Uploading {link['uri']} with category: {link.get('category')} ")
|
||||
try:
|
||||
chunk_to_upload = [
|
||||
{"_index": index_name, "_id": make_id_from_url(link['uri']), "_source": link}
|
||||
for link in (chunk_to_skip + chunk_to_feed)
|
||||
]
|
||||
success, failed = helpers.bulk(es, chunk_to_upload, raise_on_error=False)
|
||||
print(f"Success:{success}, Failed:{len(failed)}")
|
||||
|
||||
for f in failed:
|
||||
print(json.dumps(f, indent=2))
|
||||
success_counter += success
|
||||
fail_counter += len(failed)
|
||||
except Exception as e:
|
||||
print("Error during bulk upload:", e)
|
||||
|
||||
print(f"{success_counter} successfully uploaded. Failed: {fail_counter}\n")
|
||||
return success_counter, fail_counter
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description="Classify extracted links into content categories via an LLM.")
|
||||
add_common_args(parser)
|
||||
parser.add_argument("links_to_analyze_file", nargs="?", default=None,
|
||||
help="Override path to links_to_analyze.json (default: this entity's run output)")
|
||||
parser.add_argument("--problem-orgs", default=None,
|
||||
help="Override the problem_orgs_file configured for this entity")
|
||||
args = parser.parse_args()
|
||||
|
||||
start_time = time.time()
|
||||
print("Starting to categorize URLs")
|
||||
|
||||
config = load_config(args.config)
|
||||
entity = get_entity(config, args.entity)
|
||||
|
||||
# entity-driven settings that used to be hardcoded at module level
|
||||
es = get_es_client(config)
|
||||
llm_client, MODEL_NAME = get_llm_client(config)
|
||||
print(f"Using LLM model: {MODEL_NAME}, {config['llm']}")
|
||||
raw_index = entity["elasticsearch"]["raw_index"]
|
||||
index_name = entity["elasticsearch"]["categorized_index"]
|
||||
BANNED_HOSTNAMES = entity.get(
|
||||
"classifier_banned_hostnames",
|
||||
entity.get("banned_hostnames", []),
|
||||
)
|
||||
CATEGORIES = config.get("default_categories", ["Teaching", "Research", "Projects", "Staff", "News", "Other"])
|
||||
|
||||
links_file = args.links_to_analyze_file or out_path(config, args.entity, "links_to_analyze_file")
|
||||
with open(links_file, 'r') as json_stream:
|
||||
links_total = json.load(json_stream)
|
||||
|
||||
log_filename = out_path(config, args.entity, "classifier_log")
|
||||
if os.path.exists(log_filename):
|
||||
with open(log_filename, 'r') as f:
|
||||
try:
|
||||
categorizedUrls = json.load(f)
|
||||
except json.JSONDecodeError:
|
||||
categorizedUrls = {}
|
||||
else:
|
||||
categorizedUrls = {}
|
||||
|
||||
# get problem orgs file to add missing sources
|
||||
problem_orgs = {}
|
||||
path_to_problem_orgs = args.problem_orgs or (
|
||||
entity_input_path(config, args.entity, "problem_orgs_file") if entity.get("problem_orgs_file") else None
|
||||
)
|
||||
if path_to_problem_orgs:
|
||||
try:
|
||||
with open(path_to_problem_orgs, 'r') as file:
|
||||
problem_orgs = json.load(file)
|
||||
except Exception:
|
||||
print(f'Could not open the problem_orgs file at {path_to_problem_orgs}.')
|
||||
|
||||
parents = links_total['parent_leafs']
|
||||
children = links_total['child_leafs']
|
||||
|
||||
parents_to_analyse, children_to_analyse, total_urls = getParentsChildrenUrlCount(parents=parents, children=children)
|
||||
|
||||
if not check_elastic_status(index_name):
|
||||
sys.exit(1)
|
||||
|
||||
for i, parent in enumerate(parents_to_analyse):
|
||||
for j, child in enumerate(parent['children']):
|
||||
print(f'Parent {i + 1} of {len(parents_to_analyse)}: Child {j + 1} of {len(parent["children"])} \n')
|
||||
|
||||
if problem_orgs: # categorize actual orgs and not aggregators from problem_orgs.json
|
||||
for key, value in problem_orgs.items():
|
||||
if value == child['link']:
|
||||
child['link'] = key
|
||||
|
||||
categorizedUrls[child['link']] = "Entity"
|
||||
successes, fails = startCategorizing(child['sublinks'], index_name)
|
||||
total_updates += successes
|
||||
failures += fails
|
||||
with open(log_filename, 'w') as f:
|
||||
json.dump(categorizedUrls, f)
|
||||
print(f'Total: {total_updates} of {total_urls}. Failed: {failures}\n')
|
||||
|
||||
for i, child in enumerate(children_to_analyse):
|
||||
print(f'child {i + 1} of {len(children_to_analyse)}\n')
|
||||
|
||||
if problem_orgs: # categorize actual orgs and not aggregators from problem_orgs.json
|
||||
for key, value in problem_orgs.items():
|
||||
if value == child['link']:
|
||||
child['link'] = key
|
||||
|
||||
categorizedUrls[child['link']] = "Entity"
|
||||
|
||||
successes, fails = startCategorizing(child['sublinks'], index_name, max_rate=30)
|
||||
total_updates += successes
|
||||
failures += fails
|
||||
with open(log_filename, 'w') as f:
|
||||
json.dump(categorizedUrls, f)
|
||||
print(f'Total: {total_updates} of {total_urls}. Failed: {failures}\n')
|
||||
print(f'updated {total_updates} of {total_urls}\n')
|
||||
|
||||
runtime_hours = (time.time() - start_time) / 3600
|
||||
print(f"Runtime: {runtime_hours:.2f} hours")
|
||||
print("finished categorizing URLs")
|
||||
+1065
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,309 @@
|
||||
import time
|
||||
import json
|
||||
from json import JSONDecodeError
|
||||
import tiktoken
|
||||
import traceback
|
||||
import os
|
||||
import sys
|
||||
import argparse
|
||||
from pydantic import BaseModel
|
||||
from typing import List
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
|
||||
from pipeline_utils import load_config, get_entity, out_path, get_es_client, get_llm_client, add_common_args
|
||||
|
||||
MAX_KEYWORDS = 30
|
||||
|
||||
failed_extractions = {}
|
||||
failed_organizations = []
|
||||
|
||||
|
||||
class Keywords(BaseModel):
|
||||
items: List[str]
|
||||
|
||||
|
||||
def count_tokens(content):
|
||||
enc = tiktoken.encoding_for_model("gpt-4o")
|
||||
tokens = enc.encode(content)
|
||||
return len(tokens)
|
||||
|
||||
|
||||
def filter_scores(data, threshold=0.30): # threshold = % of highest
|
||||
if not data or not data[0].get('_score'):
|
||||
return []
|
||||
|
||||
highest_score = data[0]['_score']
|
||||
|
||||
return [
|
||||
item for item in data
|
||||
if (highest_score - item['_score']) / highest_score < threshold
|
||||
]
|
||||
|
||||
|
||||
def get_unique_keywords(string_array):
|
||||
unique_set = set(s.lower() for s in string_array)
|
||||
return list(dict.fromkeys(s for s in string_array if s.lower() in unique_set))
|
||||
|
||||
|
||||
def extract_keywords(prompt, bodies, org_uri, entity_title, source_links, max_retries=5):
|
||||
time.sleep(1)
|
||||
total_keywords = []
|
||||
for idx, body in enumerate(bodies):
|
||||
retries = 0
|
||||
tokens_count = count_tokens(body)
|
||||
print(f'Extracting body. ({idx + 1} of {len(bodies)}) with {tokens_count} ')
|
||||
while True:
|
||||
if retries > max_retries:
|
||||
keywords = {'items': []}
|
||||
print(f"Couldnt extract keywords for {entity_title}... Number of retries exceeded. Skipping it...")
|
||||
if org_uri in failed_extractions:
|
||||
failed_extractions[org_uri]['entities'].append(entity_title)
|
||||
failed_extractions[org_uri]['pages'].append(source_links[idx])
|
||||
else:
|
||||
failed_extractions[org_uri] = {}
|
||||
failed_extractions[org_uri]['entities'] = [entity_title]
|
||||
failed_extractions[org_uri]['pages'] = [source_links[idx]]
|
||||
with open(fails_log_filename, 'w') as f:
|
||||
json.dump(failed_extractions, f)
|
||||
break
|
||||
try:
|
||||
messages = [
|
||||
{"role": "system", "content": prompt},
|
||||
{"role": "user", "content": body}
|
||||
]
|
||||
|
||||
chat_completion = client.chat.completions.create(
|
||||
messages=messages,
|
||||
model=MODEL_NAME,
|
||||
)
|
||||
content = chat_completion.choices[0].message.content
|
||||
try:
|
||||
if content.startswith("```json"):
|
||||
response_array = json.loads(content[7:-3])
|
||||
else:
|
||||
response_array = json.loads(content)
|
||||
except JSONDecodeError:
|
||||
retries += 1
|
||||
print(f"Invalid JSON format. Retrying...{content}")
|
||||
continue
|
||||
try:
|
||||
keywords = Keywords(items=response_array)
|
||||
keywords = keywords.model_dump()
|
||||
except ValueError:
|
||||
retries += 1
|
||||
print(f"Content is formatted wrong. Retrying...{response_array}")
|
||||
continue
|
||||
except Exception:
|
||||
print(f"Exception occurred.{traceback.format_exc()} Retrying...")
|
||||
time.sleep(1)
|
||||
continue
|
||||
break
|
||||
total_keywords += keywords['items']
|
||||
return get_unique_keywords(total_keywords)[:MAX_KEYWORDS]
|
||||
|
||||
|
||||
def check_elastic_status():
|
||||
if not es.ping():
|
||||
print("Elasticsearch connection not found")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def update_organization(index_name, org):
|
||||
doc_id = org['_id']
|
||||
update_body = {
|
||||
"doc": {
|
||||
"staff": org['_source']['staff'],
|
||||
"projects": org['_source']['projects'],
|
||||
"news": org['_source']['news'],
|
||||
}
|
||||
}
|
||||
response = es.update(index=index_name, id=doc_id, body=update_body)
|
||||
return response
|
||||
|
||||
|
||||
def update_staff(prompt, org):
|
||||
org_uri = org['_source']['uri']
|
||||
staff = org['_source']['staff']
|
||||
for idx, staff_entry in enumerate(staff):
|
||||
name = staff_entry['name']
|
||||
query = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{"match_phrase": {"sources": org_uri}},
|
||||
{"match": {"body": {"query": name.lower(), "operator": "AND"}}}
|
||||
],
|
||||
"should": [
|
||||
{"match": {"uri": {"query": name.lower(), "boost": 5}}},
|
||||
{"match": {"uri": {"query": "staff", "boost": 2}}},
|
||||
{"match": {"uri": {"query": "mitarbeiter", "boost": 2}}},
|
||||
{"match": {"uri": {"query": "team", "boost": 2}}},
|
||||
{"match": {"uri": {"query": "member", "boost": 2}}},
|
||||
{"match": {"uri": {"query": "person", "boost": 2}}},
|
||||
{"match": {"body": {"query": "staff", "boost": 1.5}}},
|
||||
{"match": {"body": {"query": "mitarbeiter", "boost": 1.5}}},
|
||||
{"match": {"body": {"query": "member", "boost": 1.5}}},
|
||||
{"match": {"body": {"query": "person", "boost": 1.5}}},
|
||||
{"match": {"body": {"query": "team", "boost": 1.5}}}
|
||||
]
|
||||
}
|
||||
},
|
||||
"size": 5
|
||||
}
|
||||
|
||||
print(f'Extracting keywords of {name}: {idx + 1} of {len(staff)}')
|
||||
staff[idx] = update_content_entity(query=query, prompt=prompt.replace('{name}', name), entity=staff_entry, entity_title=name, org_uri=org_uri)
|
||||
|
||||
|
||||
def update_projects(prompt, org):
|
||||
org_uri = org['_source']['uri']
|
||||
projects = org['_source']['projects']
|
||||
for idx, project_entry in enumerate(projects):
|
||||
title = project_entry['title']
|
||||
query = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{"match_phrase": {"sources": org_uri}},
|
||||
{"match": {"body": title.lower()}}
|
||||
],
|
||||
"should": [
|
||||
{"match": {"uri": {"query": title.lower(), "boost": 5}}},
|
||||
{"match": {"uri": {"query": "projects", "boost": 2}}},
|
||||
{"match": {"uri": {"query": "projekte", "boost": 2}}},
|
||||
{"match": {"body": {"query": "projects", "boost": 1.5}}},
|
||||
{"match": {"body": {"query": "projekte", "boost": 1.5}}}
|
||||
]
|
||||
}
|
||||
},
|
||||
"size": 5
|
||||
}
|
||||
|
||||
print(f'Extracting keywords of {title}: {idx + 1} of {len(projects)}')
|
||||
projects[idx] = update_content_entity(query=query, prompt=prompt.replace('{project}', title), entity=project_entry, entity_title=title, org_uri=org_uri)
|
||||
|
||||
|
||||
def update_news(prompt, org):
|
||||
org_uri = org['_source']['uri']
|
||||
news = org['_source']['news']
|
||||
for idx, news_item in enumerate(news):
|
||||
title = news_item['title']
|
||||
query = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"must": [
|
||||
{"match_phrase": {"sources": org_uri}},
|
||||
{"match": {"body": title.lower()}}
|
||||
],
|
||||
"should": [
|
||||
{"match": {"uri": {"query": title.lower(), "boost": 5}}},
|
||||
{"match": {"uri": {"query": "news", "boost": 2}}},
|
||||
{"match": {"uri": {"query": "neuigkeit", "boost": 2}}},
|
||||
{"match": {"body": {"query": "news", "boost": 1.5}}},
|
||||
{"match": {"body": {"query": "neuigkeit", "boost": 1.5}}}
|
||||
]
|
||||
}
|
||||
},
|
||||
"size": 5
|
||||
}
|
||||
|
||||
print(f'Extracting keywords of {title}: {idx + 1} of {len(news)}')
|
||||
news[idx] = update_content_entity(query=query, prompt=prompt.replace('{news_item}', title), entity=news_item, entity_title=title, org_uri=org_uri)
|
||||
|
||||
|
||||
def update_content_entity(query, prompt, entity, entity_title, org_uri):
|
||||
entity_pages = filter_scores(es.search(index=categorized_index, body=query)['hits']['hits'])
|
||||
entity_pages_bodys = []
|
||||
source_links = []
|
||||
for page in entity_pages:
|
||||
entity_pages_bodys.append(page['_source']['body'])
|
||||
source_links.append(page['_source']['uri'])
|
||||
|
||||
keywords = extract_keywords(prompt=prompt, bodies=entity_pages_bodys, entity_title=entity_title, source_links=source_links, org_uri=org_uri)
|
||||
entity['keywords'] = keywords
|
||||
entity['links'] = source_links
|
||||
return entity
|
||||
|
||||
|
||||
def get_all_orgs():
|
||||
body = {
|
||||
"size": 10000,
|
||||
"query": {"bool": {"must": {"match_all": {}}}},
|
||||
"collapse": {"field": "uri.keyword"}
|
||||
}
|
||||
|
||||
all_organizations = es.search(index=content_index, body=body)['hits']['hits']
|
||||
return all_organizations
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description="Mine keywords from previously extracted staff/projects/news content.")
|
||||
add_common_args(parser)
|
||||
args = parser.parse_args()
|
||||
|
||||
print("Starting mining content keywords from extracted content")
|
||||
start_time = time.time()
|
||||
|
||||
config = load_config(args.config)
|
||||
entity = get_entity(config, args.entity)
|
||||
|
||||
es = get_es_client(config)
|
||||
client, MODEL_NAME = get_llm_client(config)
|
||||
categorized_index = entity["elasticsearch"]["categorized_index"]
|
||||
content_index = entity["elasticsearch"]["content_index"]
|
||||
|
||||
prompt_staff = """Extract as a big as possible set of unique and narrowly focused keywords from the following text that reflect {name}'s specific research interests and areas of expertise. Avoid general or broad terms. Focus only on concrete topics, methods, technologies. Return only a JSON-formatted array of keywords as a string.If no keywods can be extracted output an empty array. Do not include any explanations or additional text."""
|
||||
prompt_projects = """Extract as a big as possible set of unique and narrowly focused keywords from the project "{project}" that reflect its specific topics, methods, technologies, or application domains. Avoid general or vague terms. If no meaningful keywords can be extracted, return an empty JSON array. Output only a JSON-formatted array of keywords as a string. Do not include any explanations or additional text."""
|
||||
prompt_news = """Extract as a big as possible set of unique and narrowly focused keywords from the given news title "{news_item}" that capture its specific topic, event, technology, or issue. Avoid general terms or overly broad concepts. If no meaningful keywords can be extracted, return an empty JSON array. Output only a JSON-formatted array of keywords as a string. Do not include any explanations or additional text."""
|
||||
|
||||
if check_elastic_status():
|
||||
log_filename = out_path(config, args.entity, "keywords_updated_log")
|
||||
fails_log_filename = out_path(config, args.entity, "keywords_failed_log")
|
||||
|
||||
if os.path.exists(log_filename):
|
||||
with open(log_filename, 'r') as f:
|
||||
try:
|
||||
uploaded_orgs = json.load(f)
|
||||
except json.JSONDecodeError:
|
||||
uploaded_orgs = []
|
||||
else:
|
||||
uploaded_orgs = []
|
||||
|
||||
uploaded_urls = [org['uri'] for org in uploaded_orgs]
|
||||
|
||||
print('Uploaded orgs:', uploaded_urls)
|
||||
all_organizations = get_all_orgs()
|
||||
organizations = [org for org in all_organizations if org['_source']['uri'] not in uploaded_urls]
|
||||
if len(organizations) > 0:
|
||||
for idx, org in enumerate(organizations):
|
||||
print(f'Extracting organization: {idx + 1} of {len(organizations)}: {org["_source"]["uri"]}')
|
||||
update_staff(prompt=prompt_staff, org=org)
|
||||
update_projects(prompt=prompt_projects, org=org)
|
||||
update_news(prompt=prompt_news, org=org)
|
||||
|
||||
response = update_organization(index_name=content_index, org=org)
|
||||
if response and response['_shards']['failed'] == 0:
|
||||
print(f"{org['_source']['uri']} successfully updated.")
|
||||
uploaded_orgs.append({"uri": org['_source']['uri']})
|
||||
with open(log_filename, 'w') as f:
|
||||
json.dump(uploaded_orgs, f)
|
||||
else:
|
||||
print(f"Update failed for {org['_source']['uri']}")
|
||||
failed_organizations.append(org['_source']['uri'])
|
||||
|
||||
if not failed_organizations:
|
||||
print('All Organizations were updated.')
|
||||
else:
|
||||
print('Couldnt update the following organizations:', failed_organizations)
|
||||
|
||||
if failed_extractions:
|
||||
print('Failed extractions', failed_extractions)
|
||||
else:
|
||||
print("All Extractions were successfull.")
|
||||
else:
|
||||
print(f"Nothing to update. Delete {log_filename} first.")
|
||||
|
||||
runtime_hours = (time.time() - start_time) / 3600
|
||||
print(f"Runtime: {runtime_hours:.2f} hours")
|
||||
print("Finished mining content keywords from extracted content")
|
||||
@@ -0,0 +1,28 @@
|
||||
# Orgminer pipeline image. Build from the repo root:
|
||||
# docker build -f service/scripts/orgminer_pipeline/Dockerfile \
|
||||
# -t docker.nes.uni-due.de/inse/jobs/orgminer_pipeline:latest .
|
||||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PIP_NO_CACHE_DIR=1 \
|
||||
HF_HOME=/opt/hf-cache
|
||||
|
||||
# libmagic1: needed by python-magic. tini: forwards SIGTERM and reaps child processes.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends libmagic1 tini \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app/orgminer_pipeline
|
||||
|
||||
|
||||
RUN pip install torch==2.9.1
|
||||
|
||||
COPY service/scripts/orgminer_pipeline/requirements.txt .
|
||||
RUN pip install -r requirements.txt
|
||||
|
||||
COPY service/scripts/orgminer_pipeline/ ./
|
||||
|
||||
# Pipeline state (WARCs, crawl state, checkpoints). Mounted as a volume by the job runner.
|
||||
RUN mkdir -p /app/orgminer_pipeline/runs
|
||||
|
||||
ENTRYPOINT ["tini", "--"]
|
||||
@@ -0,0 +1,36 @@
|
||||
# University Organization Pipeline
|
||||
|
||||
This repository crawls university organization websites and extracts structured
|
||||
staff, project, news, and keyword information.
|
||||
|
||||
## Pipeline stages
|
||||
|
||||
For one configured entity, the pipeline executes:
|
||||
|
||||
1. Generate crawl seeds from the ground-truth file.
|
||||
2. Crawl all seed URLs and their allowed internal links.
|
||||
3. Store responses as WARC files.
|
||||
4. Build a redirect lookup.
|
||||
5. Upload HTML content to Elasticsearch.
|
||||
6. Build the organization hierarchy.
|
||||
7. Classify crawled URLs with the configured LLM.
|
||||
8. Extract staff, projects, and news.
|
||||
9. Extract focused keywords for extracted content.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Python environment containing Scrapy, scrapy-warcio, warcio, Elasticsearch,
|
||||
OpenAI client, Trafilatura, YAKE, langdetect, tiktoken, and project dependencies.
|
||||
- Elasticsearch credentials.
|
||||
- LLM endpoint and API key.
|
||||
|
||||
Create `.env` in the repository root:
|
||||
|
||||
```env
|
||||
ES_PASSWORD=...
|
||||
ES_HOST=https://your-elasticsearch-host:443
|
||||
ES_USERNAME=elastic
|
||||
|
||||
llm_api=https://your-llm-api/v1
|
||||
llm_key=...
|
||||
```
|
||||
Binary file not shown.
@@ -0,0 +1,12 @@
|
||||
# Define here the models for your scraped items
|
||||
#
|
||||
# See documentation in:
|
||||
# https://docs.scrapy.org/en/latest/topics/items.html
|
||||
|
||||
import scrapy
|
||||
|
||||
|
||||
class CrawlerItem(scrapy.Item):
|
||||
# define the fields for your item here like:
|
||||
# name = scrapy.Field()
|
||||
pass
|
||||
@@ -0,0 +1,120 @@
|
||||
# Define here the models for your spider middleware
|
||||
#
|
||||
# See documentation in:
|
||||
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
|
||||
|
||||
from scrapy import signals
|
||||
|
||||
# useful for handling different item types with a single interface
|
||||
from itemadapter import is_item, ItemAdapter
|
||||
|
||||
import scrapy_warcio
|
||||
|
||||
class CrawlerSpiderMiddleware:
|
||||
# Not all methods need to be defined. If a method is not defined,
|
||||
# scrapy acts as if the spider middleware does not modify the
|
||||
# passed objects.
|
||||
|
||||
@classmethod
|
||||
def from_crawler(cls, crawler):
|
||||
# This method is used by Scrapy to create your spiders.
|
||||
s = cls()
|
||||
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
|
||||
return s
|
||||
|
||||
def process_spider_input(self, response, spider):
|
||||
# Called for each response that goes through the spider
|
||||
# middleware and into the spider.
|
||||
|
||||
# Should return None or raise an exception.
|
||||
return None
|
||||
|
||||
def process_spider_output(self, response, result, spider):
|
||||
# Called with the results returned from the Spider, after
|
||||
# it has processed the response.
|
||||
|
||||
# Must return an iterable of Request, or item objects.
|
||||
for i in result:
|
||||
yield i
|
||||
|
||||
def process_spider_exception(self, response, exception, spider):
|
||||
# Called when a spider or process_spider_input() method
|
||||
# (from other spider middleware) raises an exception.
|
||||
|
||||
# Should return either None or an iterable of Request or item objects.
|
||||
pass
|
||||
|
||||
def process_start_requests(self, start_requests, spider):
|
||||
# Called with the start requests of the spider, and works
|
||||
# similarly to the process_spider_output() method, except
|
||||
# that it doesn’t have a response associated.
|
||||
|
||||
# Must return only requests (not items).
|
||||
for r in start_requests:
|
||||
yield r
|
||||
|
||||
def spider_opened(self, spider):
|
||||
spider.logger.info("Spider opened: %s" % spider.name)
|
||||
|
||||
|
||||
class CrawlerDownloaderMiddleware:
|
||||
# Not all methods need to be defined. If a method is not defined,
|
||||
# scrapy acts as if the downloader middleware does not modify the
|
||||
# passed objects.
|
||||
|
||||
@classmethod
|
||||
def from_crawler(cls, crawler):
|
||||
# This method is used by Scrapy to create your spiders.
|
||||
s = cls()
|
||||
crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
|
||||
return s
|
||||
|
||||
def process_request(self, request, spider):
|
||||
# Called for each request that goes through the downloader
|
||||
# middleware.
|
||||
|
||||
# Must either:
|
||||
# - return None: continue processing this request
|
||||
# - or return a Response object
|
||||
# - or return a Request object
|
||||
# - or raise IgnoreRequest: process_exception() methods of
|
||||
# installed downloader middleware will be called
|
||||
return None
|
||||
|
||||
def process_response(self, request, response, spider):
|
||||
# Called with the response returned from the downloader.
|
||||
|
||||
# Must either;
|
||||
# - return a Response object
|
||||
# - return a Request object
|
||||
# - or raise IgnoreRequest
|
||||
return response
|
||||
|
||||
def process_exception(self, request, exception, spider):
|
||||
# Called when a download handler or a process_request()
|
||||
# (from other downloader middleware) raises an exception.
|
||||
|
||||
# Must either:
|
||||
# - return None: continue processing this exception
|
||||
# - return a Response object: stops process_exception() chain
|
||||
# - return a Request object: stops process_exception() chain
|
||||
pass
|
||||
|
||||
def spider_opened(self, spider):
|
||||
spider.logger.info("Spider opened: %s" % spider.name)
|
||||
|
||||
|
||||
# Warc IO downloader middleware
|
||||
class WarcioDownloaderMiddleware:
|
||||
|
||||
def __init__(self):
|
||||
self.warcio = scrapy_warcio.ScrapyWarcIo()
|
||||
|
||||
def process_request(self, request, spider):
|
||||
request.meta['WARC-Date'] = scrapy_warcio.warc_date()
|
||||
return None
|
||||
|
||||
def process_response(self, request, response, spider):
|
||||
request.meta["WARC-Record-Depth"] = str(request.meta.get("depth", 0))
|
||||
self.warcio.write(response, request)
|
||||
return response
|
||||
@@ -0,0 +1,13 @@
|
||||
# Define your item pipelines here
|
||||
#
|
||||
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
|
||||
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
|
||||
|
||||
|
||||
# useful for handling different item types with a single interface
|
||||
from itemadapter import ItemAdapter
|
||||
|
||||
|
||||
class CrawlerPipeline:
|
||||
def process_item(self, item, spider):
|
||||
return item
|
||||
@@ -0,0 +1,122 @@
|
||||
# Scrapy settings for crawler project
|
||||
#
|
||||
# For simplicity, this file contains only settings considered important or
|
||||
# commonly used. You can find more settings consulting the documentation:
|
||||
#
|
||||
# https://docs.scrapy.org/en/latest/topics/settings.html
|
||||
# https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
|
||||
# https://docs.scrapy.org/en/latest/topics/spider-middleware.html
|
||||
|
||||
import os
|
||||
|
||||
BOT_NAME = "crawler"
|
||||
|
||||
SPIDER_MODULES = ["crawler.spiders"]
|
||||
NEWSPIDER_MODULE = "crawler.spiders"
|
||||
|
||||
|
||||
# Crawl responsibly by identifying yourself (and your website) on the user-agent
|
||||
USER_AGENT = "inse-crawler (+https://www.nes.uni-due.de)"
|
||||
|
||||
# Obey robots.txt rules
|
||||
ROBOTSTXT_OBEY = True
|
||||
|
||||
# Configure maximum concurrent requests performed by Scrapy (default: 16)
|
||||
CONCURRENT_REQUESTS = 16
|
||||
|
||||
# Configure a delay for requests for the same website (default: 0)
|
||||
# See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay
|
||||
# See also autothrottle settings and docs
|
||||
DOWNLOAD_DELAY = 2
|
||||
# The download delay setting will honor only one of:
|
||||
CONCURRENT_REQUESTS_PER_DOMAIN = 16
|
||||
# CONCURRENT_REQUESTS_PER_IP = 16
|
||||
|
||||
# Disable cookies (enabled by default)
|
||||
#COOKIES_ENABLED = False
|
||||
|
||||
# Disable Telnet Console (enabled by default)
|
||||
#TELNETCONSOLE_ENABLED = False
|
||||
|
||||
# Override the default request headers:
|
||||
#DEFAULT_REQUEST_HEADERS = {
|
||||
# "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
|
||||
# "Accept-Language": "en",
|
||||
#}
|
||||
|
||||
# Enable or disable spider middlewares
|
||||
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
|
||||
#SPIDER_MIDDLEWARES = {
|
||||
# "crawler.middlewares.CrawlerSpiderMiddleware": 543,
|
||||
#}
|
||||
|
||||
# Enable or disable downloader middlewares
|
||||
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
|
||||
#DOWNLOADER_MIDDLEWARES = {
|
||||
# "crawler.middlewares.CrawlerDownloaderMiddleware": 543,
|
||||
#}
|
||||
|
||||
# Enable or disable extensions
|
||||
# See https://docs.scrapy.org/en/latest/topics/extensions.html
|
||||
#EXTENSIONS = {
|
||||
# "scrapy.extensions.telnet.TelnetConsole": None,
|
||||
#}
|
||||
|
||||
# Configure item pipelines
|
||||
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
|
||||
#ITEM_PIPELINES = {
|
||||
# "crawler.pipelines.CrawlerPipeline": 300,
|
||||
#}
|
||||
|
||||
# Enable and configure the AutoThrottle extension (disabled by default)
|
||||
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
|
||||
#AUTOTHROTTLE_ENABLED = True
|
||||
# The initial download delay
|
||||
#AUTOTHROTTLE_START_DELAY = 5
|
||||
# The maximum download delay to be set in case of high latencies
|
||||
#AUTOTHROTTLE_MAX_DELAY = 60
|
||||
# The average number of requests Scrapy should be sending in parallel to
|
||||
# each remote server
|
||||
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
|
||||
# Enable showing throttling stats for every response received:
|
||||
#AUTOTHROTTLE_DEBUG = False
|
||||
|
||||
# Enable and configure HTTP caching (disabled by default)
|
||||
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
|
||||
#HTTPCACHE_ENABLED = True
|
||||
#HTTPCACHE_EXPIRATION_SECS = 0
|
||||
#HTTPCACHE_DIR = "httpcache"
|
||||
#HTTPCACHE_IGNORE_HTTP_CODES = []
|
||||
#HTTPCACHE_STORAGE = "scrapy.extensions.httpcache.FilesystemCacheStorage"
|
||||
|
||||
# Set settings whose default value is deprecated to a future-proof value
|
||||
REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7"
|
||||
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
|
||||
FEED_EXPORT_ENCODING = "utf-8"
|
||||
|
||||
# Add the warcio downloader middleware
|
||||
os.environ.setdefault("SCRAPY_WARCIO_SETTINGS", "warc.yml")
|
||||
|
||||
DOWNLOAD_DELAY = 2
|
||||
CONCURRENT_REQUESTS = 16
|
||||
CONCURRENT_REQUESTS_PER_DOMAIN = 16
|
||||
DOWNLOAD_TIMEOUT = 40
|
||||
|
||||
DOWNLOADER_MIDDLEWARES = {
|
||||
# swap the order of redirect and compression middleware to inject warcio at the right place
|
||||
"scrapy.downloadermiddlewares.redirect.RedirectMiddleware": 590,
|
||||
"crawler.middlewares.WarcioDownloaderMiddleware": 595,
|
||||
"scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware": 600,
|
||||
}
|
||||
|
||||
# # Use true breadth first search to crawl the websites
|
||||
# DEPTH_LIMIT = 6
|
||||
# DEPTH_STATS_VERBOSE = True
|
||||
DEPTH_PRIORITY = 1
|
||||
SCHEDULER_DISK_QUEUE = "scrapy.squeues.PickleFifoDiskQueue"
|
||||
SCHEDULER_MEMORY_QUEUE = "scrapy.squeues.FifoMemoryQueue"
|
||||
|
||||
#DFS
|
||||
# DEPTH_PRIORITY = 1
|
||||
# SCHEDULER_DISK_QUEUE = 'scrapy.squeues.LifoDiskQueue'
|
||||
# SCHEDULER_MEMORY_QUEUE = 'scrapy.squeues.LifoMemoryQueue'
|
||||
@@ -0,0 +1,4 @@
|
||||
# This package will contain the spiders of your Scrapy project
|
||||
#
|
||||
# Please refer to the documentation for information on how to create and manage
|
||||
# your spiders.
|
||||
@@ -0,0 +1,141 @@
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import scrapy
|
||||
from scrapy.linkextractors import LinkExtractor
|
||||
from scrapy.spiders import CrawlSpider, Rule
|
||||
|
||||
|
||||
REPOSITORY_ROOT = os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), "..", "..", "..")
|
||||
)
|
||||
if REPOSITORY_ROOT not in sys.path:
|
||||
sys.path.insert(0, REPOSITORY_ROOT)
|
||||
|
||||
from pipeline_utils import generated_entities_path, get_entity, load_config
|
||||
|
||||
|
||||
class OrganizationSpider(CrawlSpider):
|
||||
"""
|
||||
Generic entity-driven university crawler.
|
||||
|
||||
Example:
|
||||
scrapy crawl organization -a entity=ude -a config=/path/pipeline_config.json
|
||||
"""
|
||||
|
||||
name = "organization"
|
||||
|
||||
@classmethod
|
||||
def from_crawler(cls, crawler, *args, **kwargs):
|
||||
entity = kwargs.get("entity")
|
||||
config = kwargs.get("config")
|
||||
if entity and config:
|
||||
pipeline_config = load_config(config)
|
||||
entity_config = get_entity(pipeline_config, entity)
|
||||
crawl_config = entity_config.get("crawl", {})
|
||||
print ("CRAWL CONFIG: ", crawl_config)
|
||||
crawler.settings.set(
|
||||
"DEPTH_LIMIT", int(crawl_config.get("depth_limit", 6)), priority="spider"
|
||||
)
|
||||
crawler.settings.set(
|
||||
"DOWNLOAD_DELAY", float(crawl_config.get("download_delay", 2)), priority="spider"
|
||||
)
|
||||
crawler.settings.set(
|
||||
"CONCURRENT_REQUESTS",
|
||||
int(crawl_config.get("concurrent_requests", 16)),
|
||||
priority="spider",
|
||||
)
|
||||
crawler.settings.set(
|
||||
"CONCURRENT_REQUESTS_PER_DOMAIN",
|
||||
int(crawl_config.get("concurrent_requests_per_domain", 16)),
|
||||
priority="spider",
|
||||
)
|
||||
crawler.settings.set(
|
||||
"DOWNLOAD_TIMEOUT", int(crawl_config.get("download_timeout", 40)), priority="spider"
|
||||
)
|
||||
crawler.settings.set(
|
||||
"USER_AGENT", crawl_config.get("user_agent", "inse-crawler"), priority="spider"
|
||||
)
|
||||
print(
|
||||
f"Starting crawler with maximum depth: "
|
||||
f"{crawler.settings.getint('DEPTH_LIMIT')}"
|
||||
)
|
||||
return super().from_crawler(crawler, *args, **kwargs)
|
||||
|
||||
def __init__(self, entity=None, config=None, *args, **kwargs):
|
||||
if not entity:
|
||||
raise ValueError("Missing required Scrapy argument: -a entity=<entity>")
|
||||
|
||||
self.entity_name = entity
|
||||
self.config_path = config
|
||||
|
||||
pipeline_config = load_config(config)
|
||||
entity_config = get_entity(pipeline_config, entity)
|
||||
crawl_config = entity_config.get("crawl", {})
|
||||
|
||||
self.allowed_domains = crawl_config.get("allowed_domains", [])
|
||||
self.banned_hostnames = {
|
||||
host.lower().rstrip(".")
|
||||
for host in crawl_config.get("banned_hostnames", [])
|
||||
}
|
||||
self.deny_patterns = crawl_config.get("deny_url_patterns", [])
|
||||
|
||||
if not self.allowed_domains:
|
||||
raise ValueError(
|
||||
f"Entity '{entity}' has no configured crawl.allowed_domains."
|
||||
)
|
||||
|
||||
seeds_path = generated_entities_path(pipeline_config, entity)
|
||||
if not os.path.exists(seeds_path):
|
||||
raise ValueError(
|
||||
f"Generated seed file does not exist: {seeds_path}. "
|
||||
"Run generate_entities.py first."
|
||||
)
|
||||
|
||||
with open(seeds_path, encoding="utf-8") as handle:
|
||||
seed_data = json.load(handle)
|
||||
|
||||
self.start_urls = [seed["url"] for seed in seed_data.get("seeds", [])]
|
||||
if not self.start_urls:
|
||||
raise ValueError(
|
||||
f"No valid seeds available in {seeds_path}; refusing to crawl."
|
||||
)
|
||||
|
||||
self.rules = (
|
||||
Rule(
|
||||
LinkExtractor(allow_domains=self.allowed_domains, deny=self.deny_patterns),
|
||||
follow=True,
|
||||
callback="parse_page",
|
||||
),
|
||||
)
|
||||
|
||||
super().__init__(*args, **kwargs)
|
||||
|
||||
def hostname_is_banned(self, url):
|
||||
hostname = (urlsplit(url).hostname or "").lower().rstrip(".")
|
||||
return any(
|
||||
hostname == banned or hostname.endswith("." + banned)
|
||||
for banned in self.banned_hostnames
|
||||
)
|
||||
|
||||
def start_requests(self):
|
||||
for request in super().start_requests():
|
||||
if not self.hostname_is_banned(request.url):
|
||||
yield request
|
||||
|
||||
def _requests_to_follow(self, response):
|
||||
for request in super()._requests_to_follow(response):
|
||||
if not self.hostname_is_banned(request.url):
|
||||
yield request
|
||||
|
||||
def parse_start_url(self, response):
|
||||
print(f"[SEED] depth {response.meta.get('depth', 0)}: {response.url}")
|
||||
self.crawler.stats.inc_value("organization/pages_visited")
|
||||
return []
|
||||
|
||||
def parse_page(self, response):
|
||||
print(f"[LINK] depth {response.meta.get('depth', 0)}: {response.url}")
|
||||
self.crawler.stats.inc_value("organization/pages_visited")
|
||||
return []
|
||||
@@ -0,0 +1,14 @@
|
||||
import scrapy
|
||||
import scrapy.spiders
|
||||
import scrapy.linkextractors
|
||||
|
||||
class TudSpider(scrapy.spiders.CrawlSpider):
|
||||
name = "tud"
|
||||
allowed_domains = ["https://www.tu-dortmund.de/" ]
|
||||
start_urls = [ "https://www.tu-dortmund.de/" ]
|
||||
skip_urls = []
|
||||
rules = (scrapy.spiders.Rule(scrapy.linkextractors.LinkExtractor(deny=skip_urls), follow=True),)
|
||||
|
||||
def parse(self, response):
|
||||
# parse item here
|
||||
self.state["items_count"] = self.state.get("items_count", 0) + 1
|
||||
@@ -0,0 +1,44 @@
|
||||
import scrapy
|
||||
import scrapy.spiders
|
||||
import scrapy.linkextractors
|
||||
import logging
|
||||
import pickle
|
||||
|
||||
class UdeSpider(scrapy.spiders.CrawlSpider):
|
||||
name = "ude"
|
||||
allowed_domains = [ "uni-due.de", "uk-essen.de"]
|
||||
|
||||
# start_urls = [ "https://www.uni-due.de" ]
|
||||
|
||||
with open("entities", 'rb') as f:
|
||||
start_urls = pickle.load(f)[:1]
|
||||
|
||||
skip_urls = [
|
||||
r"(campus|webmailer|webmail|git|moodle|primo|shop|lehramtswiki)\.(uni-duisburg-essen|uni-due)\.de",
|
||||
r"belegung\.uni-due\.de",
|
||||
r"belegung\.uni-due\.de/lsf",
|
||||
r"uni-due\.de/ub",
|
||||
r"uni-due\.digibib\.net",
|
||||
r"uni-due\.zoom\.us",
|
||||
r"uni-due\.de/myude/",
|
||||
r"uni-due\.de/en/deadlines\.php",
|
||||
r"uni-due\.de/verwaltung",
|
||||
r"uni-due\.de/zim",
|
||||
r"uni-due\.de/aktuell",
|
||||
r"duepublico2\.uni-due\.de",
|
||||
r"uni-due\.de/person",
|
||||
r"uni-due\.de/de/presse",
|
||||
r"uni-due\.de/de/campusaktuell",
|
||||
r"uni-due\.de/de/intranet",
|
||||
r"uni-due\.de/de/veranstaltungen",
|
||||
r"uni-due\.de/de/presse/meldung\.php",
|
||||
r"\.bib$"
|
||||
]
|
||||
rules = (scrapy.spiders.Rule(scrapy.linkextractors.LinkExtractor(deny=skip_urls), follow=True),)
|
||||
|
||||
# def start_requests(self):
|
||||
# yield scrapy.Request(url=self.start_urls, callback=self.parse)
|
||||
|
||||
|
||||
def parse(self, response):
|
||||
self.state["items_count"] = self.state.get("items_count", 0) + 1
|
||||
@@ -0,0 +1,13 @@
|
||||
# export SCRAPY_WARCIO_SETTINGS='/path/to/settings.yml'
|
||||
|
||||
---
|
||||
warc_spec: https://iipc.github.io/warc-specifications/specifications/warc-format/warc-1.0/
|
||||
max_warc_size: 5000000000 # 5GB
|
||||
|
||||
collection: UDE # collection name
|
||||
description: A crawl of the websites of the UDE # collection description
|
||||
operator: arman.arzani@uni-due.de # operator email address
|
||||
robots: obey # robots policy
|
||||
user_agent: ude-crawler # your user-agent
|
||||
warc_prefix: ude # WARC filename prefix
|
||||
warc_dest: ./warc # WARC files destination
|
||||
@@ -0,0 +1,91 @@
|
||||
import json
|
||||
import os
|
||||
import model
|
||||
import typing
|
||||
import selenium
|
||||
import selenium.webdriver
|
||||
import selenium.webdriver.chrome.service
|
||||
import webdriver_manager.chrome
|
||||
import time
|
||||
|
||||
class Browser:
|
||||
chrome: selenium.webdriver.Chrome
|
||||
def __init__(self):
|
||||
self.__create_chrome()
|
||||
|
||||
def __create_chrome(self):
|
||||
''' Creates a headless chrome browser that does not download files. '''
|
||||
options = selenium.webdriver.ChromeOptions()
|
||||
options.add_argument('--headless') # if headless not working correctly use '--headless=new' or '--headless=old'
|
||||
options.add_argument('--window-size=1920,1080')
|
||||
options.add_argument("--disable-cache")
|
||||
options.add_argument("--disk-cache-size=0")
|
||||
os.makedirs("downloads", exist_ok=True)
|
||||
options.add_experimental_option("prefs", { "download_restrictions" : 3, "download.default_directory": "downloads" })
|
||||
options.page_load_strategy = 'normal'
|
||||
self.chrome = selenium.webdriver.Chrome(service=selenium.webdriver.chrome.service.Service(webdriver_manager.chrome.ChromeDriverManager().install()), options=options)
|
||||
self.chrome.execute_cdp_cmd("Network.setCacheDisabled", {"cacheDisabled":True})
|
||||
|
||||
def __download(self, url: str, pagedepth: int = 0, link_text: str = '') -> model.Page:
|
||||
''' Downloads a page using a headless browser and extracts all links. '''
|
||||
self.chrome.get(url)
|
||||
time.sleep(0.5)
|
||||
page_source = self.chrome.page_source
|
||||
page_links = json.loads(self.chrome.execute_script(
|
||||
'''
|
||||
var elements = document.getElementsByTagName('a');
|
||||
var results = [];
|
||||
for (var i = 0; i < elements.length; i++) {
|
||||
if (typeof elements[i].href === 'string' || elements[i].href instanceof String){
|
||||
results.push({
|
||||
url: "" + elements[i].href,
|
||||
text: "" + elements[i].innerText,
|
||||
wrapper: elements[i].querySelector('a') != null
|
||||
});
|
||||
}
|
||||
}
|
||||
return JSON.stringify(results);
|
||||
'''
|
||||
))
|
||||
|
||||
if link_text == '':
|
||||
found_link_text_flag = False
|
||||
elif link_text in page_source:
|
||||
found_link_text_flag = True
|
||||
else:
|
||||
found_link_text_flag = False
|
||||
|
||||
links: typing.List[model.Link] = []
|
||||
for page_link in page_links:
|
||||
u = page_link['url']
|
||||
while u.endswith("/"):
|
||||
u = u[:-1]
|
||||
link = model.Link(url = page_link['url'], pagedepth = pagedepth + 1, text = page_link['text'], wrapper = page_link['wrapper'])
|
||||
links.append(link)
|
||||
|
||||
browser_url = self.chrome.current_url
|
||||
if browser_url.endswith("/"):
|
||||
browser_url = browser_url[:-1]
|
||||
return model.Page(url = browser_url, pagedepth = pagedepth, text = page_source, links = links, found_link_text_flag = found_link_text_flag)
|
||||
|
||||
def normalize(self, url: str) -> str:
|
||||
return url.strip()
|
||||
|
||||
def download(self, url: str, pagedepth: int = 0, link_text: str = '') -> model.Page:
|
||||
''' Downloads a page and handles crashes by restarting chrome once. '''
|
||||
url = self.normalize(url)
|
||||
try:
|
||||
return self.__download(url, pagedepth, link_text)
|
||||
except Exception as e:
|
||||
self.__create_chrome()
|
||||
try:
|
||||
return self.__download(url, pagedepth, link_text)
|
||||
except Exception as e:
|
||||
print("Failed to download", url, "due to", e)
|
||||
return model.Page(url = url, pagedepth = pagedepth, text = '', links = [], found_link_text_flag = False)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
import typing
|
||||
import json
|
||||
import model
|
||||
# from . import model
|
||||
import browser
|
||||
# import algorithm
|
||||
|
||||
def read_truth(file_path: str, browser: typing.Optional[browser.Browser] = None) -> typing.List[model.FacultyEntity]:
|
||||
''' Reads the truth from a json file. '''
|
||||
data = dict()
|
||||
with open(file_path, 'r') as file:
|
||||
data = json.load(file)
|
||||
result = []
|
||||
for f_data in data["faculties"]:
|
||||
faculty = _parse_truth(model.FacultyEntity, f_data, browser)
|
||||
if faculty is not None:
|
||||
result.append(faculty)
|
||||
for i_data in f_data["institutes"]:
|
||||
institute = _parse_truth(model.InsituteEntity, i_data, browser)
|
||||
if institute is not None:
|
||||
faculty.institutes.append(institute)
|
||||
for c_data in i_data["chairs"]:
|
||||
chair = _parse_truth(model.ChairEntity, c_data, browser)
|
||||
if chair is not None:
|
||||
faculty.chairs.append(chair)
|
||||
for c_data in f_data["chairs"]:
|
||||
chair = _parse_truth(model.ChairEntity, c_data, browser)
|
||||
if chair is not None:
|
||||
faculty.chairs.append(chair)
|
||||
faculty.institutes = _deduplicate(faculty.institutes)
|
||||
faculty.chairs = _deduplicate(faculty.chairs)
|
||||
return result
|
||||
|
||||
def _parse_truth(cls: type, data: dict, browser: typing.Optional[browser.Browser]) -> typing.Optional[model.Entity]:
|
||||
links = [ ]
|
||||
if data['link_en'] != 'None':
|
||||
links.append(data['link_en'])
|
||||
# links.append(data['link_en'] + "/")
|
||||
|
||||
if 'link_en_2' in data:
|
||||
if data['link_en_2'] != 'None' and data['link_en_2'] not in links:
|
||||
links.append(data['link_en_2'])
|
||||
# links.append(data['link_en_2'] + "/")
|
||||
if 'link_en_3' in data:
|
||||
if data['link_en_3'] != 'None' and data['link_en_3'] not in links:
|
||||
links.append(data['link_en_3'])
|
||||
# links.append(data['link_en_3'] + "/")
|
||||
|
||||
if data['link_de'] != 'None' and data['link_de'] not in links:
|
||||
links.append(data['link_de'])
|
||||
# links.append(data['link_de'] + "/")
|
||||
|
||||
if 'link_de_2' in data:
|
||||
if data['link_de_2'] != 'None' and data['link_de_2'] not in links:
|
||||
links.append(data['link_de_2'])
|
||||
# links.append(data['link_de_2'] + "/")
|
||||
if 'link_de_3' in data:
|
||||
if data['link_de_3'] != 'None' and data['link_de_3'] not in links:
|
||||
links.append(data['link_de_3'])
|
||||
# links.append(data['link_de_3'] + "/")
|
||||
|
||||
if len(links) == 0:
|
||||
return None
|
||||
name = ""
|
||||
if data["name_de"] != '':
|
||||
name = data["name_de"]
|
||||
elif data["name_en"] != '':
|
||||
name = data["name_en"]
|
||||
return cls.create(name=name, targets=_create_targets(links, browser))
|
||||
|
||||
|
||||
def read_prediction(file_path: str, browser: typing.Optional[browser.Browser] = None) -> typing.List[model.FacultyEntity]:
|
||||
''' Reads a json file with predictions. '''
|
||||
aggregators = _read_aggregators(file_path)
|
||||
faculties = _create_faculties(aggregators, browser)
|
||||
aggregators_by_url = { aggregator.url: aggregator for aggregator in aggregators }
|
||||
for aggregator in aggregators:
|
||||
if aggregator.concept.type == model.ConceptType.FACULTY:
|
||||
continue
|
||||
faculty = None
|
||||
current = aggregator
|
||||
while True:
|
||||
search = current.parent_link
|
||||
faculty = _find_facultiy(search, faculties)
|
||||
if current.parent == '' or faculty != None:
|
||||
break
|
||||
current = aggregators_by_url[current.parent]
|
||||
if faculty == None:
|
||||
# continue
|
||||
raise Exception("Could not find faculty for " + aggregator.url + " with parent " + aggregator.parent + " and parent link " + aggregator.parent_link)
|
||||
if aggregator.concept.type == model.ConceptType.CHAIR:
|
||||
faculty.chairs.extend(_create_chairs(aggregator.children, browser))
|
||||
elif aggregator.concept.type == model.ConceptType.INSTITUTE:
|
||||
faculty.institutes.extend(_create_institutes(aggregator.children, browser))
|
||||
for faculty in faculties:
|
||||
faculty.chairs = _deduplicate(faculty.chairs)
|
||||
faculty.institutes = _deduplicate(faculty.institutes)
|
||||
return faculties
|
||||
|
||||
def _read_aggregators(file_path: str) -> typing.List[model.AggregatorPage]:
|
||||
''' Reads a json file with aggregators. '''
|
||||
lines = []
|
||||
with open(file_path, "r") as f:
|
||||
lines = f.readlines()
|
||||
aggregators = []
|
||||
for line in lines:
|
||||
data = json.loads(line)
|
||||
data['text'] = ''
|
||||
aggregator = model.AggregatorPage.model_validate(data)
|
||||
aggregators.append(aggregator)
|
||||
return aggregators
|
||||
|
||||
def _deduplicate(entities: typing.List[model.Entity]) -> typing.List[model.Entity]:
|
||||
''' Deduplicates a list of entities. '''
|
||||
results = []
|
||||
for entity in entities:
|
||||
duplicate = False
|
||||
for result in results:
|
||||
if entity.equals(result):
|
||||
duplicate = True
|
||||
break
|
||||
if not duplicate:
|
||||
results.append(entity)
|
||||
return results
|
||||
|
||||
|
||||
def _find_facultiy(url: str, faculties: typing.List[model.FacultyEntity]) -> typing.Optional[model.FacultyEntity]:
|
||||
''' Finds a faculty with the specified url. '''
|
||||
for faculty in faculties:
|
||||
for target in faculty.targets:
|
||||
if target.url == url:
|
||||
return faculty
|
||||
return None
|
||||
|
||||
def _create_chairs(links: typing.List[model.Link], browser: typing.Optional[browser.Browser]) -> typing.List[model.ChairEntity]:
|
||||
''' Creates chairs from a list of links. '''
|
||||
chairs = []
|
||||
for link in links:
|
||||
chairs.append(model.ChairEntity.create(name=link.text, targets=_create_targets([link.url], browser, link.pagedepth, link.text)))
|
||||
return chairs
|
||||
|
||||
def _create_institutes(links: typing.List[model.Link], browser: typing.Optional[browser.Browser]) -> typing.List[model.InsituteEntity]:
|
||||
''' Creates institutes from a list of links. '''
|
||||
institutes = []
|
||||
for link in links:
|
||||
institutes.append(model.InsituteEntity.create(name=link.text, targets=_create_targets([link.url], browser, link.pagedepth, link.text)))
|
||||
return institutes
|
||||
|
||||
def _create_faculties(aggregators: typing.List[model.AggregatorPage], browser: typing.Optional[browser.Browser]) -> typing.List[model.FacultyEntity]:
|
||||
''' Creates faculties from a list of aggregators. '''
|
||||
faculty_links = []
|
||||
for aggregator in aggregators:
|
||||
if aggregator.concept.type == model.ConceptType.FACULTY:
|
||||
aggregator_url = aggregator.url
|
||||
if aggregator_url.endswith("/"):
|
||||
aggregator_url[:-1]
|
||||
for link in aggregator.children:
|
||||
link_url = link.url
|
||||
if link_url.endswith("/"):
|
||||
link_url[:-1]
|
||||
if aggregator_url == link_url:
|
||||
continue
|
||||
if not algorithm.contains_resource(faculty_links, link.url):
|
||||
faculty_links.append(link)
|
||||
faculties = []
|
||||
for link in faculty_links:
|
||||
faculties.append(model.FacultyEntity.create(name=link.text, targets=_create_targets([link.url], browser, link.pagedepth, link.text)))
|
||||
return faculties
|
||||
|
||||
def _create_targets(urls: typing.List[str], browser: typing.Optional[browser.Browser], pagedepth: int = 0, link_text: str = '' ) -> typing.List[model.Target]:
|
||||
''' Creates a target from a list of URLs. '''
|
||||
contents = []
|
||||
pagedepths = []
|
||||
for url in urls:
|
||||
if browser == None:
|
||||
contents.append(url)
|
||||
pagedepths.append(pagedepth)
|
||||
else:
|
||||
page = browser.download(url, pagedepth=pagedepth, link_text=link_text)
|
||||
if page.text != '':
|
||||
contents.append(page.text)
|
||||
pagedepths.append(page.pagedepth)
|
||||
else:
|
||||
contents.append(url)
|
||||
pagedepths.append(page.pagedepth)
|
||||
return [ model.Target.create(url, content, pagedepth_inner) for url, content, pagedepth_inner in zip(urls, contents, pagedepths) ]
|
||||
|
||||
|
||||
def print_faculties(faculties: typing.List[model.FacultyEntity]) -> None:
|
||||
''' Prints a list of faculties. '''
|
||||
for f in faculties:
|
||||
print (f.name, f.targets[0].url)
|
||||
for i in f.institutes:
|
||||
print(" I ", i.name, i.targets[0].url)
|
||||
for c in f.chairs:
|
||||
print(" C ", c.name, c.targets[0].url)
|
||||
|
||||
def print_evaluation_flat(truth: typing.List[model.FacultyEntity], prediction: typing.List[model.FacultyEntity]):
|
||||
''' Evaluates a prediction against the truth. '''
|
||||
prediction_flat = _flatten(prediction)
|
||||
truth_flat = _flatten(truth)
|
||||
for key in prediction_flat.keys():
|
||||
print("Evaluating", key)
|
||||
print(" Predictions", len(prediction_flat[key]), "Truth", len(truth_flat[key]))
|
||||
_print_evaluation(truth_flat[key], prediction_flat[key])
|
||||
|
||||
def print_evaluation_hierarchy(truth: typing.List[model.FacultyEntity], prediction: typing.List[model.FacultyEntity]):
|
||||
''' Evaluates a prediction against the truth following the hierarchy. '''
|
||||
mapping = { }
|
||||
counts = { }
|
||||
for p in range(len(prediction)):
|
||||
counts[p] = 0
|
||||
for t in range(len(truth)):
|
||||
mapping[t] = []
|
||||
for p in range(len(prediction)):
|
||||
if truth[t].matches(prediction[p]):
|
||||
counts[p] += 1
|
||||
mapping[t].append(p)
|
||||
for p, count in counts.items():
|
||||
if count == 0:
|
||||
raise Exception("Could not find matching faculty for ", prediction[p].name, prediction[p].targets[0].url, "in truth.")
|
||||
if count > 1:
|
||||
raise Exception("Found", count, "matches for faculty", prediction[p].name, prediction[p].targets[0].url, " in truth.")
|
||||
for tx, px in mapping.items():
|
||||
if len(px) != 1:
|
||||
raise Exception("Found", len(px), "matches for faculty", truth[tx].name, truth[tx].targets[0].url, " in prediction.")
|
||||
t = truth[tx]
|
||||
p = prediction[px[0]]
|
||||
print("Evaluating", t.name, p.name)
|
||||
print(" Institutes")
|
||||
_print_evaluation(t.institutes, p.institutes)
|
||||
print(" Chairs")
|
||||
_print_evaluation(t.chairs, p.chairs)
|
||||
|
||||
|
||||
def _print_evaluation(ts: typing.List[model.Entity], ps: typing.List[model.Entity]):
|
||||
''' Prints the evalution for a list of entities. '''
|
||||
ps = _reset(ps)
|
||||
ts = _reset(ts)
|
||||
for p in ps:
|
||||
found = False
|
||||
for t in ts:
|
||||
if p.matches(t):
|
||||
found = True
|
||||
t.found = True
|
||||
p.found = not found
|
||||
tp = [x for x in ts if x.found == True]
|
||||
fp = [x for x in ps if x.found == True]
|
||||
fn = [x for x in ts if x.found == False]
|
||||
for f in fp:
|
||||
print(" FP", f.name, f.targets[0].url)
|
||||
# for f in fn:
|
||||
# print(" FN", f.name, f.targets[0].url)
|
||||
score = _score(len(tp), len(fp), len(fn))
|
||||
print(" TP", len(tp), "FP", len(fp), "FN", len(fn))
|
||||
print(" P", score[0], "R", score[1], "F1", score[2])
|
||||
|
||||
def _score(tp_val: int, fp_val: int, fn_val: int) -> typing.Tuple[float, float, float]:
|
||||
precision = tp_val / (tp_val + fp_val) if (tp_val + fp_val) > 0 else 0
|
||||
recall = tp_val / (tp_val + fn_val) if (tp_val + fn_val) > 0 else 0
|
||||
f1_score = 2 * (precision * recall) / (precision + recall) if (precision + recall) > 0 else 0
|
||||
return precision, recall, f1_score
|
||||
|
||||
def _reset(entities: typing.List[model.Entity]) -> typing.List[model.Entity]:
|
||||
''' Resets the found flag of all entities. '''
|
||||
for entity in entities:
|
||||
entity.found = False
|
||||
return entities
|
||||
|
||||
def _flatten(faculties: typing.List[model.FacultyEntity]) -> typing.Dict[model.ConceptType, typing.List[model.Entity]]:
|
||||
''' Flattens a list of faculties. '''
|
||||
result = { model.ConceptType.FACULTY: [], model.ConceptType.INSTITUTE: [], model.ConceptType.CHAIR: [] }
|
||||
for faculty in faculties:
|
||||
result[model.ConceptType.FACULTY].append(faculty)
|
||||
for institute in faculty.institutes:
|
||||
result[model.ConceptType.INSTITUTE].append(institute)
|
||||
for chair in faculty.chairs:
|
||||
result[model.ConceptType.CHAIR].append(chair)
|
||||
for key in result.keys():
|
||||
result[key] = _deduplicate(result[key])
|
||||
return result
|
||||
|
||||
def filter_urls(faculties: typing.List[model.FacultyEntity], filter: typing.Callable[[str], bool]):
|
||||
''' Filters the targets of faculties, chairs and institutes by url. '''
|
||||
for faculty in faculties:
|
||||
for target in [ t for t in faculty.targets]:
|
||||
if filter(target.url):
|
||||
faculty.targets.remove(target)
|
||||
for institute in [t for t in faculty.institutes]:
|
||||
for target in [ t for t in institute.targets]:
|
||||
if filter(target.url):
|
||||
institute.targets.remove(target)
|
||||
if len(institute.targets) == 0:
|
||||
faculty.institutes.remove(institute)
|
||||
for chair in [t for t in faculty.chairs]:
|
||||
for target in [ t for t in chair.targets]:
|
||||
if filter(target.url):
|
||||
chair.targets.remove(target)
|
||||
if len(chair.targets) == 0:
|
||||
faculty.chairs.remove(chair)
|
||||
return faculties
|
||||
@@ -0,0 +1,838 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 3,
|
||||
"id": "a0651f51",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import evalutation2\n",
|
||||
"import pickle"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 4,
|
||||
"id": "a1dc4ee7",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"truth = evalutation2.read_truth(\"ude_truth.json\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 5,
|
||||
"id": "dcc109bd",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"faculties = []\n",
|
||||
"institutes = []\n",
|
||||
"chairs = []\n",
|
||||
"for f in truth:\n",
|
||||
" for target in f.targets:\n",
|
||||
" faculties.append(target.url)\n",
|
||||
" for targets in f.institutes:\n",
|
||||
" for institute in targets.targets:\n",
|
||||
" institutes.append(institute.url)\n",
|
||||
" for targets in f.chairs:\n",
|
||||
" for chair in targets.targets:\n",
|
||||
" chairs.append(chair.url) \n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"entities = institutes + chairs\n",
|
||||
"with open(\"entities\", 'wb') as f:\n",
|
||||
" pickle.dump(entities, f)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 6,
|
||||
"id": "12de5855",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"with open(\"entities\", 'rb') as f:\n",
|
||||
" my_list = pickle.load(f)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"id": "8408ecf6",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"['https://www.uni-due.de/cgcr/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/cgcr/index.php',\n",
|
||||
" 'https://www.uni-due.de/anglistik',\n",
|
||||
" 'https://www.uni-due.de/daz-daf/index-en.php',\n",
|
||||
" 'https://www.uni-due.de/daz-daf',\n",
|
||||
" 'https://www.uni-due.de/humanities/geography/index.php',\n",
|
||||
" 'https://www.uni-due.de/geographie',\n",
|
||||
" 'https://www.uni-due.de/humanities/german_studies',\n",
|
||||
" 'https://www.uni-due.de/germanistik',\n",
|
||||
" 'https://www.uni-due.de/humanities/history/index.php',\n",
|
||||
" 'https://www.uni-due.de/geschichte',\n",
|
||||
" 'https://www.uni-due.de/geschichte/index.php',\n",
|
||||
" 'https://www.uni-due.de/kowi/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/kowi',\n",
|
||||
" 'https://www.uni-due.de/kowi/index.php',\n",
|
||||
" 'https://www.uni-due.de/kunst-kuwiss/kuk_home.shtml',\n",
|
||||
" 'https://www.uni-due.de/germanistik/niederlandistik',\n",
|
||||
" 'https://www.uni-due.de/philosophie/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/philosophie',\n",
|
||||
" 'https://www.uni-due.de/humanities/romance_studies',\n",
|
||||
" 'https://www.uni-due.de/romanistik',\n",
|
||||
" 'https://www.uni-due.de/humanities/special_needs_education',\n",
|
||||
" 'https://www.uni-due.de/sonderpaedagogik',\n",
|
||||
" 'https://www.uni-due.de/humanities/protestant_theology/index.php',\n",
|
||||
" 'https://www.uni-due.de/EvangelischeTheologie',\n",
|
||||
" 'https://www.uni-due.de/humanities/catholic_theology/index.shtml',\n",
|
||||
" 'https://www.uni-due.de/katheol',\n",
|
||||
" 'https://www.uni-due.de/turkistik/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/turkistik',\n",
|
||||
" 'https://www.uni-due.de/inkur/index.php',\n",
|
||||
" 'https://www.uni-due.de/inkur',\n",
|
||||
" 'https://www.uni-due.de/isu/isu_englisch.php',\n",
|
||||
" 'https://www.uni-due.de/isu',\n",
|
||||
" 'https://www.uni-due.de/cgcr/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/cgcr/index.php',\n",
|
||||
" 'https://www.uni-due.de/politik/institute.php',\n",
|
||||
" 'https://www.uni-due.de/politik',\n",
|
||||
" 'https://www.uni-due.de/soziologie/department.php',\n",
|
||||
" 'https://www.uni-due.de/soziologie',\n",
|
||||
" 'https://www.uni-due.de/soziooekonomie/home_en',\n",
|
||||
" 'https://www.uni-due.de/soziooekonomie/institut_en',\n",
|
||||
" 'https://www.uni-due.de/soziooekonomie',\n",
|
||||
" 'https://www.uni-due.de/inef/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/inef',\n",
|
||||
" 'https://www.uni-due.de/iaq/en_index.php',\n",
|
||||
" 'https://www.uni-due.de/iaq',\n",
|
||||
" 'https://www.uni-due.de/ibw',\n",
|
||||
" 'https://www.uni-due.de/biwi/erziehungswissenschaft',\n",
|
||||
" 'https://www.uni-due.de/biwi/erziehungswissenschaft.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/psychologie',\n",
|
||||
" 'https://www.uni-due.de/biwi/isp',\n",
|
||||
" 'https://www.uni-due.de/biwi/isp/index.php',\n",
|
||||
" 'https://www.uni-due.de/sport-und-bewegungswissenschaften',\n",
|
||||
" 'https://cinch.uni-due.de/de',\n",
|
||||
" 'https://cinch.uni-due.de',\n",
|
||||
" 'https://www.elfe.uni-due.de/en/news',\n",
|
||||
" 'https://www.elfe.uni-due.de/',\n",
|
||||
" 'https://www.hemf.wiwi.uni-due.de/en',\n",
|
||||
" 'https://www.hemf.wiwi.uni-due.de',\n",
|
||||
" 'https://www.maarc.msm.uni-due.de',\n",
|
||||
" 'https://www.uni-due.de/mathematik/ruhrpad/ruhr.pad',\n",
|
||||
" 'https://www.uni-due.de/mathematik/iem_en.php',\n",
|
||||
" 'https://www.uni-due.de/mathematik/mathematik_iem.php',\n",
|
||||
" 'https://www.esaga.uni-due.de',\n",
|
||||
" 'https://www.uni-due.de/didmath',\n",
|
||||
" 'https://www.uni-due.de/activesites',\n",
|
||||
" 'https://www.uni-due.de/cenide/en',\n",
|
||||
" 'https://www.uni-due.de/cenide/de',\n",
|
||||
" 'https://www.uni-due.de/cenide/netz/en',\n",
|
||||
" 'https://www.uni-due.de/cenide/netz',\n",
|
||||
" 'https://www.uni-due.de/izfb/index_en',\n",
|
||||
" 'https://www.uni-due.de/izfb',\n",
|
||||
" 'https://www.uni-due.de/zmb',\n",
|
||||
" 'https://www.uni-due.de/zwu/start.php',\n",
|
||||
" 'https://www.uni-due.de/zwu',\n",
|
||||
" 'https://www.uni-due.de/zmb',\n",
|
||||
" 'https://www.uni-due.de/zwu/start.php',\n",
|
||||
" 'https://www.uni-due.de/zwu',\n",
|
||||
" 'https://www.uni-due.de/izfb/index_en',\n",
|
||||
" 'https://www.uni-due.de/izfb',\n",
|
||||
" 'https://www.uni-due.de/ipe/index_en.shtml',\n",
|
||||
" 'https://www.uni-due.de/ipe',\n",
|
||||
" 'https://www.uni-due.de/ipe/index.shtml',\n",
|
||||
" 'https://www.uni-due.de/cenide/en',\n",
|
||||
" 'https://www.uni-due.de/cenide/de',\n",
|
||||
" 'https://www.uni-due.de/inam/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/inam',\n",
|
||||
" 'https://www.uni-due.de/inam/index.php',\n",
|
||||
" 'https://www.uni-due.de/cenide/netz/en',\n",
|
||||
" 'https://www.uni-due.de/cenide/netz',\n",
|
||||
" 'https://www.uni-due.de/zwu/start.php',\n",
|
||||
" 'https://www.uni-due.de/zwu',\n",
|
||||
" 'https://www.uni-due.de/zlv/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/zlv',\n",
|
||||
" 'https://www.uni-due.de/cerude/index_neu_en.php',\n",
|
||||
" 'https://www.uni-due.de/cerude',\n",
|
||||
" 'https://www.uni-due.de/css',\n",
|
||||
" 'https://www.uni-due.de/cenide/ican/index_en',\n",
|
||||
" 'https://www.uni-due.de/cenide/ican',\n",
|
||||
" 'https://www.uni-due.de/for-sex/index_en',\n",
|
||||
" 'https://www.uni-due.de/for-sex/index.php',\n",
|
||||
" 'https://www.uni-due.de/igsm/home-en.php',\n",
|
||||
" 'https://www.uni-due.de/igsm',\n",
|
||||
" 'https://www.uni-due.de/igsm/index.php',\n",
|
||||
" 'https://www.uni-due.de/med/pharmakogenetik/index.php',\n",
|
||||
" 'https://www.uni-due.de/med/pharmakogenetik',\n",
|
||||
" 'https://paluno.uni-due.de/en',\n",
|
||||
" 'https://paluno.uni-due.de',\n",
|
||||
" 'https://www.uni-due.de/anglistik/applied_linguistics_didactics/index',\n",
|
||||
" 'https://www.uni-due.de/anglistik/linguistics',\n",
|
||||
" 'https://www.uni-due.de/amerikanistik',\n",
|
||||
" 'https://www.uni-due.de/balc',\n",
|
||||
" 'https://www.uni-due.de/anglistik/english_literary_and_cultural_studies',\n",
|
||||
" 'https://www.uni-due.de/anglistik/postcolonial_studies',\n",
|
||||
" 'https://www.uni-due.de/wigeo/eng_index.php',\n",
|
||||
" 'https://www.uni-due.de/wigeo',\n",
|
||||
" 'https://www.uni-due.de/geographie/sachunterricht/gryl.php',\n",
|
||||
" 'https://www.uni-due.de/germanistik/niederlandistik',\n",
|
||||
" 'https://www.uni-due.de/germanistik/mediaevistik.php',\n",
|
||||
" 'https://www.uni-due.de/germanistik/literaturwissenschaft_literaturdidaktik.php',\n",
|
||||
" 'https://www.uni-due.de/germanistik/pontzen',\n",
|
||||
" 'https://www.uni-due.de/germanistik/morek',\n",
|
||||
" 'https://www.uni-due.de/germanistik/linguistik_sprachdidaktik.php',\n",
|
||||
" 'https://www.uni-due.de/geschichte/abt_didaktik',\n",
|
||||
" 'https://www.uni-due.de/geschichte/abt_alte_geschichte.php',\n",
|
||||
" 'https://www.uni-due.de/geschichte/abt_fruehe_neuzeit.php',\n",
|
||||
" 'https://www.uni-due.de/geschichte/abt_mittelalter.php',\n",
|
||||
" 'https://www.uni-due.de/geschichte/abteilung_kulturgeschichte_des_oekonomischen.php',\n",
|
||||
" 'https://www.uni-due.de/geschichte/abteilung_steinheim_institut.php',\n",
|
||||
" 'https://www.uni-due.de/geschichte/abt_spaetmittelalter',\n",
|
||||
" 'https://www.uni-due.de/kowi/instikom/index.php',\n",
|
||||
" 'https://www.uni-due.de/kowi/theorkom/index.php',\n",
|
||||
" 'https://www.uni-due.de/kowi/mukom/index_en',\n",
|
||||
" 'https://www.uni-due.de/kowi/mukom/index.php',\n",
|
||||
" 'https://www.uni-due.de/philosophie/anthropology',\n",
|
||||
" 'https://www.uni-due.de/philosophie/anthropologie',\n",
|
||||
" 'https://www.uni-due.de/philosophie/politischephilosophie',\n",
|
||||
" 'https://www.uni-due.de/philosophie/theoretischephilosophie_vanriel',\n",
|
||||
" 'https://www.uni-due.de/philosophie/achim_lohmar.php',\n",
|
||||
" 'https://www.uni-due.de/philosophie/bernd_graefrath.php',\n",
|
||||
" 'https://www.uni-due.de/philosophie/praktischephilosophie_hallich/index.php',\n",
|
||||
" 'https://www.uni-due.de/philosophie/dirk_hartmann.php',\n",
|
||||
" 'https://www.uni-due.de/philosophie/ingensiep',\n",
|
||||
" 'https://www.uni-due.de/sonderpaedagogik/ese/index',\n",
|
||||
" 'https://www.uni-due.de/sonderpaedagogik/sprache/index',\n",
|
||||
" 'https://www.uni-due.de/EvangelischeTheologie/aaron_schart.php',\n",
|
||||
" 'https://www.uni-due.de/EvangelischeTheologie/marcel_nieden.php',\n",
|
||||
" 'https://www.uni-due.de/EvangelischeTheologie/st-start.php',\n",
|
||||
" 'https://www.uni-due.de/EvangelischeTheologie/rp-start.php',\n",
|
||||
" 'https://www.uni-due.de/katheol/scherer.php',\n",
|
||||
" 'https://www.uni-due.de/katheol/systheol',\n",
|
||||
" 'https://www.uni-due.de/politik/berendt.php',\n",
|
||||
" 'https://www.uni-due.de/politik/debiel.php',\n",
|
||||
" 'https://www.uni-due.de/in-east/politik_und_gesellschaft_chinas/home.en',\n",
|
||||
" 'https://www.uni-due.de/in-east/politik_und_gesellschaft_chinas',\n",
|
||||
" 'https://www.uni-due.de/politik/martinsen_f.php',\n",
|
||||
" 'https://www.uni-due.de/soziologie/suug.php',\n",
|
||||
" 'https://www.uni-due.de/soziologie/baykara.php',\n",
|
||||
" 'https://www.uni-due.de/soziologie/klammer.php',\n",
|
||||
" 'https://www.uni-due.de/soziologie/ABO.php',\n",
|
||||
" 'https://www.uni-due.de/soziologie/arbeitsgruppe_quack.php',\n",
|
||||
" 'https://www.uni-due.de/soziologie/schnell.php',\n",
|
||||
" 'https://www.uni-due.de/soziologie/steinbach.php',\n",
|
||||
" 'https://www.uni-due.de/iaq/aim.php',\n",
|
||||
" 'https://www.uni-due.de/iaq/azao.php',\n",
|
||||
" 'https://www.uni-due.de/iaq/best.php',\n",
|
||||
" 'https://www.uni-due.de/iaq/prera.php',\n",
|
||||
" 'https://www.uni-due.de/ibw/erziehungswissenschaft_genderperspektive',\n",
|
||||
" 'https://www.uni-due.de/biwi/vet',\n",
|
||||
" 'https://www.uni-due.de/berupaed/en',\n",
|
||||
" 'https://www.uni-due.de/berupaed',\n",
|
||||
" 'https://www.uni-due.de/biwi/eb/index.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/politische-bildung',\n",
|
||||
" 'https://learninglab.uni-due.de',\n",
|
||||
" 'https://www.uni-due.de/informatik/ecg',\n",
|
||||
" 'https://www.uni-due.de/bw-pp',\n",
|
||||
" 'https://www.uni-due.de/colaps',\n",
|
||||
" 'https://www.uni-due.de/allgemeine-didaktik',\n",
|
||||
" 'https://www.uni-due.de/biwi/allgemeine-paedagogik',\n",
|
||||
" 'https://www.uni-due.de/bifo/en',\n",
|
||||
" 'https://www.uni-due.de/bifo',\n",
|
||||
" 'https://www.uni-due.de/biwi/inklusive_paedagogik/index',\n",
|
||||
" 'https://www.uni-due.de/biwi/jugend-und-schulforschung',\n",
|
||||
" 'https://www.uni-due.de/biwi/kindheitsforschung/en_index.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/kindheitsforschung',\n",
|
||||
" 'https://www.uni-due.de/biwi/kindheitsforschung/index.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/boeger',\n",
|
||||
" 'https://www.uni-due.de/biwi/migrations-ungleichheitsforschung',\n",
|
||||
" 'https://www.uni-due.de/biwi/paedagogik/professionsforschung',\n",
|
||||
" 'https://www.uni-due.de/schule_und_jugendhilfe',\n",
|
||||
" 'https://www.uni-due.de/biwi/schulforschung/mammes.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/schulforschung',\n",
|
||||
" 'https://www.uni-due.de/edu-research/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/edu-research/index.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/koenig/start_en.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/koenig/start.php',\n",
|
||||
" 'https://www.uni-due.de/unterrichtsentwicklung/index.php',\n",
|
||||
" 'https://www.uni-due.de/ufo',\n",
|
||||
" 'https://www.uni-due.de/biwi/steins',\n",
|
||||
" 'https://www.uni-due.de/biwi/sprachekognition',\n",
|
||||
" 'https://www.uni-due.de/biwi/aopsy/en//index',\n",
|
||||
" 'https://www.uni-due.de/biwi/aopsy/de/index.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/sb/start.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/sb/index.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/diff',\n",
|
||||
" 'https://www.uni-due.de/biwi/interkulturelle_psychologie/index_engl.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/interkulturelle_psychologie/index.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/psychologie/klinischepsychologie/index.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/llp/en/index.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/llp/de/index.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/lls',\n",
|
||||
" 'https://www.uni-due.de/hpg/klinische_intervention.php',\n",
|
||||
" 'https://www.uni-due.de/dia',\n",
|
||||
" 'https://www.uni-due.de/biwi/hofaecker/start',\n",
|
||||
" 'https://www.uni-due.de/biwi/sozialpolitik/engl_vers',\n",
|
||||
" 'https://www.uni-due.de/biwi/sozialpolitik',\n",
|
||||
" 'https://www.uni-due.de/biwi/wehrheim/wehrheim.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/isp/sozialpaedagogik/thieme.php',\n",
|
||||
" 'https://www.uni-due.de/biwi/isp/tum/index_en',\n",
|
||||
" 'https://www.uni-due.de/biwi/isp/tum',\n",
|
||||
" 'https://www.uni-due.de/sport-und-bewegungswissenschaften/bewegung-und-training-englisch.php',\n",
|
||||
" 'https://www.uni-due.de/sport-und-bewegungswissenschaften/bewegung-und-training.php',\n",
|
||||
" 'https://www.uni-due.de/sport-und-bewegungswissenschaften/dlls.php',\n",
|
||||
" 'https://www.uni-due.de/sport-und-bewegungswissenschaften/sozialwissenschaften_des_sports.php',\n",
|
||||
" 'https://www.uni-due.de/sport-und-bewegungswissenschaften/sportpaedagogik_sportdidaktik.php',\n",
|
||||
" 'https://www.mm.wiwi.uni-due.de',\n",
|
||||
" 'https://www.wipo.wiwi.uni-due.de/en/profile',\n",
|
||||
" 'https://www.wipo.wiwi.uni-due.de/profil',\n",
|
||||
" 'https://www.wpar.wiwi.uni-due.de',\n",
|
||||
" 'https://www.exp.wiwi.uni-due.de',\n",
|
||||
" 'https://www.oek.wiwi.uni-due.de/en',\n",
|
||||
" 'https://www.oek.wiwi.uni-due.de',\n",
|
||||
" 'https://www.goek.wiwi.uni-due.de/en',\n",
|
||||
" 'https://www.goek.wiwi.uni-due.de',\n",
|
||||
" 'https://www.iwb.wiwi.uni-due.de/en',\n",
|
||||
" 'https://www.iwb.wiwi.uni-due.de',\n",
|
||||
" 'https://www.makro.wiwi.uni-due.de',\n",
|
||||
" 'https://www.mikro.wiwi.uni-due.de/en',\n",
|
||||
" 'https://www.mikro.wiwi.uni-due.de',\n",
|
||||
" 'https://www.pubecon.wiwi.uni-due.de/en',\n",
|
||||
" 'https://www.pubecon.wiwi.uni-due.de',\n",
|
||||
" 'https://www.stat.wiwi.uni-due.de/en',\n",
|
||||
" 'https://www.stat.wiwi.uni-due.de',\n",
|
||||
" 'https://amg.wiwi.uni-due.de/en/home',\n",
|
||||
" 'https://amg.wiwi.uni-due.de',\n",
|
||||
" 'https://www.labor.wiwi.uni-due.de',\n",
|
||||
" 'https://www.labor.wiwi.uni-due.de/team/sebastian-otten',\n",
|
||||
" 'https://www.labor.wiwi.uni-due.de/team/julia-bredtmann',\n",
|
||||
" 'https://futureofwork.wiwi.uni-due.de/',\n",
|
||||
" 'https://www.wida.wiwi.uni-due.de/en',\n",
|
||||
" 'https://www.wida.wiwi.uni-due.de',\n",
|
||||
" 'https://www.lef.wiwi.uni-due.de/en',\n",
|
||||
" 'https://www.lef.wiwi.uni-due.de',\n",
|
||||
" 'https://www.ewl.wiwi.uni-due.de/en',\n",
|
||||
" 'https://www.ewl.wiwi.uni-due.de',\n",
|
||||
" 'https://www.fin.wiwi.uni-due.de/en',\n",
|
||||
" 'https://www.fin.wiwi.uni-due.de',\n",
|
||||
" 'https://www.irl.wiwi.uni-due.de',\n",
|
||||
" 'https://www.marketing.wiwi.uni-due.de',\n",
|
||||
" 'https://www.pim.wiwi.uni-due.de/profil',\n",
|
||||
" 'https://www.steuern.wiwi.uni-due.de/en/1',\n",
|
||||
" 'https://www.steuern.wiwi.uni-due.de',\n",
|
||||
" 'https://www.uee.wiwi.uni-due.de/en',\n",
|
||||
" 'https://www.uee.wiwi.uni-due.de',\n",
|
||||
" 'https://www.abwl.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.abwl.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.bafi.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.bafi.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.bwsl.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.dmh.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.dmh.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.finance.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.finance.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.ircg.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.ircg.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.log.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.log.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.marketing.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.marketing.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.puu.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.puu.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.pl.msm.uni-due.de/en',\n",
|
||||
" 'https://www.pl.msm.uni-due.de',\n",
|
||||
" 'https://www.scm.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.scm.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.rwpc.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.rwpc.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.so.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.so.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.mc.msm.uni-due.de/en',\n",
|
||||
" 'https://www.mc.msm.uni-due.de/',\n",
|
||||
" 'https://www.insurance.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.mikro.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.mikro.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.makro.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.makro.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.qmw.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.qmw.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.vwl.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.vwl.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.neg.msm.uni-due.de/en/profile',\n",
|
||||
" 'https://www.neg.msm.uni-due.de/profil',\n",
|
||||
" 'https://www.wipaed.msm.uni-due.de/en/startseite',\n",
|
||||
" 'https://www.wipaed.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.china.msm.uni-due.de/en/chair-for-east-asian-economic-studies-china',\n",
|
||||
" 'https://www.china.msm.uni-due.de/chair-for-east-asian-economic-studies-china',\n",
|
||||
" 'https://tdr.informatik.uni-due.de/en',\n",
|
||||
" 'https://tdr.informatik.uni-due.de',\n",
|
||||
" 'https://se.informatik.uni-due.de',\n",
|
||||
" 'https://www.esaga.uni-due.de/ag/ludwig',\n",
|
||||
" 'https://www.esaga.uni-due.de/ag/hein',\n",
|
||||
" 'https://www.esaga.uni-due.de/ag/heinloth',\n",
|
||||
" 'https://www.esaga.uni-due.de/ag/levine',\n",
|
||||
" 'https://www.esaga.uni-due.de/ag/greb',\n",
|
||||
" 'https://www.esaga.uni-due.de/ag/bertolini',\n",
|
||||
" 'https://www.esaga.uni-due.de/ag/kohlhaase',\n",
|
||||
" 'https://www.esaga.uni-due.de/ag/paskunas',\n",
|
||||
" 'https://www.esaga.uni-due.de/ag/goertz',\n",
|
||||
" 'https://www.esaga.uni-due.de/ag/sprang',\n",
|
||||
" 'https://www.uni-due.de/didmath/ag_barzel',\n",
|
||||
" 'https://www.uni-due.de/didmath/mitarbeiter_buechter',\n",
|
||||
" 'https://www.uni-due.de/didmath/ag_schacht',\n",
|
||||
" 'https://www.uni-due.de/didmath/ag_scherer',\n",
|
||||
" 'https://www.uni-due.de/mathematik/ag_wittbold/ag_wittbold_english',\n",
|
||||
" 'https://www.uni-due.de/mathematik/ag_wittbold',\n",
|
||||
" 'https://www.uni-due.de/mathematik/aggastel',\n",
|
||||
" 'https://www.uni-due.de/mathematik/ag_neff/index_en',\n",
|
||||
" 'https://www.uni-due.de/mathematik/ag_neff',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agdierkes',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agdierkes/index.php',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agtoerner',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agweiss',\n",
|
||||
" 'https://www.uni-due.de/mathematik/ag_scheven.shtml',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agpozzi/pozzi',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agkraus',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agkraus/index.html',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agstarke',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agyousept/yousept.php',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agroesch',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agschultz/arbeitsgruppe_engl.php',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agschultz',\n",
|
||||
" 'https://www.uni-due.de/mathematik/ag_belomestny/urusov',\n",
|
||||
" 'https://www.uni-due.de/mathematik/ag_stochastische_analysis',\n",
|
||||
" 'https://www.uni-due.de/mathematik/ag_winter',\n",
|
||||
" 'https://www.uni-due.de/agbovensiepen',\n",
|
||||
" 'https://www.uni-due.de/ag-campen/index.en.php',\n",
|
||||
" 'https://www.uni-due.de/ag-campen',\n",
|
||||
" 'https://www.uni-due.de/agfarle/index_enu.php',\n",
|
||||
" 'https://www.uni-due.de/agfarle',\n",
|
||||
" 'https://www.uni-due.de/physik/gruber',\n",
|
||||
" 'https://www.uni-due.de/ag-hvh/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/ag-hvh',\n",
|
||||
" 'https://www.uni-due.de/ag-hvh/index.php',\n",
|
||||
" 'https://www.uni-due.de/aglorke',\n",
|
||||
" 'https://www.uni-due.de/ag-mittendorff/home_en.php',\n",
|
||||
" 'https://www.uni-due.de/ag-mittendorff',\n",
|
||||
" 'https://www.uni-due.de/ag-nienhaus',\n",
|
||||
" 'https://www.uni-due.de/physik/schleberger/info_english',\n",
|
||||
" 'https://www.uni-due.de/physik/schleberger',\n",
|
||||
" 'https://www.uni-due.de/ag-schmid',\n",
|
||||
" 'https://www.uni-due.de/agschneider/index-en.shtml',\n",
|
||||
" 'https://www.uni-due.de/agschneider',\n",
|
||||
" 'https://www.uni-due.de/physik/wende/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/physik/wende',\n",
|
||||
" 'https://www.uni-due.de/physik/agw/home.php',\n",
|
||||
" 'https://www.uni-due.de/physik/agw/index.php',\n",
|
||||
" 'https://www.uni-due.de/physik/twist',\n",
|
||||
" 'https://www.uni-due.de/physik/ag_guhr/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/physik/ag_guhr',\n",
|
||||
" 'https://www.uni-due.de/tqp/index_en.shtml',\n",
|
||||
" 'https://www.uni-due.de/tqp',\n",
|
||||
" 'https://www.uni-due.de/thp/index_en.shtml',\n",
|
||||
" 'https://www.uni-due.de/thp',\n",
|
||||
" 'https://www.uni-due.de/ptt',\n",
|
||||
" 'https://www.uni-due.de/physik/kratzer/index_eng.php',\n",
|
||||
" 'https://www.uni-due.de/physik/kratzer',\n",
|
||||
" 'https://www.uni-due.de/physik/agk/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/physik/agk',\n",
|
||||
" 'https://www.uni-due.de/physik/pentcheva/highlights_en',\n",
|
||||
" 'https://www.uni-due.de/physik/pentcheva',\n",
|
||||
" 'https://www.uni-due.de/comphys/index_en.shtml',\n",
|
||||
" 'https://www.uni-due.de/comphys',\n",
|
||||
" 'https://www.uni-due.de/physik/parteli',\n",
|
||||
" 'https://www.uni-due.de/physik/pentcheva',\n",
|
||||
" 'https://www.uni-due.de/didaktik_der_physik/haertig-eng.php',\n",
|
||||
" 'https://www.uni-due.de/didaktik_der_physik/haertig.php',\n",
|
||||
" 'https://www.uni-due.de/didaktik_der_physik/ForschungTheyssen.shtml',\n",
|
||||
" 'https://www.uni-due.de/tech3chem',\n",
|
||||
" 'https://www.uni-due.de/barcikowski-group',\n",
|
||||
" 'https://www.uni-due.de/ag-campen/index.en.php',\n",
|
||||
" 'https://www.uni-due.de/agbovensiepen',\n",
|
||||
" 'https://www.uni-due.de/ag-campen',\n",
|
||||
" 'https://www.uni-due.de/chemie/akdomke',\n",
|
||||
" 'https://www.uni-due.de/schluecker-lab/profil.shtml',\n",
|
||||
" 'https://www.uni-due.de/chemie/akgiese',\n",
|
||||
" 'https://www.uni-due.de/chemie/ak_gutmann',\n",
|
||||
" 'https://www.uni-due.de/akhaberhauer',\n",
|
||||
" 'https://www.uni-due.de/zmb/chemical-biology',\n",
|
||||
" 'https://www.uni-due.de/zmb/molecular-biology-knauer/index.php',\n",
|
||||
" 'https://www.uni-due.de/schluecker-lab',\n",
|
||||
" 'https://www.uni-due.de/iac',\n",
|
||||
" 'https://www.uni-due.de/aac',\n",
|
||||
" 'https://www.uni-due.de/chemie/ak_schrader/index_en',\n",
|
||||
" 'https://www.uni-due.de/chemie/ak_schrader/index.php',\n",
|
||||
" 'https://www.uni-due.de/empi/rf/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/empi/rf',\n",
|
||||
" 'https://www.uni-due.de/ak_schulz/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/empi/cfd/en/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/empi/cfd',\n",
|
||||
" 'https://www.uni-due.de/nst/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/nst',\n",
|
||||
" 'https://www.uni-due.de/empi/cfd/tomo',\n",
|
||||
" 'https://www.uni-due.de/wet/index_en.shtml',\n",
|
||||
" 'https://www.uni-due.de/wet/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/wet',\n",
|
||||
" 'https://www.uni-due.de/reichenberger-group',\n",
|
||||
" 'https://www.uni-due.de/empi/aqm/en',\n",
|
||||
" 'https://www.uni-due.de/empi/aqm',\n",
|
||||
" 'https://www.uni-due.de/empi/pst',\n",
|
||||
" 'https://www.uni-due.de/tech2chem',\n",
|
||||
" 'https://www.uni-due.de/physik/wende/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/physik/wende',\n",
|
||||
" 'https://www.uni-due.de/akniemeyer/index.php',\n",
|
||||
" 'https://www.uni-due.de/chemie/voskuhl',\n",
|
||||
" 'https://www.uni-due.de/chemie/ak_disch/ak_disch.php',\n",
|
||||
" 'https://www.uni-due.de/chemie/ak_exner',\n",
|
||||
" 'https://www.uni-due.de/umb/enzym_home.shtml',\n",
|
||||
" 'https://www.uni-due.de/umb',\n",
|
||||
" 'https://www.uni-due.de/tech3chem/index.php',\n",
|
||||
" 'https://www.uni-due.de/chemiedidaktik',\n",
|
||||
" 'https://www.uni-due.de/chemiedidaktik/09_forschung_agrumann.shtml',\n",
|
||||
" 'https://www.uni-due.de/chemiedidaktik/09_forschung_agsumfleth.shtml',\n",
|
||||
" 'https://www.uni-due.de/chemiedidaktik/agwalpuski_en.',\n",
|
||||
" 'https://www.uni-due.de/chemiedidaktik/agwalpuski',\n",
|
||||
" 'https://www.uni-due.de/probst-lab',\n",
|
||||
" 'https://www.uni-due.de/chemie/galstyan-lab/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/chemie/galstyan-lab',\n",
|
||||
" 'https://www.uni-due.de/chemie/ak_epple/en/index.php',\n",
|
||||
" 'https://www.uni-due.de/chemie/ak_epple',\n",
|
||||
" 'https://www.uni-due.de/chemie/ak_jansen',\n",
|
||||
" 'https://www.uni-due.de/chemie/ag_mayer',\n",
|
||||
" 'https://www.uni-due.de/zmb/bioinformatics-computational-biophysics',\n",
|
||||
" 'https://www.uni-due.de/zmb/bionanotechnology/index.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/chemical-biology',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/andrea-vortkamp.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/barbara-gruener.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/dirk-matthias-hermann.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/farnusch-kaschani.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/silvia-vega-rubin-de-celis.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/mechanistic-cell-biology/index.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/andrea-musacchio.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/microbiology',\n",
|
||||
" 'https://www.uni-due.de/zmb/molecular-biology-meyer',\n",
|
||||
" 'https://www.uni-due.de/zmb/molecular-biology-knauer/index.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/molecular-genetics-westermann/index.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/molecular-genetics-boos/index.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/molecular-cell-biology',\n",
|
||||
" 'https://www.uni-due.de/zmb/molecular-cell-biology/index.html',\n",
|
||||
" 'https://www.uni-due.de/zmb/molecular-cell-meyer',\n",
|
||||
" 'https://www.uni-due.de/zmb/molecular-cell-meyer/index.html',\n",
|
||||
" 'https://www.uni-due.de/zmb/structural-medicinal-biochemistry/index.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/strukturelle-medizinische-biochemie/index.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/daniel-hoffmann.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/barbara-sacca.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/jens-voskuhl.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/jens-siveke.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/basant-kumar-thakur.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/ulrike-hendgen-cotta.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/markus-kaiser.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/tienush-rassaf.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/dirk-schadendorf.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/dagmar-fuehrer-sakel.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/christian-reinhardt.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/adalbert-krawczyk-zmb.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/christoph-kleinschnitz.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/ken-herrmann-2.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/martin-schuler.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/erich-gulbins.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/developmental-biology/index.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/manuela-wuelling-zmb.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/alexander-probst.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/elke-cario.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/ivo-bendix.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/josephine-herz.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/farnoush-farahpour.php',\n",
|
||||
" 'https://www.uni-due.de/farahpourlab/index.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/bernd-giebel-2.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/thomas-schrader.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/nina-schulze-zmb.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/elisabeth-littwitz-salomon.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/stefanie-flohe.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/astrid-westendorf.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/matthias-epple.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/katharina-fleischhauer.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/peter-horn.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/gunther-wennemuth.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/ralf-kueppers.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/matthias-gunzer.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/karl-sebastian-lang.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/jan-buer.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/winfried-siffert.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/hans-werner-ingensiep.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/joachim-fandrey.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/katja-ferenz.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/ulf-dittmer.php',\n",
|
||||
" 'https://www.uni-due.de/virologie/ag_sutter.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/anke-hinney.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/doris-hellerschmied-jelinek.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/johann-matschke.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/hemmo-meyer.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/shirley-knauer.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/sebastian-schluecker.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/verena-jendrossek.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/perihan-nalbant.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/bettina-siebers.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/christian-johannes.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/stefan-westermann.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/dominik-boos.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/wiebke-hansen.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/alexander-schramm.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/heike-heuer.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/annette-paschen-zmb.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/nicole-duenker.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/dietmar-lohmann.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/sven-brandau.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/jadwiga-jablonska-koch.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/anzhela-galstyan.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/katharina-lueckerath.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/george-iliakis.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/carsten-kirschning.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/peter-bayer.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/stefan-raunser.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/robert-huber.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/jochen-niemeyer.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/stephan-barcikowski.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/kai-exner.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/samuel-pena-llopis.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/bjoern-scheffler.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/claere-von-neubeck-zmb.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/sebastian-bauer-zmb.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/juergen-becker.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/alexander-roesch.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/barbara-gruenwald.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/alpaslan-tasdogan.php',\n",
|
||||
" 'https://www.uni-due.de/zmb/members/diana-klein-zmb.php',\n",
|
||||
" 'https://www.uni-due.de/aquatic_ecology',\n",
|
||||
" 'https://www.uni-due.de/aquatische_oekologie',\n",
|
||||
" 'https://www.uni-due.de/zmb/molecular-cell-biology',\n",
|
||||
" 'https://www.uni-due.de/leeselab/leeselab',\n",
|
||||
" 'https://www.uni-due.de/aquatische_oekosystemforschung',\n",
|
||||
" 'https://www.uni-due.de/biodiversitaet',\n",
|
||||
" 'https://www.uni-due.de/biologiedidaktik',\n",
|
||||
" 'https://www.uni-due.de/berll/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/berll',\n",
|
||||
" 'https://www.uni-due.de/biologie/eukaryotische-mikrobiologie/index.php',\n",
|
||||
" 'https://www.uni-due.de/fluss_und_auenoekologie/index.php',\n",
|
||||
" 'https://www.uni-due.de/interdisziplinaerer_umweltschutz/index.php',\n",
|
||||
" 'https://www.uni-due.de/biologie/oekotoxikologie/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/phycology',\n",
|
||||
" 'https://www.uni-due.de/phykologie',\n",
|
||||
" 'https://www.uni-due.de/biologie/fakultaet/seniorprofessur.php',\n",
|
||||
" 'https://www.uni-due.de/biologie/angewandte_bodenkunde',\n",
|
||||
" 'https://www.uni-due.de/klimatologie',\n",
|
||||
" 'https://www.uni-due.de/zoologie',\n",
|
||||
" 'https://www.uni-due.de/fertigungstechnik',\n",
|
||||
" 'https://www.uni-due.de/kkm/index-en.php',\n",
|
||||
" 'https://www.uni-due.de/kkm',\n",
|
||||
" 'https://www.uni-due.de/pep',\n",
|
||||
" 'https://www.uni-due.de/tul/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/tul',\n",
|
||||
" 'https://www.uni-due.de/tul/index.php',\n",
|
||||
" 'https://www.uni-due.de/vip',\n",
|
||||
" 'https://www.uni-due.de/tech3chem',\n",
|
||||
" 'https://www.uni-due.de/barcikowski-group',\n",
|
||||
" 'https://www.uni-due.de/empi/rf/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/empi/rf',\n",
|
||||
" 'https://www.uni-due.de/empi/cfd/en/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/empi/cfd',\n",
|
||||
" 'https://www.uni-due.de/nst/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/nst',\n",
|
||||
" 'https://www.uni-due.de/empi/cfd/tomo',\n",
|
||||
" 'https://www.uni-due.de/wet/index_en.shtml',\n",
|
||||
" 'https://www.uni-due.de/wet',\n",
|
||||
" 'https://www.uni-due.de/reichenberger-group',\n",
|
||||
" 'https://www.uni-due.de/empi/aqm/schierning-cv-en',\n",
|
||||
" 'https://www.uni-due.de/empi/aqm/schierning-cv',\n",
|
||||
" 'https://www.uni-due.de/empi/pst',\n",
|
||||
" 'https://www.uni-due.de/tech2chem',\n",
|
||||
" 'https://www.uni-due.de/physik/wende/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/physik/wende',\n",
|
||||
" 'https://sitm.ris.uni-due.de',\n",
|
||||
" 'https://www.uni-due.de/ISMT/index_en.shtml',\n",
|
||||
" 'https://www.uni-due.de/IST',\n",
|
||||
" 'https://www.uni-due.de/innovation/english',\n",
|
||||
" 'https://www.uni-due.de/innovation',\n",
|
||||
" 'https://www.so.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.so.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.uni-due.de/ets/index_en',\n",
|
||||
" 'https://www.uni-due.de/ets',\n",
|
||||
" 'https://www.uni-due.de/wigeo/juchelka.php',\n",
|
||||
" 'https://www.uni-due.de/wigeo',\n",
|
||||
" 'https://www.uni-due.de/bautechnik',\n",
|
||||
" 'https://www.log.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.log.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.uni-due.de/baubetrieb',\n",
|
||||
" 'https://www.scm.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.scm.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.nes.uni-due.de',\n",
|
||||
" 'https://www.uni-due.de/tul/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/tul',\n",
|
||||
" 'https://www.uni-due.de/iam',\n",
|
||||
" 'https://www.dmh.msm.uni-due.de/en/home',\n",
|
||||
" 'https://www.dmh.msm.uni-due.de/startseite',\n",
|
||||
" 'https://www.uni-due.de/mechatronik/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/mechatronik',\n",
|
||||
" 'https://www.uni-due.de/ptt',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agschultz/arbeitsgruppe_engl.php',\n",
|
||||
" 'https://www.uni-due.de/mathematik/agschultz/index.php',\n",
|
||||
" 'https://www.ewl.wiwi.uni-due.de/en',\n",
|
||||
" 'https://www.ewl.wiwi.uni-due.de',\n",
|
||||
" 'https://www.uni-due.de/imobis',\n",
|
||||
" 'https://www.pim.wiwi.uni-due.de/profil',\n",
|
||||
" 'https://www.uni-due.de/controlling',\n",
|
||||
" 'https://www.uni-due.de/pom/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/pom',\n",
|
||||
" 'https://www.uni-due.de/ate/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/ate',\n",
|
||||
" 'https://www.uni-due.de/aks/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/aks',\n",
|
||||
" 'https://www.uni-due.de/bhe/index_en',\n",
|
||||
" 'https://www.uni-due.de/bhe',\n",
|
||||
" 'https://www.dsv.uni-due.de/en/home',\n",
|
||||
" 'https://www.dsv.uni-due.de/de/startseite',\n",
|
||||
" 'https://www.uni-due.de/ees/index.en.php',\n",
|
||||
" 'https://www.uni-due.de/ees',\n",
|
||||
" 'https://www.uni-due.de/ebs',\n",
|
||||
" 'https://www.uni-due.de/en/index.php',\n",
|
||||
" 'https://www.uni-due.de/energietechnik',\n",
|
||||
" 'https://www.uni-due.de/ets/index_en',\n",
|
||||
" 'https://www.uni-due.de/ets/index',\n",
|
||||
" 'https://www.uni-due.de/lee',\n",
|
||||
" 'https://www.uni-due.de/geotechnik',\n",
|
||||
" 'https://www.uni-due.de/ingmath',\n",
|
||||
" 'https://www.uni-due.de/massivbau',\n",
|
||||
" 'https://www.uni-due.de/materials/index_eng.shtml',\n",
|
||||
" 'https://www.uni-due.de/materials',\n",
|
||||
" 'https://www.uni-due.de/mfi/index_en',\n",
|
||||
" 'https://www.uni-due.de/mfi',\n",
|
||||
" 'https://www.uni-due.de/mechanika/index_englisch.php',\n",
|
||||
" 'https://www.uni-due.de/mechanika',\n",
|
||||
" 'https://www.uni-due.de/mechanika/index.php',\n",
|
||||
" 'https://www.uni-due.de/mechanikb',\n",
|
||||
" 'https://www.uni-due.de/Wassertechnik/Home_englisch.shtml',\n",
|
||||
" 'https://www.uni-due.de/Wassertechnik',\n",
|
||||
" 'https://www.uni-due.de/iml',\n",
|
||||
" 'https://www.uni-due.de/muu',\n",
|
||||
" 'https://www.uni-due.de/nts',\n",
|
||||
" 'https://www.uni-due.de/oe',\n",
|
||||
" 'https://www.uni-due.de/oe/de',\n",
|
||||
" 'https://www.uni-due.de/abfall/essen/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/abfall/essen',\n",
|
||||
" 'https://www.uni-due.de/statik/en',\n",
|
||||
" 'https://www.uni-due.de/statik/de',\n",
|
||||
" 'https://www.uni-due.de/srs/index_en.shtml',\n",
|
||||
" 'https://www.uni-due.de/srs',\n",
|
||||
" 'https://www.uni-due.de/tm',\n",
|
||||
" 'https://www.uni-due.de/smt/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/smt',\n",
|
||||
" 'https://www.uni-due.de/tud',\n",
|
||||
" 'https://www.uni-due.de/verfahrenstechnik/profile.shtml',\n",
|
||||
" 'https://www.uni-due.de/verfahrenstechnik',\n",
|
||||
" 'https://www.uni-due.de/empi/td/en',\n",
|
||||
" 'https://www.uni-due.de/empi/td',\n",
|
||||
" 'https://www.uni-due.de/tul/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/tul/index.php',\n",
|
||||
" 'https://www.uni-due.de/wasserbau/homepage.php',\n",
|
||||
" 'https://www.uni-due.de/wasserbau',\n",
|
||||
" 'https://www.uni-due.de/werkstofftechnik/index_en.shtml',\n",
|
||||
" 'https://www.uni-due.de/werkstofftechnik',\n",
|
||||
" 'https://www.uni-due.de/bauwissenschaften/de',\n",
|
||||
" 'https://syssec.informatik.uni-due.de/en',\n",
|
||||
" 'https://syssec.informatik.uni-due.de',\n",
|
||||
" 'https://softec.ris.uni-due.de/en',\n",
|
||||
" 'https://softec.ris.uni-due.de',\n",
|
||||
" 'https://s3.paluno.uni-due.de',\n",
|
||||
" 'https://se.informatik.uni-due.de',\n",
|
||||
" 'https://www.uni-due.de/swe/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/swe',\n",
|
||||
" 'https://www.nes.uni-due.de',\n",
|
||||
" 'https://sse.uni-due.de/en',\n",
|
||||
" 'https://sse.uni-due.de',\n",
|
||||
" 'https://ncs.informatik.uni-due.de',\n",
|
||||
" 'https://www.uni-due.de/es/en/en_home.php',\n",
|
||||
" 'https://www.uni-due.de/es',\n",
|
||||
" 'https://hci.informatik.uni-due.de/en',\n",
|
||||
" 'https://hci.informatik.uni-due.de',\n",
|
||||
" 'https://www.vs.uni-due.de/en',\n",
|
||||
" 'https://www.vs.uni-due.de',\n",
|
||||
" 'https://ai.ris.uni-due.de',\n",
|
||||
" 'https://www.uni-due.de/datascience',\n",
|
||||
" 'https://ddi.informatik.uni-due.de/en',\n",
|
||||
" 'https://ddi.informatik.uni-due.de',\n",
|
||||
" 'https://www.uni-due.de/fmi/index_en',\n",
|
||||
" 'https://www.uni-due.de/fmi',\n",
|
||||
" 'https://tdr.informatik.uni-due.de/en',\n",
|
||||
" 'https://tdr.informatik.uni-due.de',\n",
|
||||
" 'https://www.uni-due.de/theoinf/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/theoinf',\n",
|
||||
" 'https://www.vs.uni-due.de',\n",
|
||||
" 'https://www.uni-due.de/kognitionspsychologie/index_eng',\n",
|
||||
" 'https://www.uni-due.de/kognitionspsychologie',\n",
|
||||
" 'https://www.uni-due.de/interaktivesysteme/home_en',\n",
|
||||
" 'https://www.uni-due.de/interaktivesysteme',\n",
|
||||
" 'https://www.uni-due.de/psychologische-forschungsmethoden/index_eng.php',\n",
|
||||
" 'https://www.uni-due.de/psychologische-forschungsmethoden',\n",
|
||||
" 'https://www.uni-due.de/media-psych-edu/index_en.php',\n",
|
||||
" 'https://www.uni-due.de/media-psych-edu',\n",
|
||||
" 'https://www.uni-due.de/soco',\n",
|
||||
" 'https://www.uni-due.de/sozialpsychologie',\n",
|
||||
" 'https://www.uni-due.de/wirtschaftspsychologie/home_e.php',\n",
|
||||
" 'https://www.uni-due.de/wirtschaftspsychologie',\n",
|
||||
" 'https://www.uni-due.de/is/index_en',\n",
|
||||
" 'https://www.uni-due.de/is',\n",
|
||||
" 'https://sse.uni-due.de/en/about-us/team/dr-dominik-helm',\n",
|
||||
" 'https://sse.uni-due.de/ueber-uns/team/dr-dominik-helm',\n",
|
||||
" 'https://app.ris.uni-due.de/en',\n",
|
||||
" 'https://app.ris.uni-due.de',\n",
|
||||
" 'https://iis.ris.uni-due.de/en',\n",
|
||||
" 'https://iis.ris.uni-due.de',\n",
|
||||
" 'https://sitm.ris.uni-due.de',\n",
|
||||
" 'https://sust.ris.uni-due.de',\n",
|
||||
" 'https://tm.ris.uni-due.de',\n",
|
||||
" 'https://umo.ris.uni-due.de/en',\n",
|
||||
" 'https://umo.ris.uni-due.de']"
|
||||
]
|
||||
},
|
||||
"execution_count": 7,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"my_list"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "airflow",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3",
|
||||
"version": "3.11.0"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
#
|
||||
# This file contains the classes that represent our basic data model,
|
||||
# we use pydantic to define the data model so we can easily cache it
|
||||
# in a simple sqlite database.
|
||||
#
|
||||
import enum
|
||||
import typing
|
||||
import pydantic
|
||||
import hashlib
|
||||
|
||||
class Language(enum.Enum):
|
||||
''' Represents the language of a concept. '''
|
||||
DE = 'de'
|
||||
EN = 'en'
|
||||
|
||||
class ConceptType(enum.Enum):
|
||||
''' Represents the type of a concept. '''
|
||||
FACULTY = 'faculty'
|
||||
INSTITUTE = 'institute'
|
||||
CHAIR = 'chair'
|
||||
|
||||
class Concept(pydantic.BaseModel):
|
||||
''' A container for concepts with singular, plural and abbreviations. '''
|
||||
language: Language
|
||||
singular: str
|
||||
plural: str
|
||||
abbreviations: typing.List[str] = pydantic.Field(default=[])
|
||||
type: ConceptType
|
||||
def __hash__(self):
|
||||
return hash(self.singular)
|
||||
|
||||
class Resource(pydantic.BaseModel):
|
||||
url: str
|
||||
pagedepth: int
|
||||
text: str
|
||||
|
||||
class Link(Resource):
|
||||
''' Represents a link with a URL, a text on a page. '''
|
||||
wrapper: bool = pydantic.Field(default=False)
|
||||
|
||||
class Page(Resource):
|
||||
''' Represents a page with a URL, text and links. '''
|
||||
links: typing.List[Link]
|
||||
language: Language = pydantic.Field(default=Language.DE, exclude=True)
|
||||
headings: typing.List[str] = pydantic.Field(default=[], exclude=True)
|
||||
found_link_text_flag: bool
|
||||
ignore_flag: bool = pydantic.Field(default=False)
|
||||
|
||||
class AggregatorPage(Page):
|
||||
''' Represents a page that is used as an aggregator. '''
|
||||
parent: str = pydantic.Field(default='')
|
||||
parent_link: str = pydantic.Field(default='')
|
||||
concept: Concept
|
||||
children: typing.List[Link] = pydantic.Field(default=[])
|
||||
|
||||
class EntityDetail(pydantic.BaseModel):
|
||||
''' Represents a detailed entity '''
|
||||
name: str = pydantic.Field(default='')
|
||||
url: typing.List[str]
|
||||
content: typing.List[str]
|
||||
hash: typing.List[str]
|
||||
found: bool = pydantic.Field(default=False)
|
||||
def mark(self, value: bool):
|
||||
if isinstance(value, bool):
|
||||
self.found = value
|
||||
|
||||
class Target(Resource):
|
||||
''' Represents a target with a URL, text and a hash. '''
|
||||
hash: str
|
||||
|
||||
def matches(self, other: 'Target') -> bool:
|
||||
''' Checks if the content matches this content. '''
|
||||
if self.url == other.url:
|
||||
return True
|
||||
if self.hash == other.hash:
|
||||
return self.text == other.text
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def create(cls, url: str, text: str, pagedepth: int):
|
||||
''' Creates a target from a resource. '''
|
||||
hash = hashlib.sha256()
|
||||
hash.update(text.encode('utf-8'))
|
||||
return cls(url = url, pagedepth = pagedepth, text = text, hash = hash.hexdigest())
|
||||
|
||||
|
||||
class Entity(pydantic.BaseModel):
|
||||
''' Base class for an entity. '''
|
||||
targets: typing.List[Target]
|
||||
name: str = pydantic.Field(default='')
|
||||
found: bool = pydantic.Field(default=False)
|
||||
|
||||
def equals(self, other: 'Entity') -> bool:
|
||||
''' Checks if all targets match a target. '''
|
||||
for target in self.targets:
|
||||
if not any(target.matches(other_target) for other_target in other.targets):
|
||||
return False
|
||||
for other_target in other.targets:
|
||||
if not any(other_target.matches(target) for target in self.targets):
|
||||
return False
|
||||
return True
|
||||
|
||||
def matches(self, other: 'Entity') -> bool:
|
||||
''' Checks if any target matches the targets. '''
|
||||
for target in self.targets:
|
||||
if any(target.matches(other_target) for other_target in other.targets):
|
||||
return True
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def create(cls, name: str, targets: typing.List[Target]):
|
||||
''' Creates an entity from a name and a list of targets. '''
|
||||
return cls(name = name, targets = targets)
|
||||
|
||||
class ChairEntity(Entity):
|
||||
''' Represents a chair entity. '''
|
||||
pass
|
||||
|
||||
class InsituteEntity(Entity):
|
||||
''' Represents an institute entity. '''
|
||||
pass
|
||||
|
||||
class FacultyEntity(Entity):
|
||||
''' Represents a faculty entity. '''
|
||||
chairs: typing.List['ChairEntity'] = pydantic.Field(default=[])
|
||||
institutes: typing.List['InsituteEntity'] = pydantic.Field(default=[])
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,11 @@
|
||||
# Automatically created by: scrapy startproject
|
||||
#
|
||||
# For more information about the [deploy] section see:
|
||||
# https://scrapyd.readthedocs.io/en/latest/deploy.html
|
||||
|
||||
[settings]
|
||||
default = crawler.settings
|
||||
|
||||
[deploy]
|
||||
#url = http://localhost:6800/
|
||||
project = crawler
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"https://www.uni-due.de/biwi/koenig/start.php": "https://www.uni-due.de/biwi/koenig",
|
||||
"https://www.uni-due.de/biwi/hofaecker/start": "https://www.uni-due.de/biwi/hofaecker",
|
||||
"https://www.uni-due.de/biwi/wehrheim/wehrheim.php": "https://www.uni-due.de/biwi/wehrheim",
|
||||
"https://www.uni-due.de/chemie/ak_disch/ak_disch.php": "https://www.uni-due.de/chemie/ak_disch",
|
||||
"https://www.uni-due.de/kunst-kuwiss/kuk_home.shtml": "https://www.uni-due.de/kunst-kuwiss",
|
||||
"https://www.uni-due.de/mathematik/ruhrpad/ruhr.pad": "https://www.uni-due.de/mathematik/ruhrpad",
|
||||
"https://www.uni-due.de/mathematik/ag_belomestny/urusov": "https://www.uni-due.de/mathematik/ag_belomestny",
|
||||
"https://www.uni-due.de/empi/aqm/schierning-cv": "https://www.uni-due.de/empi/aqm"
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
"""
|
||||
Generate crawl seeds from an entity's ground-truth JSON.
|
||||
|
||||
The source truth uses the shared faculty -> institute -> chair structure.
|
||||
Configured seed_levels determine which entity levels are emitted.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urldefrag, urlsplit, urlunsplit
|
||||
|
||||
from pipeline_utils import (
|
||||
add_common_args,
|
||||
entity_input_path,
|
||||
generated_entities_path,
|
||||
get_entity,
|
||||
load_config,
|
||||
)
|
||||
|
||||
|
||||
VALID_LEVELS = {"faculty", "institute", "chair"}
|
||||
|
||||
|
||||
def normalize_url(url: str) -> str | None:
|
||||
"""Return a stable seed URL, or None for missing/invalid truth values."""
|
||||
if not isinstance(url, str):
|
||||
return None
|
||||
|
||||
url = url.strip()
|
||||
if not url or url.lower() == "none":
|
||||
return None
|
||||
|
||||
url, _ = urldefrag(url)
|
||||
parsed = urlsplit(url)
|
||||
|
||||
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
||||
return None
|
||||
|
||||
path = parsed.path.rstrip("/")
|
||||
return urlunsplit((parsed.scheme, parsed.netloc, path, parsed.query, ""))
|
||||
|
||||
|
||||
def hostname_is_blocked(hostname: str, blocked_hosts: list[str]) -> bool:
|
||||
hostname = hostname.lower().rstrip(".")
|
||||
for blocked in blocked_hosts:
|
||||
blocked = blocked.lower().rstrip(".")
|
||||
if hostname == blocked or hostname.endswith("." + blocked):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def hostname_is_allowed(hostname: str, allowed_domains: list[str]) -> bool:
|
||||
hostname = hostname.lower().rstrip(".")
|
||||
for allowed in allowed_domains:
|
||||
allowed = allowed.lower().rstrip(".")
|
||||
if hostname == allowed or hostname.endswith("." + allowed):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def extract_urls(node: dict) -> list[str]:
|
||||
"""Extract all link_de/link_en/link_de_2/... fields from one truth node."""
|
||||
urls = []
|
||||
for key, value in node.items():
|
||||
if key.startswith("link_"):
|
||||
url = normalize_url(value)
|
||||
if url:
|
||||
urls.append(url)
|
||||
return urls
|
||||
|
||||
|
||||
def collect_seeds(truth: dict, seed_levels: set[str]) -> list[dict]:
|
||||
seeds = []
|
||||
|
||||
for faculty in truth.get("faculties", []):
|
||||
if "faculty" in seed_levels:
|
||||
for url in extract_urls(faculty):
|
||||
seeds.append({
|
||||
"url": url,
|
||||
"level": "faculty",
|
||||
"name_de": faculty.get("name_de", ""),
|
||||
"name_en": faculty.get("name_en", ""),
|
||||
})
|
||||
|
||||
for institute in faculty.get("institutes", []):
|
||||
if "institute" in seed_levels:
|
||||
for url in extract_urls(institute):
|
||||
seeds.append({
|
||||
"url": url,
|
||||
"level": "institute",
|
||||
"name_de": institute.get("name_de", ""),
|
||||
"name_en": institute.get("name_en", ""),
|
||||
"faculty_de": faculty.get("name_de", ""),
|
||||
"faculty_en": faculty.get("name_en", ""),
|
||||
})
|
||||
|
||||
for chair in institute.get("chairs", []):
|
||||
if "chair" in seed_levels:
|
||||
for url in extract_urls(chair):
|
||||
seeds.append({
|
||||
"url": url,
|
||||
"level": "chair",
|
||||
"name_de": chair.get("name_de", ""),
|
||||
"name_en": chair.get("name_en", ""),
|
||||
"faculty_de": faculty.get("name_de", ""),
|
||||
"faculty_en": faculty.get("name_en", ""),
|
||||
})
|
||||
|
||||
for chair in faculty.get("chairs", []):
|
||||
if "chair" in seed_levels:
|
||||
for url in extract_urls(chair):
|
||||
seeds.append({
|
||||
"url": url,
|
||||
"level": "chair",
|
||||
"name_de": chair.get("name_de", ""),
|
||||
"name_en": chair.get("name_en", ""),
|
||||
"faculty_de": faculty.get("name_de", ""),
|
||||
"faculty_en": faculty.get("name_en", ""),
|
||||
})
|
||||
|
||||
return seeds
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Generate generic crawler seed URLs from an entity truth file."
|
||||
)
|
||||
add_common_args(parser)
|
||||
args = parser.parse_args()
|
||||
|
||||
config = load_config(args.config)
|
||||
entity = get_entity(config, args.entity)
|
||||
crawl = entity.get("crawl", {})
|
||||
|
||||
seed_levels = set(crawl.get("seed_levels", ["institute", "chair"]))
|
||||
invalid_levels = seed_levels - VALID_LEVELS
|
||||
if invalid_levels:
|
||||
raise SystemExit(
|
||||
f"Invalid seed_levels for '{args.entity}': {sorted(invalid_levels)}. "
|
||||
f"Allowed values: {sorted(VALID_LEVELS)}"
|
||||
)
|
||||
|
||||
truth_path = entity_input_path(config, args.entity, "ground_truth_file")
|
||||
output_path = generated_entities_path(config, args.entity)
|
||||
|
||||
with open(truth_path, encoding="utf-8") as handle:
|
||||
truth = json.load(handle)
|
||||
|
||||
allowed_domains = crawl.get("allowed_domains", [])
|
||||
blocked_hosts = crawl.get("banned_hostnames", [])
|
||||
|
||||
if not allowed_domains:
|
||||
raise SystemExit(
|
||||
f"Entity '{args.entity}' has no crawl.allowed_domains configuration."
|
||||
)
|
||||
|
||||
seeds = []
|
||||
skipped = []
|
||||
|
||||
for seed in collect_seeds(truth, seed_levels):
|
||||
hostname = urlsplit(seed["url"]).hostname
|
||||
if hostname_is_blocked(hostname, blocked_hosts):
|
||||
skipped.append({"url": seed["url"], "reason": "banned_hostname"})
|
||||
continue
|
||||
|
||||
if not hostname_is_allowed(hostname, allowed_domains):
|
||||
skipped.append({"url": seed["url"], "reason": "outside_allowed_domains"})
|
||||
continue
|
||||
|
||||
seeds.append(seed)
|
||||
|
||||
# Deduplicate by normalized URL while retaining the first metadata record.
|
||||
unique_seeds = {}
|
||||
for seed in seeds:
|
||||
unique_seeds.setdefault(seed["url"], seed)
|
||||
|
||||
output = {
|
||||
"entity": args.entity,
|
||||
"display_name": entity.get("display_name", args.entity),
|
||||
"source_truth_file": truth_path,
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(),
|
||||
"seed_levels": sorted(seed_levels),
|
||||
"seed_count": len(unique_seeds),
|
||||
"skipped_count": len(skipped),
|
||||
"seeds": list(unique_seeds.values()),
|
||||
"skipped": skipped,
|
||||
}
|
||||
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
with open(output_path, "w", encoding="utf-8") as handle:
|
||||
json.dump(output, handle, ensure_ascii=False, indent=2)
|
||||
|
||||
print(f"Generated {len(unique_seeds)} crawl seeds: {output_path}")
|
||||
if skipped:
|
||||
print(f"Skipped {len(skipped)} invalid, banned, or out-of-scope seed URLs.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,139 @@
|
||||
{
|
||||
"runs_dir": "runs",
|
||||
"elasticsearch": {
|
||||
"host": "https://inse.nes.uni-due.de:443/elastic",
|
||||
"user": "elastic",
|
||||
"password_env": "ES_PASSWORD",
|
||||
"request_timeout": 60,
|
||||
"max_retries": 5
|
||||
},
|
||||
"llm": {
|
||||
"base_url_env": "llm_api",
|
||||
"api_key_env": "llm_key",
|
||||
"model_name": "model_name"
|
||||
},
|
||||
"cache_dir": "runs/.llm_cache",
|
||||
"default_categories": [
|
||||
"Teaching",
|
||||
"Research",
|
||||
"Projects",
|
||||
"Staff",
|
||||
"News",
|
||||
"Other"
|
||||
],
|
||||
"entities": {
|
||||
"ude": {
|
||||
"display_name": "University of Duisburg-Essen",
|
||||
"crawler_dir": "crawler/crawler",
|
||||
"scrapy_spider": "ude",
|
||||
"ground_truth_file": "entities/ude/ground_truth.json",
|
||||
"problem_orgs_file": "entities/ude/problem_orgs.json",
|
||||
"classifier_banned_hostnames": [
|
||||
"www.uni-due.de",
|
||||
"uni-due.de",
|
||||
"www.esaga.uni-due.de",
|
||||
"esaga.uni-due.de"
|
||||
],
|
||||
"crawl": {
|
||||
"generated_entities_file": "entities.json",
|
||||
"seed_levels": [
|
||||
"institute",
|
||||
"chair"
|
||||
],
|
||||
"allowed_domains": [
|
||||
"uni-due.de",
|
||||
"uk-essen.de"
|
||||
],
|
||||
"banned_hostnames": [],
|
||||
"deny_url_patterns": [
|
||||
"(campus|webmailer|webmail|git|moodle|primo|shop|lehramtswiki)\\.(uni-duisburg-essen|uni-due)\\.de",
|
||||
"belegung\\.uni-due\\.de",
|
||||
"uni-due\\.de/ub",
|
||||
"uni-due\\.digibib\\.net",
|
||||
"uni-due\\.zoom\\.us",
|
||||
"uni-due\\.de/myude/",
|
||||
"uni-due\\.de/en/deadlines\\.php",
|
||||
"uni-due\\.de/verwaltung",
|
||||
"uni-due\\.de/zim",
|
||||
"uni-due\\.de/aktuell",
|
||||
"duepublico2\\.uni-due\\.de",
|
||||
"uni-due\\.de/person",
|
||||
"uni-due\\.de/de/presse",
|
||||
"uni-due\\.de/de/campusaktuell",
|
||||
"uni-due\\.de/de/intranet",
|
||||
"uni-due\\.de/de/veranstaltungen",
|
||||
"uni-due\\.de/de/presse/meldung\\.php",
|
||||
"\\.bib$"
|
||||
],
|
||||
"depth_limit": 1,
|
||||
"download_delay": 2,
|
||||
"concurrent_requests": 16,
|
||||
"concurrent_requests_per_domain": 16,
|
||||
"download_timeout": 40,
|
||||
"user_agent": "inse-crawler",
|
||||
"operator": "arman.arzani@uni-due.de"
|
||||
},
|
||||
"elasticsearch": {
|
||||
"raw_index": "ude_organization_TEST_BACKGROUND_JOB",
|
||||
"categorized_index": "ude_organization_categorized_TEST_BACKGROUND_JOB",
|
||||
"content_index": "ude_organization_content_TEST_BACKGROUND_JOB"
|
||||
},
|
||||
"output": {
|
||||
"redirections_file": "redirections_lookup.json",
|
||||
"links_to_analyze_file": "links_to_analyze.json",
|
||||
"hierarchy_file": "hierarchy.json",
|
||||
"classifier_log": "classifier_log.json",
|
||||
"content_extractor_log": "content_extractor_log.json",
|
||||
"content_extractor_output_log": "outputs.log",
|
||||
"keywords_updated_log": "keywords_log_updated_orgs.json",
|
||||
"keywords_failed_log": "keywords_log_failed_extractions.json"
|
||||
}
|
||||
},
|
||||
"tud": {
|
||||
"display_name": "Technische Universität Dortmund",
|
||||
"crawler_dir": "crawler/crawler",
|
||||
"scrapy_spider": "tud",
|
||||
"ground_truth_file": "entities/tud/ground_truth.json",
|
||||
"problem_orgs_file": "entities/tud/problem_orgs.json",
|
||||
"classifier_banned_hostnames": [
|
||||
"www.tu-dortmund.de/",
|
||||
"tu-dortmund.de/"
|
||||
],
|
||||
"crawl": {
|
||||
"generated_entities_file": "entities.json",
|
||||
"seed_levels": [
|
||||
"institute",
|
||||
"chair"
|
||||
],
|
||||
"allowed_domains": [
|
||||
"tu-dortmund.de",
|
||||
"www.tu-dortmund.de"
|
||||
],
|
||||
"banned_hostnames": [],
|
||||
"deny_url_patterns": [],
|
||||
"depth_limit": 1,
|
||||
"download_delay": 2,
|
||||
"concurrent_requests": 16,
|
||||
"concurrent_requests_per_domain": 16,
|
||||
"download_timeout": 40,
|
||||
"user_agent": "inse-crawler",
|
||||
"operator": "arman.arzani@uni-due.de"
|
||||
},
|
||||
"elasticsearch": {
|
||||
"raw_index": "tud_organization_TEST_BACKGROUND_JOB",
|
||||
"categorized_index": "tud_organization_categorized_TEST_BACKGROUND_JOB",
|
||||
"content_index": "tud_organization_content_TEST_BACKGROUND_JOB"
|
||||
},
|
||||
"output": {
|
||||
"redirections_file": "redirections_lookup.json",
|
||||
"links_to_analyze_file": "links_to_analyze.json",
|
||||
"hierarchy_file": "hierarchy.json",
|
||||
"classifier_log": "classifier_log.json",
|
||||
"content_extractor_log": "content_extractor_log.json",
|
||||
"content_extractor_output_log": "outputs.log",
|
||||
"keywords_updated_log": "keywords_log_updated_orgs.json",
|
||||
"keywords_failed_log": "keywords_log_failed_extractions.json"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
"""
|
||||
Shared helpers for the organization-crawling pipeline.
|
||||
|
||||
Every stage script (0_get_redirections.py, create_hierarchy.py, links_classifier.py,
|
||||
content_extractor_pydantic.py, extract_content_keywords.py) imports this module to:
|
||||
- load pipeline_config.json
|
||||
- resolve the per-entity run folder (runs/<entity>/out/...)
|
||||
- resolve entity-specific input files (ground truth, problem orgs, ...)
|
||||
- build Elasticsearch / LLM clients from shared config + env vars
|
||||
|
||||
This is the only place that should know about the on-disk layout, so adding a new
|
||||
organization is a config-only change (see 'entity_template' in pipeline_config.json).
|
||||
"""
|
||||
import shutil
|
||||
import os
|
||||
import json
|
||||
import argparse
|
||||
import functools
|
||||
import hashlib
|
||||
|
||||
import diskcache
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv() # load .env file in cwd, if present
|
||||
DEFAULT_CONFIG_FILENAME = "pipeline_config.json"
|
||||
|
||||
|
||||
def _default_config_path():
|
||||
return os.path.join(os.path.dirname(os.path.abspath(__file__)), DEFAULT_CONFIG_FILENAME)
|
||||
|
||||
|
||||
def load_config(config_path=None):
|
||||
path = os.path.abspath(config_path or _default_config_path())
|
||||
with open(path, encoding="utf-8") as f:
|
||||
config = json.load(f)
|
||||
# remember where the config lives so relative paths inside it (ground truth files,
|
||||
# crawler dirs, ...) resolve consistently no matter what the script's cwd is.
|
||||
config["_config_dir"] = os.path.dirname(path)
|
||||
return config
|
||||
|
||||
|
||||
def resolve_path(config, path):
|
||||
"""Resolve a path from the config relative to the config file's directory,
|
||||
unless it is already absolute."""
|
||||
if os.path.isabs(path):
|
||||
return path
|
||||
return os.path.join(config["_config_dir"], path)
|
||||
|
||||
|
||||
def get_entity(config, entity_name):
|
||||
entities = config.get("entities", {})
|
||||
if entity_name not in entities:
|
||||
raise SystemExit(
|
||||
f"Entity '{entity_name}' not found in pipeline_config.json. "
|
||||
f"Available entities: {list(entities.keys())}"
|
||||
)
|
||||
return entities[entity_name]
|
||||
|
||||
|
||||
def run_dir(config, entity_name):
|
||||
"""The per-entity, per-run folder: runs/<entity>/ (with an out/ subfolder)."""
|
||||
d = resolve_path(config, os.path.join(config.get("runs_dir", "runs"), entity_name))
|
||||
os.makedirs(os.path.join(d, "out"), exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def out_path(config, entity_name, key):
|
||||
"""Resolve the path of a named output artifact for an entity's run.
|
||||
'key' matches a key under entities.<entity>.output in pipeline_config.json,
|
||||
e.g. out_path(config, 'ude', 'hierarchy_file')."""
|
||||
entity = get_entity(config, entity_name)
|
||||
filename = entity["output"][key]
|
||||
return os.path.join(run_dir(config, entity_name), "out", filename)
|
||||
|
||||
|
||||
def entity_input_path(config, entity_name, key):
|
||||
"""Resolve an entity-specific input file path, e.g. 'ground_truth_file' or
|
||||
'problem_orgs_file'."""
|
||||
entity = get_entity(config, entity_name)
|
||||
return resolve_path(config, entity[key])
|
||||
|
||||
|
||||
def get_es_client(config):
|
||||
from elasticsearch import Elasticsearch
|
||||
es_conf = config["elasticsearch"]
|
||||
password_env = es_conf.get("password_env", "ES_PASSWORD")
|
||||
host = es_conf.get("host") or os.getenv(es_conf.get("host_env", "ES_HOST"))
|
||||
username = es_conf.get("user") or os.getenv(es_conf.get("user_env", "ES_USERNAME"))
|
||||
password = os.getenv(password_env)
|
||||
if password is None or username is None or host is None:
|
||||
raise SystemExit(
|
||||
f"Elasticsearch credentials not set. Configure elasticsearch.host and elasticsearch.user in pipeline_config.json, and export {password_env} for the password."
|
||||
)
|
||||
request_timeout = es_conf.get("request_timeout", 60)
|
||||
max_retries = es_conf.get("max_retries", 5)
|
||||
return Elasticsearch(
|
||||
host,
|
||||
basic_auth=(username, password),
|
||||
request_timeout=request_timeout,
|
||||
max_retries=max_retries,
|
||||
retry_on_timeout=True,
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# kwargs that only affect transport, not the answer - excluded from the cache
|
||||
# key so a streamed call and a non-streamed call with the same prompt share
|
||||
# one cache entry.
|
||||
_TRANSPORT_KWARGS = ("stream", "stream_options", "timeout")
|
||||
|
||||
|
||||
def _stable_key(func_name, kwargs):
|
||||
kwargs = {k: v for k, v in kwargs.items() if k not in _TRANSPORT_KWARGS}
|
||||
|
||||
def default(o):
|
||||
if isinstance(o, type):
|
||||
# e.g. a pydantic response_format class -> key on its schema,
|
||||
if hasattr(o, "model_json_schema"):
|
||||
return o.model_json_schema()
|
||||
return f"{o.__module__}.{o.__qualname__}"
|
||||
if hasattr(o, "model_dump"):
|
||||
return o.model_dump()
|
||||
return str(o)
|
||||
|
||||
payload = json.dumps({"func": func_name, **kwargs}, default=default, sort_keys=True)
|
||||
return hashlib.sha256(payload.encode()).hexdigest()
|
||||
|
||||
|
||||
def _collect_stream(stream):
|
||||
"""Consume a chat.completions stream and assemble it into a regular
|
||||
ChatCompletion object (first choice only, tool calls ignored).
|
||||
|
||||
We stream purely as a keep-alive: the Apache reverse proxy in front of
|
||||
vLLM drops idle connections after ~300s, and a long generation with
|
||||
stream=False sends nothing until it is finished -> 502 Proxy Error.
|
||||
With streaming, chunks flow continuously and the proxy stays happy.
|
||||
"""
|
||||
from openai.types.chat import ChatCompletion, ChatCompletionMessage
|
||||
from openai.types.chat.chat_completion import Choice
|
||||
|
||||
meta = {"id": "", "model": "", "created": 0}
|
||||
content, reasoning, finish_reason, usage = [], [], None, None
|
||||
for chunk in stream:
|
||||
for k in meta:
|
||||
meta[k] = meta[k] or getattr(chunk, k, None) or meta[k]
|
||||
if getattr(chunk, "usage", None):
|
||||
usage = chunk.usage
|
||||
for choice in chunk.choices or []:
|
||||
if choice.index != 0:
|
||||
continue
|
||||
delta = choice.delta
|
||||
if delta is not None:
|
||||
if delta.content:
|
||||
content.append(delta.content)
|
||||
r = getattr(delta, "reasoning", None) or getattr(delta, "reasoning_content", None)
|
||||
if r:
|
||||
reasoning.append(r)
|
||||
if choice.finish_reason:
|
||||
finish_reason = choice.finish_reason
|
||||
|
||||
if finish_reason is None:
|
||||
# Connection dropped mid-generation - never hand back a truncated
|
||||
# answer as if it were complete; let the caller's retry loop handle it.
|
||||
raise RuntimeError("LLM stream ended without a finish_reason (connection dropped?)")
|
||||
|
||||
message = ChatCompletionMessage(role="assistant", content="".join(content))
|
||||
completion = ChatCompletion(
|
||||
id=meta["id"], object="chat.completion", created=meta["created"], model=meta["model"],
|
||||
choices=[Choice(index=0, finish_reason=finish_reason, message=message)],
|
||||
usage=usage,
|
||||
)
|
||||
if reasoning:
|
||||
completion.reasoning = "".join(reasoning) # keep for debugging (extra attr, not part of the schema)
|
||||
return completion
|
||||
|
||||
|
||||
def _wrap_stream_collect(method):
|
||||
"""stream=True still returns a fully assembled ChatCompletion, so callers
|
||||
(and the cache) never have to deal with Stream objects."""
|
||||
@functools.wraps(method)
|
||||
def wrapper(*args, **kwargs):
|
||||
if kwargs.get("stream"):
|
||||
return _collect_stream(method(*args, **kwargs))
|
||||
return method(*args, **kwargs)
|
||||
return wrapper
|
||||
|
||||
|
||||
def _wrap_cached(method, cache, func_name):
|
||||
@functools.wraps(method)
|
||||
def wrapper(*args, **kwargs):
|
||||
key = _stable_key(func_name, kwargs)
|
||||
if key in cache:
|
||||
return cache[key]
|
||||
result = method(*args, **kwargs)
|
||||
if _is_complete(result):
|
||||
cache[key] = result
|
||||
return result
|
||||
return wrapper
|
||||
|
||||
|
||||
def _is_complete(completion):
|
||||
"""Only cache answers the model actually finished. A truncated answer
|
||||
(finish_reason == "length": max_tokens hit, possibly by a reasoning
|
||||
trace alone) would otherwise be replayed from the cache on every retry."""
|
||||
try:
|
||||
return all(c.finish_reason == "stop" for c in completion.choices)
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
|
||||
def get_llm_client(config, use_cache=True):
|
||||
from openai import OpenAI
|
||||
llm_conf = config["llm"]
|
||||
base_url = os.environ.get(llm_conf.get("base_url_env", "llm_api"))
|
||||
api_key = os.environ.get(llm_conf.get("api_key_env", "llm_key"))
|
||||
model_name = os.environ.get(llm_conf.get("model_name", "model_name"))
|
||||
client = OpenAI(base_url=base_url, api_key=api_key, max_retries=0)
|
||||
client.chat.completions.create = _wrap_stream_collect(client.chat.completions.create)
|
||||
|
||||
if use_cache:
|
||||
cache_dir = resolve_path(config, llm_conf.get("cache_dir", ".llm_cache"))
|
||||
cache = diskcache.Cache(cache_dir)
|
||||
|
||||
client.chat.completions.create = _wrap_cached(
|
||||
client.chat.completions.create, cache, "chat.completions.create"
|
||||
)
|
||||
# if content_extractor_pydantic.py uses structured outputs via .parse()
|
||||
if hasattr(client.beta.chat.completions, "parse"):
|
||||
client.beta.chat.completions.parse = _wrap_cached(
|
||||
client.beta.chat.completions.parse, cache, "beta.chat.completions.parse"
|
||||
)
|
||||
|
||||
return client, model_name
|
||||
|
||||
|
||||
def add_common_args(parser: argparse.ArgumentParser):
|
||||
"""Every stage script accepts --entity (required) and --config (optional override)."""
|
||||
parser.add_argument("--entity", required=True, help="Entity name as defined in pipeline_config.json")
|
||||
parser.add_argument("--config", default=None, help="Path to pipeline_config.json (default: alongside this file)")
|
||||
return parser
|
||||
|
||||
def generated_entities_path(config, entity_name):
|
||||
"""Generated crawl-seed JSON: runs/<entity>/entities.json."""
|
||||
entity = get_entity(config, entity_name)
|
||||
filename = entity.get("crawl", {}).get("generated_entities_file", "entities.json")
|
||||
return os.path.join(run_dir(config, entity_name), filename)
|
||||
|
||||
|
||||
def warc_dir(config, entity_name):
|
||||
"""Entity-specific WARC output: runs/<entity>/warc/."""
|
||||
path = os.path.join(run_dir(config, entity_name), "warc")
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def crawl_state_dir(config, entity_name):
|
||||
"""Entity-specific resumable Scrapy state: runs/<entity>/crawl-state/."""
|
||||
path = os.path.join(run_dir(config, entity_name), "crawl-state")
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def reset_entity_run(config, entity_name):
|
||||
"""Delete all generated data for one entity, including WARC and crawl state."""
|
||||
path = resolve_path(
|
||||
config,
|
||||
os.path.join(config.get("runs_dir", "runs"), entity_name),
|
||||
)
|
||||
if os.path.exists(path):
|
||||
shutil.rmtree(path)
|
||||
return run_dir(config, entity_name)
|
||||
@@ -0,0 +1,140 @@
|
||||
aiohappyeyeballs==2.6.1
|
||||
aiohttp==3.13.5
|
||||
aiosignal==1.4.0
|
||||
annotated-types==0.7.0
|
||||
anyio==4.12.1
|
||||
async-timeout==5.0.1
|
||||
attrs==26.1.0
|
||||
Automat==25.4.16
|
||||
babel==2.18.0
|
||||
beautifulsoup4==4.14.3
|
||||
certifi==2026.2.25
|
||||
cffi==2.1.1
|
||||
charset-normalizer==3.4.4
|
||||
click==8.3.1
|
||||
constantly==23.10.4
|
||||
courlan==1.3.2
|
||||
cryptography==50.0.0
|
||||
cssselect==1.5.0
|
||||
dateparser==1.4.0
|
||||
defusedxml==0.7.1
|
||||
dill==0.4.1
|
||||
diskcache==5.6.3
|
||||
distro==1.9.0
|
||||
elastic-transport==8.17.1
|
||||
elasticsearch==8.17.0
|
||||
exceptiongroup==1.3.1
|
||||
filelock==3.20.0
|
||||
frozenlist==1.8.0
|
||||
fsspec==2025.12.0
|
||||
greenlet==3.4.0
|
||||
h11==0.16.0
|
||||
hf-xet==1.2.0
|
||||
htmldate==1.9.4
|
||||
httpcore==1.0.9
|
||||
httpx==0.28.1
|
||||
huggingface-hub==0.36.0
|
||||
hyperlink==21.0.0
|
||||
idna==3.11
|
||||
ijson==3.5.1
|
||||
Incremental==24.11.0
|
||||
itemadapter==0.13.1
|
||||
itemloaders==1.4.0
|
||||
jellyfish==1.2.1
|
||||
Jinja2==3.1.6
|
||||
jiter==0.16.0
|
||||
jmespath==1.1.0
|
||||
joblib==1.5.3
|
||||
jusText==3.0.2
|
||||
langdetect==1.0.9
|
||||
llvmlite==0.46.0
|
||||
lxml==6.0.2
|
||||
lxml_html_clean==0.4.4
|
||||
MarkupSafe==3.0.3
|
||||
mpmath==1.3.0
|
||||
multidict==6.7.1
|
||||
multiprocess==0.70.19
|
||||
narwhals==2.13.0
|
||||
nest_asyncio==1.6.0
|
||||
networkx==3.4.2
|
||||
nltk==3.9.2
|
||||
numba==0.63.1
|
||||
numpy==2.2.6
|
||||
openai==2.41.1
|
||||
outcome==1.3.0.post0
|
||||
packaging==25.0
|
||||
pandas==2.3.3
|
||||
parsel==1.11.0
|
||||
pillow==12.2.0
|
||||
pip==25.3
|
||||
platformdirs==4.5.1
|
||||
prompt_toolkit==3.0.52
|
||||
propcache==0.4.1
|
||||
Protego==0.6.2
|
||||
psutil==7.1.3
|
||||
pure_eval==0.2.3
|
||||
pyarrow==23.0.1
|
||||
pycparser==3.0
|
||||
pydantic==2.13.0
|
||||
pydantic_core==2.46.0
|
||||
PyDispatcher==2.0.7
|
||||
pynndescent==0.5.13
|
||||
pyOpenSSL==26.4.0
|
||||
PySocks==1.7.1
|
||||
python-dateutil==2.9.0.post0
|
||||
python-dotenv==1.2.2
|
||||
python-magic==0.4.27
|
||||
pytz==2025.2
|
||||
PyYAML==6.0.3
|
||||
queuelib==1.9.0
|
||||
regex==2025.11.3
|
||||
requests==2.32.5
|
||||
requests-file==3.0.1
|
||||
safetensors==0.7.0
|
||||
scikit-learn==1.7.2
|
||||
scipy==1.15.3
|
||||
Scrapy==2.17.0
|
||||
scrapy-warcio==0.0.8
|
||||
segtok==1.5.11
|
||||
sentence-transformers==5.2.0
|
||||
service-identity==26.1.0
|
||||
setuptools==80.9.0
|
||||
six==1.17.0
|
||||
sniffio==1.3.1
|
||||
sortedcontainers==2.4.0
|
||||
soupsieve==2.8.3
|
||||
stack_data==0.6.3
|
||||
svgwrite==1.4.3
|
||||
sympy==1.14.0
|
||||
tabulate==0.10.0
|
||||
threadpoolctl==3.6.0
|
||||
tiktoken==0.13.0
|
||||
tld==0.13.2
|
||||
tldextract==5.3.1
|
||||
tokenizers==0.22.1
|
||||
tomli==2.4.1
|
||||
tqdm==4.67.1
|
||||
trafilatura==2.0.0
|
||||
transformers==4.57.3
|
||||
trio==0.33.0
|
||||
trio-websocket==0.12.2
|
||||
Twisted==26.4.0
|
||||
typing_extensions==4.15.0
|
||||
typing-inspection==0.4.2
|
||||
tzdata==2025.3
|
||||
tzlocal==5.3.1
|
||||
umap-learn==0.5.9.post2
|
||||
urllib3==2.6.3
|
||||
w3lib==2.4.1
|
||||
warcio==1.8.1
|
||||
warctools==5.0.1
|
||||
wcwidth==0.2.14
|
||||
webdriver-manager==4.0.2
|
||||
websocket-client==1.9.0
|
||||
wheel==0.45.1
|
||||
wsproto==1.3.2
|
||||
xlsxwriter==3.2.9
|
||||
xxhash==3.6.0
|
||||
yake==0.7.3
|
||||
yarl==1.23.0
|
||||
zope.interface==8.5
|
||||
@@ -0,0 +1,143 @@
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
import argparse
|
||||
import time
|
||||
import json
|
||||
|
||||
from pipeline_utils import (
|
||||
crawl_state_dir,
|
||||
generated_entities_path,
|
||||
get_entity,
|
||||
load_config,
|
||||
reset_entity_run,
|
||||
run_dir,
|
||||
resolve_path,
|
||||
warc_dir,
|
||||
)
|
||||
|
||||
|
||||
def run_command(command, cwd=None):
|
||||
"""Run a shell command and exit if it fails."""
|
||||
result = subprocess.run(command,
|
||||
shell=True,
|
||||
cwd=cwd,
|
||||
text=True)
|
||||
if result.returncode != 0:
|
||||
print(f"Command failed: {command}")
|
||||
sys.exit(result.returncode)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="Run the full organization-crawling pipeline for one entity.")
|
||||
parser.add_argument(
|
||||
"--skip-entity-generation",
|
||||
action="store_true",
|
||||
help="Skip generation of runs/<entity>/entities.json and reuse an existing seed file",
|
||||
)
|
||||
parser.add_argument("--entity", required=True, help="Entity name as defined in pipeline_config.json")
|
||||
parser.add_argument("--config", default=None, help="Path to pipeline_config.json")
|
||||
parser.add_argument("--fresh", action="store_true",
|
||||
help="Wipe this entity's runs/<entity>/out folder before starting")
|
||||
parser.add_argument("--skip-crawl", action="store_true",
|
||||
help="Skip the Scrapy crawl step (reuse an existing warc/ directory)")
|
||||
parser.add_argument("--upload-limit", type=int, default=None,
|
||||
help="Only upload the first N pages to Elasticsearch (smoke-test the pipeline "
|
||||
"without a full crawl upload)")
|
||||
args = parser.parse_args()
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
base_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
config = load_config(args.config or os.path.join(base_dir, "pipeline_config.json"))
|
||||
entity = get_entity(config, args.entity)
|
||||
|
||||
entity_run_dir = run_dir(config, args.entity)
|
||||
out_dir = os.path.join(entity_run_dir, "out")
|
||||
|
||||
if args.fresh:
|
||||
print(f"Removing all generated data for entity '{args.entity}'...")
|
||||
entity_run_dir = reset_entity_run(config, args.entity)
|
||||
else:
|
||||
entity_run_dir = run_dir(config, args.entity)
|
||||
|
||||
out_dir = os.path.join(entity_run_dir, "out")
|
||||
entity_warc_dir = warc_dir(config, args.entity)
|
||||
entity_crawl_state_dir = crawl_state_dir(config, args.entity)
|
||||
|
||||
crawler_dir = os.path.join(base_dir, entity["crawler_dir"])
|
||||
warc_directory = os.path.join(entity_run_dir, "warc")
|
||||
|
||||
config_path = os.path.abspath(args.config or os.path.join(base_dir, "pipeline_config.json"))
|
||||
common_args = f'--entity {args.entity} --config "{config_path}"'
|
||||
|
||||
if not args.skip_entity_generation:
|
||||
print(f"Generating crawl seed URLs for entity '{args.entity}'...")
|
||||
run_command(
|
||||
f'{sys.executable} generate_entities.py {common_args}',
|
||||
cwd=base_dir,
|
||||
)
|
||||
else:
|
||||
seed_file = generated_entities_path(config, args.entity)
|
||||
if not os.path.exists(seed_file):
|
||||
raise SystemExit(
|
||||
f"--skip-entity-generation was requested but seed file is missing: {seed_file}"
|
||||
)
|
||||
|
||||
if not args.skip_crawl:
|
||||
crawl = entity.get("crawl", {})
|
||||
depth_limit = crawl.get("depth_limit", 6)
|
||||
|
||||
warc_config_path = os.path.join(entity_run_dir, "warc.yml")
|
||||
warc_config = {
|
||||
"warc_spec": "https://iipc.github.io/warc-specifications/specifications/warc-format/warc-1.0/",
|
||||
"max_warc_size": 5000000000,
|
||||
"collection": args.entity,
|
||||
"description": f"A crawl of {entity.get('display_name', args.entity)}",
|
||||
"operator": crawl.get("operator", "unknown"),
|
||||
"robots": "obey",
|
||||
"user_agent": crawl.get("user_agent", "inse-crawler"),
|
||||
"warc_prefix": f"{args.entity}_depth{depth_limit}",
|
||||
"warc_dest": entity_warc_dir,
|
||||
}
|
||||
|
||||
with open(warc_config_path, "w", encoding="utf-8") as handle:
|
||||
json.dump(warc_config, handle, indent=2)
|
||||
|
||||
print(f"Running generic Scrapy crawler for entity '{args.entity}'...")
|
||||
run_command(
|
||||
f'SCRAPY_WARCIO_SETTINGS="{warc_config_path}" scrapy crawl organization '
|
||||
f'-a entity="{args.entity}" -a config="{config_path}" '
|
||||
f'-s JOBDIR="{entity_crawl_state_dir}"',
|
||||
cwd=resolve_path(config, entity["crawler_dir"]),
|
||||
)
|
||||
else:
|
||||
if not os.path.isdir(entity_warc_dir) or not os.listdir(entity_warc_dir):
|
||||
raise SystemExit(
|
||||
f"--skip-crawl was requested but no WARC files exist in {entity_warc_dir}"
|
||||
)
|
||||
print("Skipping crawl step (--skip-crawl).")
|
||||
|
||||
print("Managing redirections")
|
||||
run_command(f"{sys.executable} 00_redirections/0_get_redirections.py {warc_directory} {common_args}", cwd=base_dir)
|
||||
|
||||
print("Uploading crawled pages to Elasticsearch")
|
||||
limit_flag = f" --limit {args.upload_limit}" if args.upload_limit is not None else ""
|
||||
run_command(f"{sys.executable} 01_upload/1_upload_pages.py {warc_directory} "
|
||||
f"{os.path.join(out_dir, entity['output']['redirections_file'])} {common_args}{limit_flag}", cwd=base_dir)
|
||||
|
||||
print("Generating organization hierarchy")
|
||||
run_command(f"{sys.executable} 02_hierarchy/create_hierarchy.py {common_args}", cwd=base_dir)
|
||||
|
||||
print("Classifying URLs")
|
||||
run_command(f"{sys.executable} 03_url_classifier/links_classifier.py {common_args}", cwd=base_dir)
|
||||
|
||||
print("Extracting content from classified URLs")
|
||||
run_command(f"{sys.executable} 04_content_extractor/content_extractor_pydantic.py {common_args}", cwd=base_dir)
|
||||
|
||||
print("Extracting keywords from extracted content")
|
||||
run_command(f"{sys.executable} 05_keyword_extraction/extract_content_keywords.py {common_args}", cwd=base_dir)
|
||||
|
||||
runtime_hours = (time.time() - start_time) / 3600
|
||||
print(f"Final runtime: {runtime_hours:.2f} hours")
|
||||
print(f"Finished running the '{args.entity}' organization pipeline.")
|
||||
Reference in New Issue
Block a user