Compare commits

...
Author SHA1 Message Date
genja 05ae62dc1d fixed elastic api error on tests
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-11-03 18:21:57 +01:00
genja 804ce69df9 fixed the expanded/collapsed bug for orgminer content, where no orgminer content was shown after a chart node was clicked
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-11-03 15:55:44 +01:00
genja 32ad139038 Merge branch 'feature/orgminer' of nes.uni-due.de:lbs/smartguide into feature/orgminer_to_background_jobs
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-11-03 15:24:51 +01:00
genja fdea28266f Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/orgminer_to_background_jobs 2026-11-03 15:24:04 +01:00
genja d08db10f01 orgminer pipeline config edited
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-11-03 15:21:27 +01:00
genja ba3cacfddb gradle scripts adjusted for initializing /data volume for background jobs 2026-11-03 15:21:17 +01:00
arzani 8cdb2ef78d stopped tracking .env, added global example, added env for jenkins pipeline
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-11-03 15:14:25 +01:00
genja 0a84560027 adjusted the pipeline logic to take hierarchy from the single source of truth directory 2026-11-02 23:57:55 +01:00
genja 3313ea733e added docker volume to enable the jobs container access hierarchies 2026-11-02 23:55:00 +01:00
genja 20ee636a91 added underlying uni clinic orgs to hierarchy.json 2026-11-02 23:44:23 +01:00
genja 8f05155fab Merge branch 'feature/orgminer' of nes.uni-due.de:lbs/smartguide into feature/orgminer_to_background_jobs 2026-11-02 21:18:37 +01:00
genja 58d0fc1d9e hierarchy is also saved for orgminer_pipeline 2026-11-02 21:16:07 +01:00
genja 0f70022a16 added test indexes to config 2026-11-02 21:15:17 +01:00
genja f9fee59b25 persistent directory added to temporary save data on failed runs 2026-11-02 21:15:00 +01:00
genja 751badad13 fixed env variable naming conflict 2026-10-28 16:14:35 +01:00
genja 4298d5bf1c added orgminer pipeline to backkground jobs 2026-10-28 09:34:08 +01:00
60 changed files with 11298 additions and 255 deletions
+5
View File
@@ -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/
+1
View File
@@ -15,6 +15,7 @@ src/python/account/
.env
*.pyc
.env
node_modules/
angular-app/.angular
Vendored
+2
View File
@@ -70,10 +70,12 @@ pipeline {
-o StrictHostKeyChecking=no \
${DEPLOY_HOST} "
docker load < ~/tmp/app-image.tar.gz &&
docker volume create smartguide-data &&
docker stop inse-app || true &&
docker rm inse-app || true &&
docker run -d \
--name inse-app \
-v smartguide-data:/data \
-p 8080:8000 \
${IMAGE_PREFIX}-app:${IMAGE_VERSION} run
"
+1
View File
@@ -26,6 +26,7 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
COPY [ "src/main", "/home" ]
COPY [ "src/data", "/data" ]
COPY [ "src/data", "/seed-data" ]
EXPOSE 8000/tcp
VOLUME [ "/home", "/mnt", "/data" ]
ENTRYPOINT [ "/home/entrypoint.sh" ]
+28 -3
View File
@@ -31,7 +31,6 @@ task createImage(type: Exec) {
commandLine 'docker', 'build', '--platform', "${targetPlatform}", '-t', "${imagePrefix}-service:${imageVersion}", '.'
}
task test(type: Exec) {
dependsOn createImage
def envFile = System.getenv('INSE_ENV_FILE')
@@ -62,12 +61,38 @@ task exportOpenApiSpec(type: Exec) {
'-c',
"import json; from inse.main import app; open('/mnt/openapi/inse-service.openapi.json', 'w').write(json.dumps(app.openapi(), indent=2))"
}
task createDataVolume(type: Exec) {
commandLine 'docker', 'volume', 'create', 'smartguide-data'
}
task initializeDataVolume(type: Exec) {
dependsOn createDataVolume
commandLine 'docker', 'run', '--rm',
'-v', 'smartguide-data:/data',
'-v', "${projectDir}/src/data:/seed-data:ro",
'alpine',
'sh', '-c',
'if [ ! -d /data/hierarchies ] || [ -z "$(find /data/hierarchies -mindepth 1 -maxdepth 1 -type d -print -quit)" ]; then cp -a /seed-data/. /data/; fi'
}
task runServeContainer(type: Exec) {
dependsOn createImage
commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-v', '/var/run/docker.sock:/var/run/docker.sock', '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '-e', 'INSE_OPENALEX_WORKS_API_KEY', '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse'
}
dependsOn initializeDataVolume
commandLine 'docker', 'run', '--rm',
'-v', "${projectDir}/src/main:/home",
'-v', 'smartguide-data:/data',
'-v', '/var/run/docker.sock:/var/run/docker.sock',
'-p', '8000:8000',
'-e', "DOCKER_DEFAULT_PLATFORM=${targetPlatform}",
'-e', 'INSE_AUTH_STANDALONE=true',
'-e', 'INSE_OPENALEX_WORKS_API_KEY',
'--name', "${imageName}-service-serve",
'--detach',
"${imagePrefix}-service:${imageVersion}",
'run', '--reload', '--reload-dir', './inse'
}
task stopServeContainer(type: Exec) {
commandLine 'docker', 'stop', "${imageName}-service-serve"
ignoreExitValue true
@@ -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,250 @@
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
import hashlib
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():
try:
info = es.info()
except Exception as error:
print(f"Elasticsearch connection failed: {error}", file=sys.stderr)
return False
print(
"Connected to Elasticsearch"
+ (f" {info.get('version', {}).get('number')}" if info else "")
)
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")
if not text:
continue
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]
doc_id = hashlib.sha256(uri.encode("utf-8")).hexdigest()
try:
es.index(index=index_name, id=doc_id, document=element)
successes += 1
except Exception as e:
print("upload failed....")
print(e)
continue
else:
print(f"Skipping non-HTML content type: {content_type}")
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})")
else:
print("Failed to connect to Elasticsearch")
sys.exit(1)
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,132 @@
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 (
add_common_args,
entity_input_path,
hierarchy_path,
get_entity,
load_config,
out_path,
)
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
def collect_analysis_links(hierarchy, problem_orgs):
parent_leafs = []
child_leafs = []
unique_links = set()
def visit(node):
link = node.get("link_de") or node.get("link_en")
children = [
child
for group in node.get("children") or []
for child in group.get("children") or []
]
if link and children:
parent = {"link": clean_uri(link), "children": []}
for child in children:
child_link = child.get("link_de") or child.get("link_en")
if child_link:
normalized_link = clean_uri(child_link)
parent["children"].append({"link": normalized_link})
unique_links.add(normalized_link)
if parent["children"]:
parent_leafs.append(parent)
elif link:
normalized_link = clean_uri(link)
if normalized_link not in unique_links:
child_leafs.append({"link": normalized_link})
unique_links.add(normalized_link)
for child in children:
visit(child)
for faculty in hierarchy:
visit(faculty)
return {
"parent_leafs": filter_parents(parent_leafs, problem_orgs),
"child_leafs": filter_children(child_leafs, problem_orgs),
}, unique_links
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Use the accepted hierarchy as the pipeline hierarchy."
)
add_common_args(parser)
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_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(hierarchy_path(config, args.entity), encoding="utf-8") as json_file:
hierarchy = json.load(json_file)
if not isinstance(hierarchy, list):
raise SystemExit("The accepted hierarchy must be a JSON array of faculties.")
linksToAnalyze, uniqueLinks = collect_analysis_links(hierarchy, 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(hierarchy, 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")
@@ -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,72 @@
# 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 accepted hierarchy.
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. Load the accepted organization hierarchy.
7. Classify crawled URLs with the configured LLM.
8. Extract staff, projects, and news.
9. Extract focused keywords for extracted content.
The hierarchy under `src/data/hierarchies` is the authoritative source. The
pipeline must mount that data directory at `/data`, so accepted hierarchy edits
made by the service are visible to the pipeline container.
## Restarting a run
Pipeline data is stored below `runs/<entity>/`. Use `--auto-resume` to keep
existing data and continue from the stages recorded in `pipeline_state.json`.
This also keeps data when the previous run used different limits or was marked
completed. If the state file is missing or invalid, the pipeline keeps the
existing files and reruns the stages because no completed stages can be known.
Use `--fresh` when you explicitly want to delete the entity's existing run
directory and start over. Without either option, the pipeline creates a new
state file without deleting existing data.
When this pipeline is launched by the background-job runner with
`--auto-resume` and no `persistent_dir` is configured, the runner automatically
mounts its named persistent volume at `/app/orgminer_pipeline/runs`.
The service data volume must also be mounted into the pipeline container at
`/data`. Use the same named volume in both containers; the default is
`smartguide-data`, configurable with `ORGMINER_DATA_VOLUME`. The pipeline mounts
it read-only because the service owns accepted hierarchy updates.
For local development, recreate the service with the shared volume:
```bash
docker volume create smartguide-data
docker run ... -v smartguide-data:/data ...
```
The background-job runner mounts that same volume automatically for OrgMiner
jobs. In CI/CD, create or provision a volume with the same configured name and
mount it at `/data` when starting the service.
## 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=...
```
@@ -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
@@ -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,244 @@
"""
Generate crawl seeds from an entity's accepted hierarchy.
The source truth uses the shared accepted hierarchy tree.
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,
generated_entities_path,
get_entity,
hierarchy_path,
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 collect_accepted_seeds(hierarchy: list[dict], seed_levels: set[str]) -> list[dict]:
seeds = []
def add(node, level, faculty):
if level not in seed_levels:
return
for url in extract_urls(node):
seed = {
"url": url,
"level": level,
"name_de": node.get("name_de", ""),
"name_en": node.get("name_en", ""),
}
if faculty:
seed.update(
faculty_de=faculty.get("name_de", ""),
faculty_en=faculty.get("name_en", ""),
)
seeds.append(seed)
for faculty in hierarchy:
add(faculty, "faculty", None)
for group in faculty.get("children") or []:
group_type = group.get("type")
if group_type == "institutes":
for institute in group.get("children") or []:
add(institute, "institute", faculty)
for chair_group in institute.get("children") or []:
if chair_group.get("type") == "chairs":
for chair in chair_group.get("children") or []:
add(chair, "chair", faculty)
elif group_type == "chairs":
for chair in group.get("children") or []:
add(chair, "chair", faculty)
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 = hierarchy_path(config, args.entity)
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 = []
seed_records = (
collect_accepted_seeds(truth, seed_levels)
if isinstance(truth, list)
else collect_seeds(truth, seed_levels)
)
for seed in seed_records:
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",
"hierarchy_file": "/data/hierarchies/I62318514/hierarchy.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": 6,
"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_november_2026",
"categorized_index": "ude_organization_categorized_november_2026",
"content_index": "ude_organization_content_november_2026"
},
"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",
"hierarchy_file": "/data/hierarchies/I200332995/hierarchy.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_bj_test",
"categorized_index": "tud_organization_categorized_bj_test",
"content_index": "tud_organization_content_bj_test"
},
"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,302 @@
"""
Shared helpers for the organization-crawling pipeline.
Every stage script imports this module to:
- load pipeline_config.json
- resolve the per-entity run folder (runs/<entity>/out/...)
- resolve entity-specific input files (accepted hierarchy, 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 hierarchy_path(config, entity_name):
"""Resolve the accepted hierarchy shared with the service."""
entity = get_entity(config, entity_name)
return resolve_path(config, entity["hierarchy_file"])
def _first_env(*names):
"""Return the first non-empty environment variable among the given names."""
for name in names:
if name and os.environ.get(name):
return os.environ[name]
return None
def get_es_client(config):
from elasticsearch import Elasticsearch
es_conf = config["elasticsearch"]
host = (
_first_env("INSE_ELASTIC_URL", "ELASTICSEARCH_INSE_URL", es_conf.get("host_env"))
or es_conf.get("host")
)
if not host:
raise SystemExit("Elasticsearch host not set (INSE_ELASTIC_URL or elasticsearch.host).")
kwargs = {
"request_timeout": es_conf.get("request_timeout", 60),
"max_retries": es_conf.get("max_retries", 5),
"retry_on_timeout": True,
}
api_key = _first_env(
"INSE_ELASTIC_API_KEY",
"ELASTICSEARCH_INSE_API_KEY",
es_conf.get("api_key_env"),
)
username = es_conf.get("user") or os.getenv(es_conf.get("user_env", "ES_USERNAME"))
password = os.getenv(es_conf.get("password_env", "ES_PASSWORD"))
if api_key:
kwargs["api_key"] = api_key
elif username and password:
kwargs["basic_auth"] = (username, password)
else:
raise SystemExit(
"Elasticsearch credentials not set: provide INSE_ELASTIC_API_KEY, "
"or elasticsearch.user plus the ES_PASSWORD variable."
)
return Elasticsearch(host, **kwargs)
# 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 = _first_env("INSE_LLM_BASE_URL", llm_conf.get("base_url_env", "llm_api"))
api_key = _first_env("INSE_LLM_API_KEY", llm_conf.get("api_key_env", "llm_key"))
model_name = _first_env("INSE_LLM_MODEL", llm_conf.get("model_name", "model_name"))
if not (base_url and api_key and model_name):
raise SystemExit("LLM settings missing (INSE_LLM_BASE_URL, INSE_LLM_API_KEY, INSE_LLM_MODEL).")
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, config.get("cache_dir") or 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,363 @@
import argparse
import json
import os
import shutil
import signal
import subprocess
import sys
import tempfile
import time
from pipeline_utils import (
crawl_state_dir,
generated_entities_path,
get_entity,
load_config,
reset_entity_run,
run_dir,
resolve_path,
warc_dir,
)
_active_process: subprocess.Popen | None = None
_stop_requested = False
def _handle_stop_signal(signum: int, _frame) -> None:
"""Forward SIGTERM to the running stage's process group and remember the request.
The handler must not block: the main loop keeps draining the child's output
until the stage has shut down (Scrapy saves its JOBDIR on the first SIGTERM).
If the container's stop timeout is shorter than the shutdown, Docker kills it.
"""
global _stop_requested
_stop_requested = True
process = _active_process
if process is not None and process.poll() is None:
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
pass
def _exit_if_stopped() -> None:
if _stop_requested:
print(
"Interrupted. Progress saved; the next run with --auto-resume continues here.",
flush=True,
)
raise SystemExit(143)
def run_command(command: str, cwd: str | None = None, log=None) -> None:
"""Run a stage in its own process group; stream output to stdout and the log file."""
global _active_process
_exit_if_stopped()
process = subprocess.Popen(
command,
shell=True,
cwd=cwd,
text=True,
encoding="utf-8",
errors="replace",
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=1,
start_new_session=True,
)
_active_process = process
try:
if _stop_requested: # signal arrived between Popen and the assignment above
try:
os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
pass
for line in process.stdout:
sys.stdout.write(line)
sys.stdout.flush()
if log is not None:
log.write(line)
log.flush()
return_code = process.wait()
finally:
_active_process = None
if return_code != 0:
_exit_if_stopped() # a non-zero exit caused by our stop is not a failure
raise subprocess.CalledProcessError(return_code, command)
def _write_state(path: str, state: dict) -> None:
directory = os.path.dirname(path)
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", dir=directory, delete=False
) as handle:
json.dump(state, handle, indent=2)
handle.write("\n")
handle.flush()
os.fsync(handle.fileno())
temporary_path = handle.name
os.replace(temporary_path, path)
def _read_state(path: str) -> dict | None:
try:
with open(path, encoding="utf-8") as handle:
state = json.load(handle)
except (OSError, ValueError):
return None
return state if isinstance(state, dict) else None
def _new_state(signature: dict) -> dict:
return {"done": [], "completed": False, "signature": signature}
def _prepare_run(
config: dict, entity_name: str, signature: dict, fresh: bool, auto_resume: bool
) -> tuple[str, dict]:
"""Return (run folder, state).
--fresh wipe the entity's run folder and start over.
--auto-resume continue the existing run without deleting data,
regardless of its signature or completion status.
neither keep existing data (so --skip-crawl and
--skip-entity-generation still work) and start a new state.
"""
if fresh:
print(f"Removing all generated data for entity '{entity_name}'...")
return reset_entity_run(config, entity_name), _new_state(signature)
entity_run_dir = resolve_path(
config, os.path.join(config.get("runs_dir", "runs"), entity_name)
)
if os.path.isdir(entity_run_dir):
with os.scandir(entity_run_dir) as entries:
has_previous_data = any(entries)
else:
has_previous_data = False
entity_run_dir = run_dir(config, entity_name)
if auto_resume:
state = _read_state(os.path.join(entity_run_dir, "pipeline_state.json"))
if state is not None and isinstance(state.get("done"), list):
if state.get("completed"):
print("Previous run completed. Starting a new run.")
return reset_entity_run(config, entity_name), _new_state(signature)
if state.get("signature") != signature:
print("Warning: flags differ from the interrupted run; resuming anyway.")
print(f"Resuming. Completed steps: {', '.join(state['done']) or 'none'}")
return entity_run_dir, state
if has_previous_data:
print("No pipeline state found. Continuing with existing data.")
else:
print("No previous data found. Starting fresh.")
return entity_run_dir, _new_state(signature)
return entity_run_dir, _new_state(signature)
def _run_step(
name: str,
state: dict,
state_path: str,
command: str,
cwd: str,
log,
) -> None:
if name in state["done"]:
print(f"Skipping '{name}' (already done).")
return
print(f"Running {name}...", flush=True)
try:
run_command(command, cwd=cwd, log=log)
except subprocess.CalledProcessError as error:
print(f"Step '{name}' failed with exit code {error.returncode}.", flush=True)
raise
state["done"].append(name)
_write_state(state_path, state)
_exit_if_stopped()
def main() -> int:
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 run folder before starting",
)
parser.add_argument(
"--auto-resume",
action="store_true",
help="Resume an unfinished run with the same pipeline signature",
)
parser.add_argument(
"--skip-crawl",
action="store_true",
help="Skip the Scrapy crawl step (reuse an existing warc/ directory)",
)
parser.add_argument(
"--crawl-limit",
type=int,
default=None,
help="Stop the Scrapy crawl gracefully after about N pages (smoke test)",
)
parser.add_argument(
"--upload-limit",
type=int,
default=None,
help="Only upload the first N pages to Elasticsearch",
)
args = parser.parse_args()
for signum in (signal.SIGTERM, signal.SIGINT):
signal.signal(signum, _handle_stop_signal)
start_time = time.time()
base_dir = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.abspath(
args.config or os.path.join(base_dir, "pipeline_config.json")
)
config = load_config(config_path)
entity = get_entity(config, args.entity)
signature = {
"entity": args.entity,
"upload_limit": args.upload_limit,
"crawl_limit": args.crawl_limit,
}
entity_run_dir, state = _prepare_run(
config, args.entity, signature, args.fresh, args.auto_resume
)
state_path = os.path.join(entity_run_dir, "pipeline_state.json")
_write_state(state_path, state)
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)
warc_directory = os.path.join(entity_run_dir, "warc")
common_args = f'--entity {args.entity} --config "{config_path}"'
with open(os.path.join(entity_run_dir, "pipeline.log"), "a", encoding="utf-8") as log:
if "entities" not in state["done"]:
if not args.skip_entity_generation:
_run_step(
"entities",
state,
state_path,
f"{sys.executable} generate_entities.py {common_args}",
base_dir,
log,
)
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}"
)
state["done"].append("entities")
_write_state(state_path, state)
if "crawl" not in state["done"]:
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")
with open(warc_config_path, "w", encoding="utf-8") as handle:
json.dump(
{
"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,
},
handle,
indent=2,
)
crawl_limit_flag = (
f" -s CLOSESPIDER_PAGECOUNT={args.crawl_limit}"
if args.crawl_limit is not None
else ""
)
_run_step(
"crawl",
state,
state_path,
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}" -s LOG_LEVEL=INFO'
f"{crawl_limit_flag}",
resolve_path(config, entity["crawler_dir"]),
log,
)
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}"
)
state["done"].append("crawl")
_write_state(state_path, state)
limit_flag = f" --limit {args.upload_limit}" if args.upload_limit is not None else ""
steps = (
(
"redirections",
f"{sys.executable} 00_redirections/0_get_redirections.py {warc_directory} {common_args}",
),
(
"upload",
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}",
),
(
"hierarchy",
f"{sys.executable} 02_hierarchy/create_hierarchy.py {common_args}",
),
(
"classify",
f"{sys.executable} 03_url_classifier/links_classifier.py {common_args}",
),
(
"extract",
f"{sys.executable} 04_content_extractor/content_extractor_pydantic.py {common_args}",
),
(
"keywords",
f"{sys.executable} 05_keyword_extraction/extract_content_keywords.py {common_args}",
),
)
for name, command in steps:
_run_step(name, state, state_path, command, base_dir, log)
state["completed"] = True
_write_state(state_path, state)
# Scrapy's JOBDIR remembers every seen URL; keeping it would make the next crawl fetch nothing.
crawl_state = os.path.join(entity_run_dir, "crawl-state")
if os.path.isdir(crawl_state):
shutil.rmtree(crawl_state)
runtime_hours = (time.time() - start_time) / 3600
print(f"Final runtime: {runtime_hours:.2f} hours")
print(f"Finished running the '{args.entity}' organization pipeline.")
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except subprocess.CalledProcessError as error:
raise SystemExit(error.returncode)
@@ -5773,7 +5773,919 @@
"link_de": "https://www.uk-essen.de",
"chairs_aggregator": "None",
"type": "leaf",
"color": "green"
"color": "green",
"children": [
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Department of Medical Intensive Care I",
"name_de": "Abteilung für Medizinische Intensivtherapie I",
"link_en": "https://www.uk-essen.de/klinik/medizinische-intensivtherapie/",
"link_de": "https://www.uk-essen.de/klinik/medizinische-intensivtherapie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "General, Visceral, Vascular and Transplant Surgery",
"name_de": "Allgemein-, Viszeral-, Gefäß- und Transplantationschirurgie",
"link_en": "https://www.uk-essen.de/klinik/allgemeinchirurgie/",
"link_de": "https://www.uk-essen.de/klinik/allgemeinchirurgie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Anaesthesiology and Intensive Care Medicine",
"name_de": "Anästhesiologie und Intensivmedizin",
"link_en": "https://www.uk-essen.de/klinik/anaesthesiologie-intensivmedizin/",
"link_de": "https://www.uk-essen.de/klinik/anaesthesiologie-intensivmedizin/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Ophthalmology",
"name_de": "Augenheilkunde",
"link_en": "https://www.uk-essen.de/klinik/augenheilkunde/",
"link_de": "https://www.uk-essen.de/klinik/augenheilkunde/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Dermatology",
"name_de": "Dermatologie",
"link_en": "https://www.uk-essen.de/klinik/dermatologie/",
"link_de": "https://www.uk-essen.de/klinik/dermatologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Endocrinology, Diabetology and Metabolism",
"name_de": "Endokrinologie, Diabetologie und Stoffwechsel",
"link_en": "https://www.uk-essen.de/klinik/endokrinologie-diabetologie-stoffwechsel/",
"link_de": "https://www.uk-essen.de/klinik/endokrinologie-diabetologie-stoffwechsel/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Gynecology and Obstetrics",
"name_de": "Frauenheilkunde und Geburtshilfe",
"link_en": "https://www.uk-essen.de/klinik/frauenheilkunde-geburtshilfe/",
"link_de": "https://www.uk-essen.de/klinik/frauenheilkunde-geburtshilfe/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Gastroenterology, Hepatology and Transplantation Medicine",
"name_de": "Gastroenterologie, Hepatologie und Transplantationsmedizin",
"link_en": "https://www.uk-essen.de/klinik/gastroenterologie-hepatologie-transplatationsmedizin/",
"link_de": "https://www.uk-essen.de/klinik/gastroenterologie-hepatologie-transplatationsmedizin/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Otorhinolaryngology",
"name_de": "Hals- Nasen- und Ohrenheilkunde",
"link_en": "https://www.uk-essen.de/klinik/hals-nasen-ohrenheilkunde/",
"link_de": "https://www.uk-essen.de/klinik/hals-nasen-ohrenheilkunde/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Hematology and Stem Cell Transplantation",
"name_de": "Hämatologie und Stammzelltransplantation",
"link_en": "https://www.uk-essen.de/klinik/haematologie-stammzelltransplantation/",
"link_de": "https://www.uk-essen.de/klinik/haematologie-stammzelltransplantation/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Infectious Diseases and Nephrology",
"name_de": "Infektiologie und Nephrologie",
"link_en": "https://www.uk-essen.de/klinik/infektiologie/",
"link_de": "https://www.uk-essen.de/klinik/infektiologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Cardiology and Angiology",
"name_de": "Kardiologie und Angiologie",
"link_en": "https://www.uk-essen.de/klinik/kardiologie-angiologie/",
"link_de": "https://www.uk-essen.de/klinik/kardiologie-angiologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Pediatrics and Adolescent Medicine",
"name_de": "Kinder- und Jugendmedizin",
"link_en": "https://www.uk-essen.de/klinik/kinder-jugendmedizin/",
"link_de": "https://www.uk-essen.de/klinik/kinder-jugendmedizin/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Pediatric Surgery",
"name_de": "Kinderchirurgie",
"link_en": "https://www.uk-essen.de/klinik/kinderchirurgie/",
"link_de": "https://www.uk-essen.de/klinik/kinderchirurgie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Medical Oncology",
"name_de": "Medizinische Onkologie",
"link_en": "https://www.uk-essen.de/klinik/medizinische-onkologie/",
"link_de": "https://www.uk-essen.de/klinik/medizinische-onkologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Oral, Maxillofacial and Plastic Facial Surgery",
"name_de": "Mund-, Kiefer- und Plastische Gesichtschirurgie",
"link_en": "https://www.uk-essen.de/klinik/klinik-fuer-mund-kiefer-und-plastische-gesichtschirurgie/",
"link_de": "https://www.uk-essen.de/klinik/klinik-fuer-mund-kiefer-und-plastische-gesichtschirurgie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Nephrology",
"name_de": "Nephrologie",
"link_en": "https://www.uk-essen.de/klinik/nephrologie/",
"link_de": "https://www.uk-essen.de/klinik/nephrologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Neurosurgery and Spinal Surgery",
"name_de": "Neurochirurgie und Wirbelsäulenchirurgie",
"link_en": "https://www.uk-essen.de/klinik/neurochirurgie-wirbelsaeulenchirurgie/",
"link_de": "https://www.uk-essen.de/klinik/neurochirurgie-wirbelsaeulenchirurgie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Neurology",
"name_de": "Neurologie",
"link_en": "https://www.uk-essen.de/klinik/neurologie/",
"link_de": "https://www.uk-essen.de/klinik/neurologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Nuclear Medicine",
"name_de": "Nuklearmedizin",
"link_en": "https://www.uk-essen.de/klinik/nuklearmedizin/",
"link_de": "https://www.uk-essen.de/klinik/nuklearmedizin/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Particle Therapy (WPE)",
"name_de": "Partikeltherapie (WPE)",
"link_en": "https://www.uk-essen.de/klinik/partikeltherapie-wpe/",
"link_de": "https://www.uk-essen.de/klinik/partikeltherapie-wpe/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Thoracic and Cardiovascular Surgery",
"name_de": "Thorax- und Kardiovaskuläre Chirurgie",
"link_en": "https://www.uk-essen.de/klinik/thorax-kardiovaskulaere-chirurgie/",
"link_de": "https://www.uk-essen.de/klinik/thorax-kardiovaskulaere-chirurgie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Tumor Orthopedics and Sarcoma Surgery",
"name_de": "Tumororthopädie und Sarkomchirurgie",
"link_en": "https://www.uk-essen.de/klinik/tumororthopaedie-sarkomchirurgie/",
"link_de": "https://www.uk-essen.de/klinik/tumororthopaedie-sarkomchirurgie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Trauma, Hand and Reconstructive Surgery",
"name_de": "Unfall-, Hand- und Wiederherstellungschirurgie",
"link_en": "https://www.uk-essen.de/klinik/unfall-hand-wiederherstellungschirurgie/",
"link_de": "https://www.uk-essen.de/klinik/unfall-hand-wiederherstellungschirurgie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Urology",
"name_de": "Urologie",
"link_en": "https://www.uk-essen.de/klinik/urologie/",
"link_de": "https://www.uk-essen.de/klinik/urologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Radiation Therapy",
"name_de": "Poliklinik für Strahlentherapie",
"link_en": "https://www.uk-essen.de/klinik/strahlentherapie/",
"link_de": "https://www.uk-essen.de/klinik/strahlentherapie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Bridge Institute for Experimental Tumor Therapy (BIT)",
"name_de": "Brückeninstitut für Experimentelle Tumortherapie (BIT)",
"link_en": "https://www.uk-essen.de/institut/tumortherapie/",
"link_de": "https://www.uk-essen.de/institut/tumortherapie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of General Practice",
"name_de": "Institut für Allgemeinmedizin",
"link_en": "https://www.uk-essen.de/institut/allgemeinmedizin/",
"link_de": "https://www.uk-essen.de/institut/allgemeinmedizin/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Anatomy",
"name_de": "Institut für Anatomie",
"link_en": "https://www.uk-essen.de/institut/anatomie/",
"link_de": "https://www.uk-essen.de/institut/anatomie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Diagnostic and Interventional Radiology and Neuroradiology",
"name_de": "Institut für Diagnostische und Interventionelle Radiologie und Neuroradiologie",
"link_en": "https://www.uk-essen.de/institut/radiologie/",
"link_de": "https://www.uk-essen.de/institut/radiologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Medical Education",
"name_de": "Institut für Didaktik in der Medizin",
"link_en": "https://www.uk-essen.de/institut/institut-fuer-didaktik-in-der-medizin/",
"link_de": "https://www.uk-essen.de/institut/institut-fuer-didaktik-in-der-medizin/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute for Research on HIV and AIDS-Associated Diseases",
"name_de": "Institut für die Erforschung von HIV und AIDS–assoziierten Erkrankungen",
"link_en": "https://www.uk-essen.de/institut/hiv-forschung/",
"link_de": "https://www.uk-essen.de/institut/hiv-forschung/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Experimental Immunology and Imaging",
"name_de": "Institut für Experimentelle Immunologie und Bildgebung",
"link_en": "https://www.uk-essen.de/institut/experimentelle-immunologie-bildgebung/",
"link_de": "https://www.uk-essen.de/institut/experimentelle-immunologie-bildgebung/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Gender-Sensitive Medicine",
"name_de": "Institut für Geschlechtersensible Medizin",
"link_en": "https://www.uk-essen.de/institut/institut-fuer-geschlechtersensible-medizin/",
"link_de": "https://www.uk-essen.de/institut/institut-fuer-geschlechtersensible-medizin/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Human Genetics",
"name_de": "Institut für Humangenetik",
"link_en": "https://www.uk-essen.de/institut/humangenetik/",
"link_de": "https://www.uk-essen.de/institut/humangenetik/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Immunology",
"name_de": "Institut für Immunologie",
"link_en": "https://www.uk-essen.de/institut/immunologie/",
"link_de": "https://www.uk-essen.de/institut/immunologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute for Artificial Intelligence in Medicine (IKIM)",
"name_de": "Institut für KI in der Medizin (IKIM)",
"link_en": "https://www.uk-essen.de/institut/ikim/",
"link_de": "https://www.uk-essen.de/institut/ikim/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Medical Informatics, Biometry and Epidemiology",
"name_de": "Institut für Medizinische Informatik, Biometrie und Epidemiologie",
"link_en": "https://www.uk-essen.de/institut/informatik-biometrie-epidemiologie/",
"link_de": "https://www.uk-essen.de/institut/informatik-biometrie-epidemiologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Medical Microbiology",
"name_de": "Institut für Medizinische Mikrobiologie",
"link_en": "https://www.uk-essen.de/institut/mikrobiologie/",
"link_de": "https://www.uk-essen.de/institut/mikrobiologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Medical Psychology and Behavioral Immunobiology",
"name_de": "Institut für Medizinische Psychologie und Verhaltensimmunbiologie",
"link_en": "https://www.uk-essen.de/institut/psychologie/",
"link_de": "https://www.uk-essen.de/institut/psychologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Molecular Biology (Cancer Research)",
"name_de": "Institut für Molekularbiologie (Tumorforschung)",
"link_en": "https://www.uk-essen.de/institut/molekularbiologie/",
"link_de": "https://www.uk-essen.de/institut/molekularbiologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Neuropathology",
"name_de": "Institut für Neuropathologie",
"link_en": "https://www.uk-essen.de/institut/neuropathologie/",
"link_de": "https://www.uk-essen.de/institut/neuropathologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Pathology",
"name_de": "Institut für Pathologie",
"link_en": "https://www.uk-essen.de/institut/pathologie/",
"link_de": "https://www.uk-essen.de/institut/pathologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Pathophysiology",
"name_de": "Institut für Pathophysiologie",
"link_en": "https://www.uk-essen.de/institut/pathophysiologie/",
"link_de": "https://www.uk-essen.de/institut/pathophysiologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Patient Experience",
"name_de": "Institut für PatientenErleben",
"link_en": "https://www.uk-essen.de/institut/patientenerleben/",
"link_de": "https://www.uk-essen.de/institut/patientenerleben/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Pharmacology",
"name_de": "Institut für Pharmakologie",
"link_en": "https://www.uk-essen.de/institut/pharmakologie/",
"link_de": "https://www.uk-essen.de/institut/pharmakologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Physiology",
"name_de": "Institut für Physiologie",
"link_en": "https://www.uk-essen.de/institut/physiologie/",
"link_de": "https://www.uk-essen.de/institut/physiologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Physiological Chemistry",
"name_de": "Institut für Physiologische Chemie",
"link_en": "https://www.uk-essen.de/institut/physiologische-chemie/",
"link_de": "https://www.uk-essen.de/institut/physiologische-chemie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Forensic Medicine",
"name_de": "Institut für Rechtsmedizin",
"link_en": "https://www.uk-essen.de/institut/rechtsmedizin/",
"link_de": "https://www.uk-essen.de/institut/rechtsmedizin/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Exercise and Movement Therapy at the West German Cancer Center Essen",
"name_de": "Institut für Sport- und Bewegungstherapie am Westdeutschen Tumorzentrum Essen",
"link_en": "https://www.uk-essen.de/institut/sport-und-bewegungstherapie-WTZ/",
"link_de": "https://www.uk-essen.de/institut/sport-und-bewegungstherapie-WTZ/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Transfusion Medicine",
"name_de": "Institut für Transfusionsmedizin",
"link_en": "https://www.uk-essen.de/institut/transfusionsmedizin/",
"link_de": "https://www.uk-essen.de/institut/transfusionsmedizin/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Urban Public Health",
"name_de": "Institut für Urban Public Health",
"link_en": "https://www.uk-essen.de/institut/urban-public-health/",
"link_de": "https://www.uk-essen.de/institut/urban-public-health/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Virology",
"name_de": "Institut für Virologie",
"link_en": "https://www.uk-essen.de/institut/virologie/",
"link_de": "https://www.uk-essen.de/institut/virologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute of Cell Biology (Cancer Research)",
"name_de": "Institut für Zellbiologie (Tumorforschung)",
"link_en": "https://www.uk-essen.de/institut/zellbiologie/",
"link_de": "https://www.uk-essen.de/institut/zellbiologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Institute for Cell Therapeutic Research",
"name_de": "Institut für Zelltherapeutische Forschung",
"link_en": "https://www.uk-essen.de/institut/zelltherapeutische-forschung/",
"link_de": "https://www.uk-essen.de/institut/zelltherapeutische-forschung/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Breast Center I at the WTZ",
"name_de": "Brustzentrum I am WTZ",
"link_en": "https://www.uk-essen.de/zentrum/brustzentrum-i/",
"link_de": "https://www.uk-essen.de/zentrum/brustzentrum-i/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Essen Center for Rare Diseases (EZSE)",
"name_de": "Essener Zentrum für seltene Erkrankungen (EZSE)",
"link_en": "https://www.uk-essen.de/zentrum/seltene-erkrankungen/",
"link_de": "https://www.uk-essen.de/zentrum/seltene-erkrankungen/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Essen Vascular Center",
"name_de": "Gefäßzentrum Essen",
"link_en": "https://www.uk-essen.de/zentrum/gefaesszentrum-essen/",
"link_de": "https://www.uk-essen.de/zentrum/gefaesszentrum-essen/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Interdisciplinary Pain Center",
"name_de": "Interdisziplinäres Schmerzzentrum",
"link_en": "https://www.uk-essen.de/zentrum/schmerzzentrum/",
"link_de": "https://www.uk-essen.de/zentrum/schmerzzentrum/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Lung Cancer Center at the WTZ",
"name_de": "Lungenkrebszentrum am WTZ",
"link_en": "https://www.uk-essen.de/zentrum/lungenkrebszentrum/",
"link_de": "https://www.uk-essen.de/zentrum/lungenkrebszentrum/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Palliative Care",
"name_de": "Palliativmedizin",
"link_en": "https://www.uk-essen.de/zentrum/palliativmedizin/",
"link_de": "https://www.uk-essen.de/zentrum/palliativmedizin/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "West German Heart and Vascular Center (WHGZ)",
"name_de": "Westdeutsches Herz- und Gefäßzentrum (WHGZ)",
"link_en": "https://www.uk-essen.de/zentrum/whgz/",
"link_de": "https://www.uk-essen.de/zentrum/whgz/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "West German Headache Center",
"name_de": "Westdeutsches Kopfschmerzzentrum",
"link_en": "https://www.uk-essen.de/zentrum/kopfschmerzzentrum/",
"link_de": "https://www.uk-essen.de/zentrum/kopfschmerzzentrum/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "West German Gastrointestinal Center",
"name_de": "Westdeutsches Magen- und Darmzentrum",
"link_en": "https://www.uk-essen.de/zentrum/magen-darmzentrum/",
"link_de": "https://www.uk-essen.de/zentrum/magen-darmzentrum/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "West German Proton Therapy Center (WPE)",
"name_de": "Westdeutsches Protonentherapiezentrum (WPE)",
"link_en": "https://www.uk-essen.de/zentrum/protonentherapiezentrum/",
"link_de": "https://www.uk-essen.de/zentrum/protonentherapiezentrum/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "West German Cancer Center Essen (WTZ)",
"name_de": "Westdeutsches Tumorzentrum Essen (WTZ)",
"link_en": "https://www.uk-essen.de/zentrum/westdeutsches-tumorzentrum-essen/",
"link_de": "https://www.uk-essen.de/zentrum/westdeutsches-tumorzentrum-essen/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "West German Center for Infectious Diseases (WZI)",
"name_de": "Westdeutsches Zentrum für Infektiologie (WZI)",
"link_en": "https://www.uk-essen.de/zentrum/westdeutsches-zentrum-fuer-infektiologie/",
"link_de": "https://www.uk-essen.de/zentrum/westdeutsches-zentrum-fuer-infektiologie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "West German Center for Organ Transplantation (WZO)",
"name_de": "Westdeutsches Zentrum für Organtransplantation (WZO)",
"link_en": "https://www.uk-essen.de/zentrum/organtransplantationen/",
"link_de": "https://www.uk-essen.de/zentrum/organtransplantationen/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Metropole Ruhr Center for Intensive Care Medicine (ZIMR)",
"name_de": "Zentrum für Intensivmedizin Metropole Ruhr (ZIMR)",
"link_en": "https://www.uk-essen.de/zentrum/zimr/",
"link_de": "https://www.uk-essen.de/zentrum/zimr/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Center for Interdisciplinary Telemedicine and Telecare (ZinTT)",
"name_de": "Zentrum für interdisziplinäre Telemedizin und Telecare (ZinTT)",
"link_en": "https://www.uk-essen.de/zentrum/telemedizin/",
"link_de": "https://www.uk-essen.de/zentrum/telemedizin/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Center for Child and Adolescent Medicine",
"name_de": "Zentrum für Kinder- und Jugendmedizin",
"link_en": "https://www.uk-essen.de/zentrum/kinder-jugendmedizin/",
"link_de": "https://www.uk-essen.de/zentrum/kinder-jugendmedizin/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Center for Naturopathy and Planetary Health",
"name_de": "Zentrum für Naturheilkunde und Planetare Gesundheit",
"link_en": "https://www.uk-essen.de/zentrum/Naturheilkunde/",
"link_de": "https://www.uk-essen.de/zentrum/Naturheilkunde/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Center for Emergency Medicine",
"name_de": "Zentrum für Notfallmedizin",
"link_en": "https://www.uk-essen.de/zentrum/notfallmedizin/",
"link_de": "https://www.uk-essen.de/zentrum/notfallmedizin/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Center for Virtual and Augmented Reality in Medicine (ZvRM)",
"name_de": "Zentrum für virtuelle und erweiterte Realität in der Medizin (ZvRM)",
"link_en": "https://www.uk-essen.de/zentrum/zentrum-fuer-virtuelle-und-erweiterte-realitaet-in-der-medizin-zvrm/",
"link_de": "https://www.uk-essen.de/zentrum/zentrum-fuer-virtuelle-und-erweiterte-realitaet-in-der-medizin-zvrm/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Department of EIMK – Empathic Intercultural Medical Communication",
"name_de": "Abteilung EIMK – Empathische Interkulturelle Medizinische Kommunikation",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/abteilung-eimk-empathische-interkulturelle-medizinische-kommunikation/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/abteilung-eimk-empathische-interkulturelle-medizinische-kommunikation/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Pharmacy",
"name_de": "Apotheke",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/apotheke/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/apotheke/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Central Division AI and Data Governance",
"name_de": "Central Division AI and Data Governance",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/ai-data-governance/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/ai-data-governance/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Data Integration Center (DIZ)",
"name_de": "Datenintegrationszentrum (DIZ)",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/datenintegrationszentrum-diz/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/datenintegrationszentrum-diz/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Information Security",
"name_de": "Informationssicherheit",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/informationssicherheit/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/informationssicherheit/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Clinical Ethics Committee (KEK)",
"name_de": "Klinisches Ethik-Komitee (KEK)",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/klinisches-ethik-komitee-kek/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/klinisches-ethik-komitee-kek/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Hospital Hygiene",
"name_de": "Krankenhaushygiene",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/krankenhaushygiene/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/krankenhaushygiene/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Human Resources and Occupational Health Service",
"name_de": "Personal- und betriebsärztlicher Dienst",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/personal-betriebsaerztlicher-dienst/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/personal-betriebsaerztlicher-dienst/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Nursing Service",
"name_de": "Pflegedienst",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/pflegedienst/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/pflegedienst/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Physiotherapy",
"name_de": "Physiotherapie",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/physiotherapie/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/physiotherapie/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Service and Information Center (SIC)",
"name_de": "Service- und Informationscenter (SIC)",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/service-und-informationscenter-sic/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/service-und-informationscenter-sic/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Digital Transformation Staff Unit",
"name_de": "Stabsstelle Digitale Transformation",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/stabsstelle-digitale-transformation/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/stabsstelle-digitale-transformation/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Quality Management and Clinical Risk Management Staff Unit",
"name_de": "Stabsstelle Qualitätsmanagement und klinisches Risikomanagement",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/stabsstelle-qualitaetsmanagement-und-klinisches-risikomanagement/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/stabsstelle-qualitaetsmanagement-und-klinisches-risikomanagement/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "UME Clinical Study Unit",
"name_de": "UME-Studieneinheit",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/ume-studieneinheit/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/ume-studieneinheit/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Central Information Technology (ZIT)",
"name_de": "Zentrale Informationstechnik (ZIT)",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/zentrale-informationstechnik-zit/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/zentrale-informationstechnik-zit/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Central Animal Laboratory",
"name_de": "Zentrales Tierlaboratorium",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/zentrales-tierlaboratorium/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/zentrales-tierlaboratorium/",
"type": "leaf",
"color": "green"
},
{
"faculty_de": "Medizin",
"faculty_en": "Medicine",
"name_en": "Central Laboratory",
"name_de": "Zentrallabor",
"link_en": "https://www.uk-essen.de/gemeinsame-einrichtung/zentrallabor/",
"link_de": "https://www.uk-essen.de/gemeinsame-einrichtung/zentrallabor/",
"type": "leaf",
"color": "green"
}
]
}
],
"value": 4,
+7 -1
View File
@@ -1,4 +1,11 @@
#!/bin/bash
set -e
if [ ! -d /data/hierarchies ] || [ -z "$(find /data/hierarchies -mindepth 1 -maxdepth 1 -type d -print -quit)" ]; then
echo "Initializing empty /data volume from the bundled data..."
cp -a /seed-data/. /data/
fi
cd /home
if [ $# -eq 0 ]; then
uvicorn --host "0.0.0.0" --port "8000" inse.main:app --log-config log-config.yaml
@@ -16,4 +23,3 @@ else
echo "test: Runs tests using pytest."
fi
fi
+29
View File
@@ -0,0 +1,29 @@
LLM_API_URL=
LLM_API_KEY=
LLM_MODEL=
# Patent search (EPO + USPTO)
PATENT_ELASTICSEARCH_URL=
PATENT_ELASTICSEARCH_API_KEY=
ELASTICSEARCH_URL=
ELASTICSEARCH_API_KEY=
ELASTICSEARCH_INSE_URL=
ELASTICSEARCH_INSE_API_KEY=
# Debugging: Log every outgoing Elasticsearch query (index + payload)
PRINT_ES_QUERIES=
# Debugging: Log the duration of every Elasticsearch request
PRINT_ES_TIMINGS=
# Sentence Transformers Configuration
SENTENCE_TRANSFORMERS_MODEL_NAME=
TOKEN_ISSUER_ID=
TOKEN_HMAC_KEY=
# Docker-Registry-Login für Background-Jobs (Nexus, nes.uni-due.de)
BACKGROUND_JOBS_REGISTRY_USERNAME=
BACKGROUND_JOBS_REGISTRY_PASSWORD=
+39 -1
View File
@@ -4,8 +4,9 @@ Database tables and API schemas for the background job runner.
from datetime import UTC, datetime
from enum import StrEnum
from pathlib import Path
from pydantic import BaseModel
from pydantic import BaseModel, Field as PydanticField, field_validator
from sqlmodel import JSON, Column, Field, SQLModel
@@ -51,6 +52,16 @@ class JobDefinition(SQLModel, table=True):
sa_column=Column(JSON),
description="Extra environment variables passed to the container.",
)
persistent_dir: str | None = Field(
default=None,
description="Absolute path where the container's named persistent volume is mounted.",
)
stop_timeout_seconds: int = Field(
default=10,
ge=1,
le=600,
description="Seconds to wait for graceful container shutdown before killing it.",
)
schedule: str | None = Field(
default=None,
description="Cron expression in UTC (e.g. '0 3 * * *'). Null = manual only.",
@@ -63,6 +74,13 @@ class JobDefinition(SQLModel, table=True):
)
created_at: datetime = Field(default_factory=utcnow)
@field_validator("persistent_dir")
@classmethod
def validate_persistent_dir(cls, value: str | None) -> str | None:
if value is not None and not Path(value).is_absolute():
raise ValueError("persistent_dir must be an absolute path.")
return value
class JobRun(SQLModel, table=True):
__tablename__ = "background_job_run"
@@ -95,6 +113,15 @@ class JobDefinitionCreateRequest(BaseModel):
target_index: str = ""
schedule: str | None = None
enabled: bool = True
persistent_dir: str | None = None
stop_timeout_seconds: int = PydanticField(default=10, ge=1, le=600)
@field_validator("persistent_dir")
@classmethod
def validate_persistent_dir(cls, value: str | None) -> str | None:
if value is not None and not Path(value).is_absolute():
raise ValueError("persistent_dir must be an absolute path.")
return value
class JobDefinitionUpdateRequest(BaseModel):
@@ -106,6 +133,15 @@ class JobDefinitionUpdateRequest(BaseModel):
target_index: str | None = None
schedule: str | None = None
enabled: bool | None = None
persistent_dir: str | None = None
stop_timeout_seconds: int | None = PydanticField(default=None, ge=1, le=600)
@field_validator("persistent_dir")
@classmethod
def validate_persistent_dir(cls, value: str | None) -> str | None:
if value is not None and not Path(value).is_absolute():
raise ValueError("persistent_dir must be an absolute path.")
return value
class BackgroundJobTask(BaseModel):
@@ -116,6 +152,8 @@ class BackgroundJobTask(BaseModel):
image: str | None
command: str | None
env: dict[str, str]
persistent_dir: str | None
stop_timeout_seconds: int
schedule: str | None
enabled: bool
next_run_at: datetime | None
@@ -6,6 +6,7 @@ periodic schedule/reconcile loop.
import asyncio
import logging
import re
import shlex
from datetime import datetime
from threading import RLock
@@ -26,6 +27,7 @@ logger = logging.getLogger(__name__)
settings = config.get_settings()
RUN_STATE_LOCK = RLock()
ORGMINER_DEFAULT_PERSISTENT_DIR = "/app/orgminer_pipeline/runs"
_client: docker.DockerClient | None = None
@@ -145,6 +147,56 @@ def resolve_command(definition: JobDefinition):
return definition.command or None
def uses_orgminer_auto_resume(definition: JobDefinition) -> bool:
"""Return whether the job is the orgminer pipeline in resume mode."""
command = definition.command or ""
try:
command_parts = shlex.split(command)
except ValueError:
return False
is_orgminer = (
"run_pipeline.py" in command_parts
or "orgminer_pipeline" in (definition.image or "")
or "orgminer_pipeline" in definition.name.lower()
)
return is_orgminer and "--auto-resume" in command_parts
def persistent_dir(definition: JobDefinition) -> str | None:
if definition.persistent_dir is not None:
return definition.persistent_dir
if uses_orgminer_auto_resume(definition):
return ORGMINER_DEFAULT_PERSISTENT_DIR
return None
def container_volumes(definition: JobDefinition) -> dict[str, dict[str, str]]:
volumes = {}
data_dir = persistent_dir(definition)
if data_dir:
volumes[f"bgjob-{definition.id}-data"] = {
"bind": data_dir,
"mode": "rw",
}
if is_orgminer(definition) and settings.orgminer_data_volume:
volumes[settings.orgminer_data_volume] = {
"bind": "/data",
"mode": "ro",
}
return volumes
def is_orgminer(definition: JobDefinition) -> bool:
command = definition.command or ""
return (
"run_pipeline.py" in command
or "orgminer_pipeline" in (definition.image or "")
or "orgminer_pipeline" in definition.name.lower()
)
def resolve_environment(definition: JobDefinition) -> dict[str, str]:
base = job_environment() if is_registry_image(resolve_image(definition)) else {}
return {**base, **(definition.env or {})}
@@ -200,15 +252,26 @@ def start_run(
session.refresh(run)
return run
run_options: dict[str, object] = {
"image": image,
"command": resolve_command(definition),
"environment": resolve_environment(definition),
"detach": True,
"name": container_name(definition, run),
"remove": False,
}
data_dir = persistent_dir(definition)
volumes = container_volumes(definition)
if volumes:
run_options["volumes"] = volumes
if data_dir and definition.persistent_dir is None:
logger.info(
"Using orgminer auto-resume data directory '%s' for run %s.",
data_dir,
run.id,
)
try:
container = get_docker_client().containers.run(
image=image,
command=resolve_command(definition),
environment=resolve_environment(definition),
detach=True,
name=container_name(definition, run),
remove=False,
)
container = get_docker_client().containers.run(**run_options)
run.container_id = container.id
except Exception as error:
run.status = JobRunStatus.FAILED
@@ -85,6 +85,8 @@ def _to_task(session: Session, definition: JobDefinition) -> BackgroundJobTask:
image=definition.image,
command=definition.command,
env=definition.env or {},
persistent_dir=definition.persistent_dir,
stop_timeout_seconds=definition.stop_timeout_seconds,
schedule=definition.schedule,
enabled=definition.enabled,
next_run_at=definition.next_run_at,
@@ -141,6 +143,8 @@ def create_task(
target_index=payload.target_index,
schedule=payload.schedule,
enabled=payload.enabled,
persistent_dir=payload.persistent_dir,
stop_timeout_seconds=payload.stop_timeout_seconds,
)
if definition.enabled and definition.schedule:
definition.next_run_at = runner.compute_next_run(definition.schedule)
@@ -166,6 +170,11 @@ def delete_task(
).all()
for run in runs:
session.delete(run)
volume_name = f"bgjob-{definition.id}-data"
try:
runner.get_docker_client().volumes.get(volume_name).remove()
except NotFound:
pass
session.delete(definition)
session.commit()
logger.info(
@@ -331,7 +340,11 @@ def stop_run(
stopped_by_request = False
if container.status not in ("exited", "dead"):
try:
container.stop(timeout=2)
definition = session.get(JobDefinition, run.definition_id)
# Docker stop blocks while waiting and holds RUN_STATE_LOCK for this time.
container.stop(
timeout=definition.stop_timeout_seconds if definition else 2
)
stopped_by_request = True
except APIError as error:
if error.status_code != 304:
+1
View File
@@ -59,6 +59,7 @@ class Settings(BaseSettings):
# Docker SDK inside the service container, which has no `docker login` creds.
background_jobs_registry_username: str | None = None
background_jobs_registry_password: str | None = None
orgminer_data_volume: str = "smartguide-data"
# Sentence Transformers config
sentence_transformers_model_name: str = "intfloat/multilingual-e5-base"
+19
View File
@@ -81,6 +81,25 @@ def _migrate_secret_table():
def create_db_and_tables():
"""Creates the database and tables based on the SQLModel metadata."""
SQLModel.metadata.create_all(engine)
background_job_columns = {
column["name"]
for column in inspect(engine).get_columns("background_job_definition")
}
with engine.begin() as connection:
if "persistent_dir" not in background_job_columns:
connection.execute(
text(
"ALTER TABLE background_job_definition "
"ADD COLUMN persistent_dir VARCHAR"
)
)
if "stop_timeout_seconds" not in background_job_columns:
connection.execute(
text(
"ALTER TABLE background_job_definition "
"ADD COLUMN stop_timeout_seconds INTEGER NOT NULL DEFAULT 10"
)
)
hierarchy_edit_columns = {
column["name"] for column in inspect(engine).get_columns("hierarchy_edits")
}
+1
View File
@@ -8,6 +8,7 @@ from inse.utils import normalize_name
from inse.model import ESCluster, ESIndex
from inse.authors.v2.service import _build_collaboration_graph
from inse.auth.model import Account, Organization
from inse import config
from .model import (
OrgminerContent,
ClassifiedPage,
@@ -1,7 +1,18 @@
import pytest
from inse import config
from inse.projects import eu_cordis_projects_client as eu_cordis_search_client
requires_inse_elasticsearch = pytest.mark.skipif(
not (
config.settings.elasticsearch_inse_url
and config.settings.elasticsearch_inse_api_key
),
reason="INSE Elasticsearch is not configured",
)
@pytest.mark.anyio
async def test_active_period_filter_matches_projects_overlapping_interval():
query, _, _ = await eu_cordis_search_client._build_eu_cordis_search_query(
@@ -18,6 +29,7 @@ async def test_active_period_filter_matches_projects_overlapping_interval():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_by_title():
"""Test searching EU CORDIS projects by title."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
@@ -35,6 +47,7 @@ async def test_search_eu_cordis_projects_by_title():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_by_keywords():
"""Test searching EU CORDIS projects by keywords."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
@@ -51,6 +64,7 @@ async def test_search_eu_cordis_projects_by_keywords():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_by_framework_programme():
"""Test filtering EU CORDIS projects by framework programme."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
@@ -67,6 +81,7 @@ async def test_search_eu_cordis_projects_by_framework_programme():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_by_status():
"""Test filtering EU CORDIS projects by status."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
@@ -83,6 +98,7 @@ async def test_search_eu_cordis_projects_by_status():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_by_funding_years():
"""Test filtering EU CORDIS projects by funding start years."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
@@ -101,6 +117,7 @@ async def test_search_eu_cordis_projects_by_funding_years():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_by_country():
"""Test filtering EU CORDIS projects by country."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
@@ -120,6 +137,7 @@ async def test_search_eu_cordis_projects_by_country():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_by_organization_name():
"""Test filtering EU CORDIS projects by organization name."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
@@ -139,6 +157,7 @@ async def test_search_eu_cordis_projects_by_organization_name():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_by_organization_id():
"""Test filtering EU CORDIS projects by organization ID."""
# Use a known organization ID (e.g., Max Planck Society)
@@ -160,6 +179,7 @@ async def test_search_eu_cordis_projects_by_organization_id():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_by_project_type():
"""Test filtering EU CORDIS projects by project type (FP7, H2020, HEU)."""
from inse.projects.model import EuCordisProjectType
@@ -192,6 +212,7 @@ async def test_search_eu_cordis_projects_by_project_type():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_with_sorting():
"""Test sorting EU CORDIS projects."""
# Test ascending sort by title
@@ -222,6 +243,7 @@ async def test_search_eu_cordis_projects_with_sorting():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_pagination():
"""Test pagination of EU CORDIS project search results."""
# Get first page
@@ -251,6 +273,7 @@ async def test_search_eu_cordis_projects_pagination():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_get_enriched_cordis_project_by_id():
"""Test fetching an enriched EU CORDIS project by ID."""
# Use a known project ID (e.g., an H2020 project)
@@ -269,6 +292,7 @@ async def test_get_enriched_cordis_project_by_id():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_get_enriched_cordis_project_by_id_not_found():
"""Test fetching a non-existent EU CORDIS project."""
project = await eu_cordis_search_client.get_enriched_cordis_project_by_id("nonexistent_id")
@@ -286,6 +310,7 @@ async def test_get_enriched_cordis_project_by_id_empty():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_get_dois_by_cordis_eu_project_id():
"""Test retrieving DOIs for a CORDIS EU project."""
known_id = "101016442" # Example H2020 project ID
@@ -295,6 +320,7 @@ async def test_get_dois_by_cordis_eu_project_id():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_get_openalex_authors_for_cordis_project_ids():
"""Test retrieving OpenAlex authors for CORDIS project IDs."""
project_ids = ["101016442"] # Example H2020 project ID
@@ -312,6 +338,7 @@ async def test_get_openalex_authors_for_cordis_project_ids():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_with_multiple_filters():
"""Test combining multiple filters in EU CORDIS project search."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
@@ -334,6 +361,7 @@ async def test_search_eu_cordis_projects_with_multiple_filters():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_empty_results():
"""Test search that should return no results."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
@@ -347,6 +375,7 @@ async def test_search_eu_cordis_projects_empty_results():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_by_funding_scheme():
"""Test filtering EU CORDIS projects by funding scheme."""
res = await eu_cordis_search_client.search_eu_cordis_projects(
@@ -363,6 +392,7 @@ async def test_search_eu_cordis_projects_by_funding_scheme():
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_eu_cordis_projects_with_fuzzy_topic_search():
"""Test fuzzy search with OpenAlex topic IDs."""
# This test requires known OpenAlex topic IDs
@@ -2,10 +2,21 @@ from unittest.mock import AsyncMock, patch
import pytest
from inse import config
from inse.projects import projects_search_client
requires_inse_elasticsearch = pytest.mark.skipif(
not (
config.settings.elasticsearch_inse_url
and config.settings.elasticsearch_inse_api_key
),
reason="INSE Elasticsearch is not configured",
)
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_search_dfg_projects():
# Test search with name
res = await projects_search_client.search_dfg_projects(
@@ -51,6 +62,7 @@ async def test_search_dfg_projects_returns_empty_page_without_enrichment_crash()
@pytest.mark.anyio
@requires_inse_elasticsearch
async def test_get_dfg_project_by_id():
# Get by ID of the project we found or a known one
known_id = 164008977
@@ -179,7 +179,7 @@ from unittest.mock import AsyncMock, patch
async def test_search_author_works_passes_institution_filter_to_query():
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
client = OpenAlexWorksSearchClient(index="openalex-works")
client = OpenAlexWorksSearchClient(index="openalex-works", api_key="test-key")
await client.search_author_works(
"A5023888391",
@@ -201,7 +201,7 @@ async def test_search_author_works_passes_institution_filter_to_query():
async def test_search_author_works_passes_topic_filter_to_query():
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
client = OpenAlexWorksSearchClient(index="openalex-works")
client = OpenAlexWorksSearchClient(index="openalex-works", api_key="test-key")
await client.search_author_works(
"A5023888391",
@@ -243,7 +243,7 @@ async def test_search_author_works_passes_topic_filter_to_query():
async def test_search_author_works_calls_elasticsearch_index_with_api_key():
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
mock_search.return_value = {"hits": {"total": {"value": 0}, "hits": []}}
client = OpenAlexWorksSearchClient(index="openalex-works")
client = OpenAlexWorksSearchClient(index="openalex-works", api_key="test-key")
result = await client.search_author_works("A5023888391", page=1, size=20)
@@ -254,7 +254,7 @@ async def test_search_author_works_calls_elasticsearch_index_with_api_key():
async def test_search_work_filters_by_work_id():
with patch("inse.integrations.elasticsearch.search", new_callable=AsyncMock) as mock_search:
mock_search.return_value = {"hits": {"total": {"value": 1}, "hits": []}}
client = OpenAlexWorksSearchClient(index="openalex-works")
client = OpenAlexWorksSearchClient(index="openalex-works", api_key="test-key")
await client.search_work("W2741809807")
@@ -17,6 +17,8 @@ export interface BackgroundJobTask {
image: string | null;
command: string | null;
env: { [key: string]: string };
persistent_dir: string | null;
stop_timeout_seconds: number;
schedule: string | null;
enabled: boolean;
next_run_at: string | null;
@@ -17,4 +17,6 @@ export interface JobDefinitionCreateRequest {
target_index?: string;
schedule?: string | null;
enabled?: boolean;
persistent_dir?: string | null;
stop_timeout_seconds?: number;
}
@@ -17,4 +17,6 @@ export interface JobDefinitionUpdateRequest {
target_index?: string | null;
schedule?: string | null;
enabled?: boolean | null;
persistent_dir?: string | null;
stop_timeout_seconds?: number | null;
}
@@ -88,27 +88,34 @@ export class HierarchyComponent implements OnInit {
}
onHierarchyExpandedChange(expanded: boolean): void {
if (this.hierarchyExpanded() === expanded) return;
this.hierarchyExpanded.set(expanded);
this.syncPanelState({ [HIERARCHY_PANEL_PARAM]: expanded });
}
onOrganizationExpandedChange(expanded: boolean): void {
if (this.organizationExpanded() === expanded) return;
this.organizationExpanded.set(expanded);
this.syncPanelState({ [ORGANIZATION_PANEL_PARAM]: expanded });
}
onClassifiedPagesExpandedChange(expanded: boolean): void {
if (this.classifiedPagesExpanded() === expanded) return;
this.classifiedPagesExpanded.set(expanded);
this.syncPanelState({ [CLASSIFIED_PAGES_PANEL_PARAM]: expanded });
}
analyzeOrg(org: { name: string; url: string }) {
this.hierarchyExpanded.set(false);
this.organizationExpanded.set(true);
void this.router.navigate([], {
async analyzeOrg(org: { name: string; url: string }): Promise<void> {
const organizationUrl = org.url.trim();
if (!organizationUrl) return;
// No local signal.set() here: the queryParamMap subscription applies the state.
// Setting hierarchyExpanded directly made the expansion panel emit
// expandedChange, which started a second navigation without the org params.
const navigated = await this.router.navigate([], {
relativeTo: this.route,
queryParams: {
[ORGANIZATION_URL_PARAM]: org.url,
[ORGANIZATION_URL_PARAM]: organizationUrl,
[ORGANIZATION_NAME_PARAM]: org.name,
[ORGMINER_EXPANDED_PARAM]: null,
[ORGMINER_SELECTION_CATEGORY_PARAM]: null,
@@ -121,6 +128,7 @@ export class HierarchyComponent implements OnInit {
queryParamsHandling: 'merge',
replaceUrl: true,
});
if (!navigated) console.warn('[Hierarchy] navigation was cancelled');
}
private syncPanelState(queryParams: Record<string, boolean>): void {
@@ -128,6 +136,7 @@ export class HierarchyComponent implements OnInit {
relativeTo: this.route,
queryParams,
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
@@ -1,247 +1,262 @@
<div class="orgminer">
<!-- ============================ SIDEBAR ============================ -->
<aside class="orgminer-sidebar">
<div class="sidebar-header">
<span class="sidebar-title">
{{ orgName() || 'Organisation' }}
</span>
@if (data()) {
<a
class="sidebar-uri"
[href]="data()!.uri"
target="_blank"
rel="noopener">
{{ data()!.uri }}
</a>
}
</div>
@if (loading()) {
<div class="orgminer-state">
<mat-spinner diameter="32"></mat-spinner>
<span>Lade Orgminer-Inhalte ...</span>
</div>
} @else if (!data()) {
<div class="orgminer-state">
<mat-icon>search_off</mat-icon>
<span
>Für {{ orgName() || 'diese Organisation' }} wurden keine
Orgminer-Inhalte gefunden.</span
>
</div>
} @else {
<div class="orgminer">
<!-- ============================ SIDEBAR ============================ -->
<aside class="orgminer-sidebar">
<div class="sidebar-header">
<span class="sidebar-title">
{{ orgName() || 'Organisation' }}
</span>
@if (data()) {
<a
class="sidebar-uri"
[href]="data()!.uri"
target="_blank"
rel="noopener">
{{ data()!.uri }}
</a>
}
</div>
<nav class="accordion">
<!-- STAFF -->
<div class="accordion-section">
<div class="splitted-accordion">
<nav class="accordion">
<!-- STAFF -->
<div class="accordion-section">
<div class="splitted-accordion">
<button
class="accordion-toggle"
[class.active]="expandedCategory() === 'staff'"
(click)="toggleCategory('staff')">
<mat-icon>{{ PERSONS_ICON }}</mat-icon>
<span class="cat-label">Personal</span>
<span class="cat-count">{{ categoryCount('staff') }}</span>
<span class="chevron" [class.open]="expandedCategory() === 'staff'"
>▾</span
>
</button>
</div>
@if (expandedCategory() === 'staff') {
<ul class="accordion-list">
@for (person of sortedStaff(); track person.name) {
<li
class="accordion-item"
[class.selected]="isSelected('staff', person)"
(click)="selectItem('staff', person)">
{{ person.name }}
@if (isVerified(person.name)) {
<mat-icon
class="verified-badge"
matTooltip="Verified Staff Member"
>verified</mat-icon
>
}
</li>
<span></span>
}
</ul>
}
</div>
<!-- PROJECTS -->
<div class="accordion-section">
<button
class="accordion-toggle"
[class.active]="expandedCategory() === 'staff'"
(click)="toggleCategory('staff')">
<mat-icon>{{ PERSONS_ICON }}</mat-icon>
<span class="cat-label">Personal</span>
<span class="cat-count">{{ categoryCount('staff') }}</span>
<span class="chevron" [class.open]="expandedCategory() === 'staff'"
[class.active]="expandedCategory() === 'projects'"
(click)="toggleCategory('projects')">
<mat-icon>{{ PROJECT_ICON }}</mat-icon>
<span class="cat-label">Projekte</span>
<span class="cat-count">{{ categoryCount('projects') }}</span>
<span class="chevron" [class.open]="expandedCategory() === 'projects'"
>▾</span
>
</button>
@if (expandedCategory() === 'projects') {
<ul class="accordion-list">
@for (project of data()?.projects ?? []; track project.title) {
<li
class="accordion-item"
[class.selected]="isSelected('projects', project)"
(click)="selectItem('projects', project)">
{{ project.title }}
</li>
}
</ul>
}
</div>
@if (expandedCategory() === 'staff') {
<ul class="accordion-list">
@for (person of sortedStaff(); track person.name) {
<li
class="accordion-item"
[class.selected]="isSelected('staff', person)"
(click)="selectItem('staff', person)">
{{ person.name }}
@if (isVerified(person.name)) {
<mat-icon
class="verified-badge"
matTooltip="Verified Staff Member"
>verified</mat-icon
>
}
</li>
<!-- NEWS -->
<div class="accordion-section">
<button
class="accordion-toggle"
[class.active]="expandedCategory() === 'news'"
(click)="toggleCategory('news')">
<mat-icon>{{ NEWS_ICON }}</mat-icon>
<span class="cat-label">Nachrichten</span>
<span class="cat-count">{{ categoryCount('news') }}</span>
<span class="chevron" [class.open]="expandedCategory() === 'news'"
>▾</span
>
</button>
<span></span>
@if (expandedCategory() === 'news') {
<ul class="accordion-list">
@for (n of data()?.news ?? []; track n.title) {
<li
class="accordion-item"
[class.selected]="isSelected('news', n)"
(click)="selectItem('news', n)">
{{ n.title }}
</li>
}
</ul>
}
</div>
</nav>
</aside>
<!-- ============================ DETAIL PANEL ============================ -->
<main class="orgminer-detail">
@if (!selection()) {
<div class="empty-state">
<p>Wählen Sie links ein Element aus, um Details anzuzeigen.</p>
</div>
}
<!-- ---------------------------- STAFF DETAIL ---------------------------- -->
@if (selectedStaff(); as staff) {
<div class="detail-card">
<h2 class="detail-title">{{ staff.name }}</h2>
<div class="detail-fields">
@if (staff.email) {
<div class="detail-row">
<span class="detail-label">E-Mail</span>
<a class="detail-value" [href]="'mailto:' + staff.email">{{
staff.email
}}</a>
</div>
}
</ul>
}
</div>
<!-- PROJECTS -->
<div class="accordion-section">
<button
class="accordion-toggle"
[class.active]="expandedCategory() === 'projects'"
(click)="toggleCategory('projects')">
<mat-icon>{{ PROJECT_ICON }}</mat-icon>
<span class="cat-label">Projekte</span>
<span class="cat-count">{{ categoryCount('projects') }}</span>
<span class="chevron" [class.open]="expandedCategory() === 'projects'"
>▾</span
>
</button>
@if (expandedCategory() === 'projects') {
<ul class="accordion-list">
@for (project of data()?.projects ?? []; track project.title) {
<li
class="accordion-item"
[class.selected]="isSelected('projects', project)"
(click)="selectItem('projects', project)">
{{ project.title }}
</li>
@if (staff.telefon) {
<div class="detail-row">
<span class="detail-label">Telefon</span>
<a class="detail-value" [href]="'tel:' + staff.telefon">{{
staff.telefon
}}</a>
</div>
}
</ul>
}
</div>
<!-- NEWS -->
<div class="accordion-section">
<button
class="accordion-toggle"
[class.active]="expandedCategory() === 'news'"
(click)="toggleCategory('news')">
<mat-icon>{{ NEWS_ICON }}</mat-icon>
<span class="cat-label">Nachrichten</span>
<span class="cat-count">{{ categoryCount('news') }}</span>
<span class="chevron" [class.open]="expandedCategory() === 'news'"
>▾</span
>
</button>
@if (expandedCategory() === 'news') {
<ul class="accordion-list">
@for (n of data()?.news ?? []; track n.title) {
<li
class="accordion-item"
[class.selected]="isSelected('news', n)"
(click)="selectItem('news', n)">
{{ n.title }}
</li>
@if (staff.links?.length) {
<div class="detail-row">
<span class="detail-label">Links</span>
<div class="detail-links">
@for (link of staff.links; track link) {
<a [href]="link" target="_blank" rel="noopener">{{ link }}</a>
}
</div>
</div>
}
</ul>
}
</div>
</nav>
</aside>
<!-- ============================ DETAIL PANEL ============================ -->
<main class="orgminer-detail">
@if (!selection()) {
<div class="empty-state">
<p>Wählen Sie links ein Element aus, um Details anzuzeigen.</p>
</div>
}
<!-- ---------------------------- STAFF DETAIL ---------------------------- -->
@if (selectedStaff(); as staff) {
<div class="detail-card">
<h2 class="detail-title">{{ staff.name }}</h2>
<div class="detail-fields">
@if (staff.email) {
<div class="detail-row">
<span class="detail-label">E-Mail</span>
<a class="detail-value" [href]="'mailto:' + staff.email">{{
staff.email
}}</a>
</div>
}
@if (staff.telefon) {
<div class="detail-row">
<span class="detail-label">Telefon</span>
<a class="detail-value" [href]="'tel:' + staff.telefon">{{
staff.telefon
}}</a>
</div>
}
@if (staff.links?.length) {
<div class="detail-row">
<span class="detail-label">Links</span>
<div class="detail-links">
@for (link of staff.links; track link) {
<a [href]="link" target="_blank" rel="noopener">{{ link }}</a>
}
@if (researchInterests(staff).length) {
<div class="detail-row">
<span class="detail-label">Forschungsinteressen</span>
<div class="chip-list">
@for (ri of researchInterests(staff); track ri) {
<app-chip> {{ ri }}</app-chip>
}
</div>
</div>
</div>
}
@if (researchInterests(staff).length) {
<div class="detail-row">
<span class="detail-label">Forschungsinteressen</span>
<div class="chip-list">
@for (ri of researchInterests(staff); track ri) {
<app-chip> {{ ri }}</app-chip>
}
}
</div>
<app-keyword-wordcloud [words]="selection()?.item?.keywords || []" />
</div>
}
<!-- --------------------------- PROJECT DETAIL --------------------------- -->
@if (selectedProject(); as project) {
<div class="detail-card">
<div class="detail-title-row">
<h2 class="detail-title">{{ project.title }}</h2>
@if (project.project_type) {
<app-chip>
{{ project.project_type }}
</app-chip>
}
</div>
<div class="detail-fields">
@if (project.topic) {
<div class="detail-row">
<span class="detail-label">Thema</span>
<span class="detail-value">{{ project.topic }}</span>
</div>
</div>
}
</div>
<app-keyword-wordcloud [words]="selection()?.item?.keywords || []" />
</div>
}
<!-- --------------------------- PROJECT DETAIL --------------------------- -->
@if (selectedProject(); as project) {
<div class="detail-card">
<div class="detail-title-row">
<h2 class="detail-title">{{ project.title }}</h2>
@if (project.project_type) {
<app-chip>
{{ project.project_type }}
</app-chip>
}
</div>
<div class="detail-fields">
@if (project.topic) {
<div class="detail-row">
<span class="detail-label">Thema</span>
<span class="detail-value">{{ project.topic }}</span>
</div>
}
@if (project.names) {
<div class="detail-row">
<span class="detail-label">Verantwortlich</span>
<span class="detail-value">{{ project.names }}</span>
</div>
}
@if (project.links?.length) {
<div class="detail-row">
<span class="detail-label">Links</span>
<div class="detail-links">
@for (link of project.links; track $index) {
<a [href]="link" target="_blank" rel="noopener">{{ link }}</a>
}
}
@if (project.names) {
<div class="detail-row">
<span class="detail-label">Verantwortlich</span>
<span class="detail-value">{{ project.names }}</span>
</div>
</div>
}
</div>
<app-keyword-wordcloud [words]="selection()?.item?.keywords || []" />
</div>
}
<!-- ----------------------------- NEWS DETAIL ----------------------------- -->
@if (selectedNews(); as news) {
<div class="detail-card">
<h2 class="detail-title">{{ news.title }}</h2>
<div class="detail-fields">
@if (news.date) {
<div class="detail-row">
<span class="detail-label">Datum</span>
<span class="detail-value">{{ news.date }}</span>
</div>
}
@if (news.topic) {
<div class="detail-row">
<span class="detail-label">Thema</span>
<span class="detail-value">{{ news.topic }}</span>
</div>
}
@if (news.links?.length) {
<div class="detail-row">
<span class="detail-label">Links</span>
<div class="detail-links">
@for (link of news.links; track link) {
<a [href]="link" target="_blank" rel="noopener">{{ link }}</a>
}
}
@if (project.links?.length) {
<div class="detail-row">
<span class="detail-label">Links</span>
<div class="detail-links">
@for (link of project.links; track $index) {
<a [href]="link" target="_blank" rel="noopener">{{ link }}</a>
}
</div>
</div>
</div>
}
}
</div>
<app-keyword-wordcloud [words]="selection()?.item?.keywords || []" />
</div>
}
<app-keyword-wordcloud [words]="selection()?.item?.keywords || []" />
</div>
}
</main>
</div>
<!-- ----------------------------- NEWS DETAIL ----------------------------- -->
@if (selectedNews(); as news) {
<div class="detail-card">
<h2 class="detail-title">{{ news.title }}</h2>
<div class="detail-fields">
@if (news.date) {
<div class="detail-row">
<span class="detail-label">Datum</span>
<span class="detail-value">{{ news.date }}</span>
</div>
}
@if (news.topic) {
<div class="detail-row">
<span class="detail-label">Thema</span>
<span class="detail-value">{{ news.topic }}</span>
</div>
}
@if (news.links?.length) {
<div class="detail-row">
<span class="detail-label">Links</span>
<div class="detail-links">
@for (link of news.links; track link) {
<a [href]="link" target="_blank" rel="noopener">{{ link }}</a>
}
</div>
</div>
}
</div>
<app-keyword-wordcloud [words]="selection()?.item?.keywords || []" />
</div>
}
</main>
</div>
}
@@ -1,3 +1,19 @@
.orgminer-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
min-height: 320px;
padding: 24px;
border: 1px dashed var(--sg-border);
border-radius: 8px;
background: var(--sg-card-bg);
color: var(--sg-text-muted);
font-size: 0.95rem;
text-align: center;
}
.orgminer {
display: flex;
width: 100%;
@@ -28,6 +28,7 @@ import {
NEWS_ICON,
} from '../../../shared/ui/icons';
import { MatTooltip } from '@angular/material/tooltip';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { OrgminerService } from '../../../api/api/orgminer.service';
/* ------------------------------ Data model ------------------------------ */
@@ -50,6 +51,7 @@ interface Selection {
MatIconModule,
ChipComponent,
MatTooltip,
MatProgressSpinnerModule,
],
templateUrl: './orgminer-content.component.html',
styleUrls: ['./orgminer-content.component.scss'],
@@ -63,7 +65,11 @@ export class OrgminerContentComponent implements OnInit {
private readonly route = inject(ActivatedRoute);
private readonly destroyRef = inject(DestroyRef);
private isOwnNavigation = false;
readonly data = toSignal(
/**
* `undefined` means the request is still running, `null` means the backend
* knows no orgminer document for this URL.
*/
readonly data = toSignal<OrgminerContent | null | undefined>(
toObservable(this.orgUrl).pipe(
switchMap((orgUrl) =>
orgUrl
@@ -73,8 +79,9 @@ export class OrgminerContentComponent implements OnInit {
: of(null),
),
),
{ initialValue: null },
{ initialValue: undefined },
);
readonly loading = computed(() => this.data() === undefined);
private readonly restoreStateEffect = effect(() => {
if (this.data()) {
this.restoreStateFromUrl();
@@ -96,6 +96,21 @@
<mat-error>Ungültige Zeile — Format: KEY=value.</mat-error>
}
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Persistenter Pfad (optional)</mat-label>
<input matInput formControlName="persistentDir" placeholder="/data/job" />
<mat-hint>Absoluter Pfad im Container; Daten bleiben zwischen Läufen erhalten.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Stop-Timeout (Sekunden)</mat-label>
<input matInput type="number" formControlName="stopTimeoutSeconds" min="1" max="600" />
<mat-hint>1 bis 600 Sekunden.</mat-hint>
@if (form.controls.stopTimeoutSeconds.invalid) {
<mat-error>Bitte einen Wert zwischen 1 und 600 eingeben.</mat-error>
}
</mat-form-field>
</form>
@if (serverError()) {
@@ -63,6 +63,11 @@ export class TaskCreateDialogComponent implements OnInit {
validators: [Validators.required],
}),
env: new FormControl('', { nonNullable: true }),
persistentDir: new FormControl('', { nonNullable: true }),
stopTimeoutSeconds: new FormControl(10, {
nonNullable: true,
validators: [Validators.min(1), Validators.max(600)],
}),
});
private readonly imageQuery = toSignal(
@@ -104,6 +109,10 @@ export class TaskCreateDialogComponent implements OnInit {
const command = value.command.trim() || null;
const env = this.parseEnv(value.env);
if (env === undefined) return;
if (value.stopTimeoutSeconds < 1 || value.stopTimeoutSeconds > 600) {
this.form.controls.stopTimeoutSeconds.markAsTouched();
return;
}
this.creating.set(true);
this.backgroundJobsService
@@ -114,6 +123,8 @@ export class TaskCreateDialogComponent implements OnInit {
image,
command,
env,
persistent_dir: value.persistentDir.trim() || null,
stop_timeout_seconds: value.stopTimeoutSeconds,
})
.subscribe({
next: (task) => this.dialogRef.close(task),
@@ -96,6 +96,21 @@
<mat-error>Ungültige Zeile — Format: KEY=value.</mat-error>
}
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Persistenter Pfad (optional)</mat-label>
<input matInput formControlName="persistentDir" placeholder="/data/job" />
<mat-hint>Absoluter Pfad im Container; Daten bleiben zwischen Läufen erhalten.</mat-hint>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Stop-Timeout (Sekunden)</mat-label>
<input matInput type="number" formControlName="stopTimeoutSeconds" min="1" max="600" />
<mat-hint>1 bis 600 Sekunden.</mat-hint>
@if (form.controls.stopTimeoutSeconds.invalid) {
<mat-error>Bitte einen Wert zwischen 1 und 600 eingeben.</mat-error>
}
</mat-form-field>
</form>
@if (serverError()) {
@@ -80,6 +80,13 @@ export class TaskEditDialogComponent implements OnInit {
env: new FormControl(this.envToText(this.data.task.env), {
nonNullable: true,
}),
persistentDir: new FormControl(this.data.task.persistent_dir ?? '', {
nonNullable: true,
}),
stopTimeoutSeconds: new FormControl(this.data.task.stop_timeout_seconds, {
nonNullable: true,
validators: [Validators.min(1), Validators.max(600)],
}),
});
private readonly imageQuery = toSignal(
@@ -120,6 +127,10 @@ export class TaskEditDialogComponent implements OnInit {
const env = this.parseEnv(value.env);
if (env === undefined) return;
if (value.stopTimeoutSeconds < 1 || value.stopTimeoutSeconds > 600) {
this.form.controls.stopTimeoutSeconds.markAsTouched();
return;
}
this.saving.set(true);
this.backgroundJobsService
@@ -130,6 +141,8 @@ export class TaskEditDialogComponent implements OnInit {
image,
command: value.command.trim() || null,
env,
persistent_dir: value.persistentDir.trim() || null,
stop_timeout_seconds: value.stopTimeoutSeconds,
})
.subscribe({
next: (task) => this.dialogRef.close(task),