Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
@@ -0,0 +1,59 @@
|
||||
# Career-Stage-Analyse
|
||||
|
||||
Diese Analyse untersucht, wie sich der Karrierestatus von Forschenden (Professor vs.
|
||||
Researcher) aus deren Publikationshistorie in OpenAlex ableiten lässt. Das Ergebnis ist die
|
||||
Grundlage für die Career-Stage-Klassifikation im SmartGuide-Backend.
|
||||
|
||||
## Vorgehen
|
||||
|
||||
- **Stichprobe:** 60 Forschende der UDE mit manuell recherchiertem, bekanntem Status
|
||||
(31 Professor, 29 Researcher inkl. Doctoral Researcher) aus fünf Disziplingruppen:
|
||||
Biology, Computer Science, Engineering, Medicine, Sociology
|
||||
([career_stage_sample.csv](career_stage_sample.csv)).
|
||||
- **Datenerhebung:** Für jede Person wurden alle Werke über die OpenAlex-API geladen
|
||||
([openalex_client.py](openalex_client.py)) und daraus pro Person Metriken berechnet
|
||||
([career_stage_analysis.py](career_stage_analysis.py) →
|
||||
[career_stage_results.csv](career_stage_results.csv)):
|
||||
- `career_span`: Jahre vom ersten bis zum letzten Publikationsjahr (inklusiv)
|
||||
- `active_years`: Anzahl **unterschiedlicher** Jahre mit mindestens einer Publikation
|
||||
- `publication_count`, `publications_per_active_year`, `publications_per_career_year`,
|
||||
`years_since_last_publication`
|
||||
- **Auswertung:** Vergleich der Metriken zwischen den bekannten Status-Gruppen, auch je
|
||||
Disziplingruppe ([career_stage_visualization.py](career_stage_visualization.py) →
|
||||
[plots/](plots/), [summaries/](summaries/)).
|
||||
|
||||
## Ergebnisse
|
||||
|
||||
Die Gruppen trennen sich deutlich (Median Professor vs. Researcher):
|
||||
|
||||
| Metrik | Professor | Researcher |
|
||||
| ----------------------------- | --------- | ---------- |
|
||||
| Aktive Publikationsjahre | 28 | 5 |
|
||||
| Career Span (Jahre) | 31 | 7 |
|
||||
| Publikationen | 224 | 11 |
|
||||
| Publikationen je aktivem Jahr | 7,6 | 1,8 |
|
||||
|
||||
Wichtigste Erkenntnis: **`career_span` ist unzuverlässig.** Fehlerhafte Autorenzuordnungen in
|
||||
OpenAlex führen zu unplausibel frühen Erstpublikationen (z. B. 1893/1906 bei aktiven
|
||||
Professor:innen) und blähen die Spannweite massiv auf (Mittelwert 45 Jahre bei Median 31).
|
||||
**`active_years` ist dagegen robust:** Ein einzelnes falsch zugeordnetes altes Werk erhöht die
|
||||
Spannweite um Jahrzehnte, die aktiven Jahre aber nur um 1. Die Trennung zwischen den Gruppen
|
||||
ist bei `active_years` zudem über alle Disziplingruppen hinweg konsistent.
|
||||
|
||||
## Fazit: finale Entscheidungskriterien im Projekt
|
||||
|
||||
Die Career Stage wird im Backend ausschließlich über die **aktiven Publikationsjahre**
|
||||
(`active_years`) bestimmt (siehe `_classify_career_stage` in
|
||||
`service/src/main/inse/persons/logic.py`):
|
||||
|
||||
| Aktive Jahre | Career Stage |
|
||||
| ------------ | ------------ |
|
||||
| 0 | unknown |
|
||||
| 1–4 | Early |
|
||||
| 5–9 | Emerging |
|
||||
| 10–14 | Established |
|
||||
| ≥ 15 | Senior |
|
||||
|
||||
Zusätzlich wird `has_suspicious_publication_years` gesetzt (Erstpublikation vor 1970 oder
|
||||
Career Span > 60 Jahre), um Personen mit vermutlich fehlerhafter OpenAlex-Zuordnung zu
|
||||
kennzeichnen.
|
||||
@@ -0,0 +1,195 @@
|
||||
import csv
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from openalex_client import get_all_author_works
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
INPUT_FILE = BASE_DIR / "career_stage_sample.csv"
|
||||
OUTPUT_FILE = BASE_DIR / "career_stage_results.csv"
|
||||
|
||||
|
||||
def extract_publication_years(works: list[dict[str, Any]]) -> list[int]:
|
||||
"""
|
||||
Extracts all valid publication years from the OpenAlex works response.
|
||||
|
||||
One entry in the returned list represents one publication.
|
||||
Therefore, duplicate years are intentionally kept.
|
||||
Example:
|
||||
[2020, 2020, 2021] means 3 publications in 2 active years.
|
||||
"""
|
||||
years: list[int] = []
|
||||
|
||||
for work in works:
|
||||
year = work.get("publication_year")
|
||||
|
||||
if isinstance(year, int):
|
||||
years.append(year)
|
||||
elif isinstance(year, str) and year.isdigit():
|
||||
years.append(int(year))
|
||||
|
||||
return years
|
||||
|
||||
|
||||
def normalize_known_status(known_status: str) -> str:
|
||||
"""
|
||||
Normalizes manually assigned status labels.
|
||||
|
||||
The analysis compares Professor vs Researcher. Doctoral Researcher is therefore
|
||||
mapped to Researcher to keep the groups consistent.
|
||||
"""
|
||||
cleaned_status = known_status.strip()
|
||||
|
||||
if cleaned_status == "Doctoral Researcher":
|
||||
return "Researcher"
|
||||
|
||||
return cleaned_status
|
||||
|
||||
|
||||
def compute_metrics(publication_years: list[int]) -> dict[str, int | float | None]:
|
||||
"""
|
||||
Computes publication-history-based career metrics.
|
||||
|
||||
Important distinction:
|
||||
- publication_count counts all publications
|
||||
- active_years counts distinct years with at least one publication
|
||||
- career_span counts the full inclusive span from first to last publication year
|
||||
"""
|
||||
current_year = datetime.now().year
|
||||
|
||||
if not publication_years:
|
||||
return {
|
||||
"first_publication_year": None,
|
||||
"last_publication_year": None,
|
||||
"career_age": None,
|
||||
"career_span": None,
|
||||
"active_years": 0,
|
||||
"publication_count": 0,
|
||||
"publications_per_active_year": None,
|
||||
"publications_per_career_year": None,
|
||||
"years_since_last_publication": None,
|
||||
}
|
||||
|
||||
sorted_years = sorted(publication_years)
|
||||
unique_years = sorted(set(publication_years))
|
||||
|
||||
first_year = sorted_years[0]
|
||||
last_year = sorted_years[-1]
|
||||
|
||||
publication_count = len(sorted_years)
|
||||
active_years = len(unique_years)
|
||||
|
||||
career_age = last_year - first_year
|
||||
career_span = last_year - first_year + 1
|
||||
|
||||
publications_per_active_year = (
|
||||
publication_count / active_years if active_years > 0 else None
|
||||
)
|
||||
|
||||
publications_per_career_year = (
|
||||
publication_count / career_span if career_span > 0 else None
|
||||
)
|
||||
|
||||
years_since_last_publication = current_year - last_year
|
||||
|
||||
return {
|
||||
"first_publication_year": first_year,
|
||||
"last_publication_year": last_year,
|
||||
"career_age": career_age,
|
||||
"career_span": career_span,
|
||||
"active_years": active_years,
|
||||
"publication_count": publication_count,
|
||||
"publications_per_active_year": publications_per_active_year,
|
||||
"publications_per_career_year": publications_per_career_year,
|
||||
"years_since_last_publication": years_since_last_publication,
|
||||
}
|
||||
|
||||
|
||||
def create_empty_metrics() -> dict[str, int | float | None]:
|
||||
return {
|
||||
"first_publication_year": None,
|
||||
"last_publication_year": None,
|
||||
"career_age": None,
|
||||
"career_span": None,
|
||||
"active_years": 0,
|
||||
"publication_count": 0,
|
||||
"publications_per_active_year": None,
|
||||
"publications_per_career_year": None,
|
||||
"years_since_last_publication": None,
|
||||
}
|
||||
|
||||
|
||||
def analyze_sample() -> None:
|
||||
if not INPUT_FILE.exists():
|
||||
raise FileNotFoundError(f"Input file not found: {INPUT_FILE}")
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
|
||||
with INPUT_FILE.open(mode="r", encoding="utf-8", newline="") as input_file:
|
||||
reader = csv.DictReader(input_file)
|
||||
|
||||
for row in reader:
|
||||
name = row.get("name", "").strip()
|
||||
discipline = row.get("discipline", "").strip()
|
||||
discipline_group = row.get("discipline_group", "").strip()
|
||||
known_status = normalize_known_status(row.get("known_status", ""))
|
||||
openalex_author_id = row.get("openalex_author_id", "").strip()
|
||||
|
||||
if not discipline_group:
|
||||
discipline_group = discipline
|
||||
|
||||
if not openalex_author_id:
|
||||
print(f"Skipping {name}: missing OpenAlex author ID")
|
||||
continue
|
||||
|
||||
print(f"Fetching works for {name} ({openalex_author_id})...")
|
||||
|
||||
try:
|
||||
works = get_all_author_works(openalex_author_id)
|
||||
publication_years = extract_publication_years(works)
|
||||
metrics = compute_metrics(publication_years)
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error while processing {name}: {error}")
|
||||
metrics = create_empty_metrics()
|
||||
|
||||
results.append(
|
||||
{
|
||||
"name": name,
|
||||
"discipline": discipline,
|
||||
"discipline_group": discipline_group,
|
||||
"known_status": known_status,
|
||||
"openalex_author_id": openalex_author_id,
|
||||
**metrics,
|
||||
}
|
||||
)
|
||||
|
||||
fieldnames = [
|
||||
"name",
|
||||
"discipline",
|
||||
"discipline_group",
|
||||
"known_status",
|
||||
"openalex_author_id",
|
||||
"first_publication_year",
|
||||
"last_publication_year",
|
||||
"career_age",
|
||||
"career_span",
|
||||
"active_years",
|
||||
"publication_count",
|
||||
"publications_per_active_year",
|
||||
"publications_per_career_year",
|
||||
"years_since_last_publication",
|
||||
]
|
||||
|
||||
with OUTPUT_FILE.open(mode="w", encoding="utf-8", newline="") as output_file:
|
||||
writer = csv.DictWriter(output_file, fieldnames=fieldnames)
|
||||
writer.writeheader()
|
||||
writer.writerows(results)
|
||||
|
||||
print(f"Analysis finished. Results written to {OUTPUT_FILE}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
analyze_sample()
|
||||
@@ -0,0 +1,61 @@
|
||||
name,discipline,discipline_group,known_status,openalex_author_id,first_publication_year,last_publication_year,career_age,career_span,active_years,publication_count,publications_per_active_year,publications_per_career_year,years_since_last_publication
|
||||
Barbara Saccà,Biology,Biology,Professor,A5075803366,1997,2024,27,28,26,91,3.5,3.25,2
|
||||
Bernd Sures,Biology,Biology,Professor,A5088631999,1994,2026,32,33,32,410,12.8125,12.424242424242424,0
|
||||
Daniel Hering,Biology,Biology,Professor,A5031147249,1893,2026,133,134,37,326,8.81081081081081,2.4328358208955225,0
|
||||
Daniel Hoffmann,Biology,Biology,Professor,A5074555350,1966,2026,60,61,35,332,9.485714285714286,5.442622950819672,0
|
||||
Peter Bayer,Biology,Biology,Professor,A5060566345,1969,2026,57,58,37,358,9.675675675675675,6.172413793103448,0
|
||||
Bianca Kamba,Biology,Biology,Researcher,A5036363877,2017,2025,8,9,4,9,2.25,1.0,1
|
||||
Daniel Grabner,Biology,Biology,Researcher,A5063959731,1980,2026,46,47,19,95,5.0,2.021276595744681,0
|
||||
Farnusch Kaschani,Biology,Biology,Researcher,A5078099512,2005,2026,21,22,21,182,8.666666666666666,8.272727272727273,0
|
||||
Kathrin Januschke,Biology,Biology,Researcher,A5064225981,2011,2026,15,16,15,36,2.4,2.25,0
|
||||
Richard Kosinski,Biology,Biology,Researcher,A5014403509,1986,2022,36,37,4,6,1.5,0.16216216216216217,4
|
||||
Jens Krüger,Computer Graphics and Visualization,Computer Science,Professor,A5087449583,1964,2025,61,62,20,67,3.35,1.0806451612903225,1
|
||||
Torben Weis,Distributed Systems,Computer Science,Professor,A5016729057,1980,2026,46,47,43,197,4.5813953488372094,4.191489361702128,0
|
||||
Stefan Schneegaß,Human Computer Interaction,Computer Science,Professor,A5024328962,2008,2026,18,19,17,224,13.176470588235293,11.789473684210526,0
|
||||
Gregor Schiele,Intelligent Embedded Systems,Computer Science,Professor,A5028943371,1999,2026,27,28,22,155,7.045454545454546,5.535714285714286,0
|
||||
Pedro José Marrón,Networked Embedded Systems,Computer Science,Professor,A5047117780,1996,2026,30,31,28,285,10.178571428571429,9.193548387096774,0
|
||||
Lucas Davi,Secure Software Systems,Computer Science,Professor,A5089242868,2009,2026,17,18,18,137,7.611111111111111,7.611111111111111,0
|
||||
Volker Gruhn,Software Engineering,Computer Science,Professor,A5049739067,1989,2025,36,37,36,410,11.38888888888889,11.08108108108108,1
|
||||
Andreas Metzger,Software Systems Engineering,Computer Science,Professor,A5082025709,1992,2026,34,35,28,202,7.214285714285714,5.771428571428571,0
|
||||
Andreas Vogelsang,Software Systems Engineering,Computer Science,Professor,A5022998651,2005,2026,21,22,20,225,11.25,10.227272727272727,0
|
||||
Barbara König,Theoretical Computer Science,Computer Science,Professor,A5103103785,1906,2026,120,121,36,230,6.388888888888889,1.9008264462809918,0
|
||||
Alexandra Dmitrienko,Vertrauenswürdige Systeme,Computer Science,Professor,A5042835341,2010,2026,16,17,17,110,6.470588235294118,6.470588235294118,0
|
||||
Carina Liebers,Human Computer Interaction,Computer Science,Researcher,A5004350173,2022,2026,4,5,5,11,2.2,2.2,0
|
||||
Jonas Keppel,Human Computer Interaction,Computer Science,Researcher,A5015767175,2022,2026,4,5,5,11,2.2,2.2,0
|
||||
Carlos Medina Sánchez,Networked Embedded Systems,Computer Science,Researcher,A5093479876,2023,2025,2,3,2,2,1.0,0.6666666666666666,1
|
||||
Marcus Handte,Networked Embedded Systems,Computer Science,Researcher,A5007170803,2004,2026,22,23,23,107,4.6521739130434785,4.6521739130434785,0
|
||||
Simon Janzon,Networked Embedded Systems,Computer Science,Researcher,A5044472300,2020,2025,5,6,5,6,1.2,1.0,1
|
||||
Christian Niesler,Secure Software Systems,Computer Science,Researcher,A5069184110,2021,2026,5,6,5,9,1.8,1.5,0
|
||||
Christian Scholz,Secure Software Systems,Computer Science,Researcher,A5120610207,2025,2026,1,2,2,2,1.0,1.0,0
|
||||
Pascal Winkler,Secure Software Systems,Computer Science,Researcher,A5081189339,2009,2026,17,18,6,22,3.6666666666666665,1.2222222222222223,0
|
||||
Stefan Hanenberg,Software Engineering,Computer Science,Researcher,A5027034338,2000,2025,25,26,25,105,4.2,4.038461538461538,1
|
||||
Wilhelm Koop,Software Engineering,Computer Science,Researcher,A5019228221,2016,2022,6,7,6,14,2.3333333333333335,2.0,4
|
||||
Venkata Marella,Vertrauenswürdige Systeme,Computer Science,Researcher,A5082156768,2017,2026,9,10,8,11,1.375,1.1,0
|
||||
Burak Atakan,Engineering,Engineering,Professor,A5041521847,1989,2026,37,38,35,202,5.771428571428571,5.315789473684211,0
|
||||
Corina Andronescu,Engineering,Engineering,Professor,A5082583063,2008,2026,18,19,19,137,7.2105263157894735,7.2105263157894735,0
|
||||
Gerd Bacher,Engineering,Engineering,Professor,A5056038758,1985,2026,41,42,38,385,10.131578947368421,9.166666666666666,0
|
||||
Miriam Böhm,Engineering,Engineering,Researcher,A5037448457,2011,2021,10,11,8,12,1.5,1.0909090909090908,5
|
||||
Soheil Salighe,Steuerung Regelung und Systemdynamik,Engineering,Researcher,A5041884757,2017,2024,7,8,5,7,1.4,0.875,2
|
||||
Tobias Mikolas,Engineering,Engineering,Researcher,A5002909977,2021,2023,2,3,2,2,1.0,0.6666666666666666,3
|
||||
Boris Hadaschik,Medicine,Medicine,Professor,A5077243123,2001,2026,25,26,24,791,32.958333333333336,30.423076923076923,0
|
||||
Hartmut Schmidt,Medicine,Medicine,Professor,A5015932441,1910,2026,116,117,63,1024,16.253968253968253,8.752136752136753,0
|
||||
Matthias Gunzer,Medicine,Medicine,Professor,A5020520632,1997,2026,29,30,29,343,11.827586206896552,11.433333333333334,0
|
||||
Oliver Witzke,Medicine,Medicine,Professor,A5087456839,1954,2026,72,73,34,615,18.08823529411765,8.424657534246576,0
|
||||
Stephan Lang,Medicine,Medicine,Professor,A5030649192,1929,2026,97,98,44,859,19.522727272727273,8.76530612244898,0
|
||||
Tienush Rassaf,Medicine,Medicine,Professor,A5048609556,2002,2025,23,24,19,62,3.263157894736842,2.5833333333333335,1
|
||||
Ulrike Bingel,Medicine,Medicine,Professor,A5002281474,1998,2026,28,29,27,315,11.666666666666666,10.862068965517242,0
|
||||
Birte Möhlendick,Medicine,Medicine,Researcher,A5030635588,2010,2025,15,16,14,48,3.4285714285714284,3.0,1
|
||||
Julia Schwichtenberg,Medicine,Medicine,Researcher,A5119372151,2025,2026,1,2,2,3,1.5,1.5,0
|
||||
Katrin Schuldt,Medicine,Medicine,Researcher,A5002003996,2000,2026,26,27,7,12,1.7142857142857142,0.4444444444444444,0
|
||||
Sabrina Guckenbiehl,Medicine,Medicine,Researcher,A5008120333,2021,2026,5,6,6,31,5.166666666666667,5.166666666666667,0
|
||||
Zülal Cibir,Medicine,Medicine,Researcher,A5035081158,2019,2025,6,7,7,21,3.0,3.0,1
|
||||
Frank Kleemann,Sociology,Sociology,Professor,A5041694590,1999,2025,26,27,22,106,4.818181818181818,3.925925925925926,1
|
||||
Gregor Bongaerts,Sociology,Sociology,Professor,A5012265262,2000,2025,25,26,18,55,3.0555555555555554,2.1153846153846154,1
|
||||
Helen Baykara-Krumme,Sociology,Sociology,Professor,A5010111732,2007,2026,19,20,19,71,3.736842105263158,3.55,0
|
||||
Marcel Erlinghagen,Sociology,Sociology,Professor,A5021715937,1970,2026,56,57,29,131,4.517241379310345,2.2982456140350878,0
|
||||
Ute Klammer,Sociology,Sociology,Professor,A5055077517,1997,2026,29,30,25,146,5.84,4.866666666666666,0
|
||||
Andreas Jansen,Sociology,Sociology,Researcher,A5030957194,1991,2026,35,36,12,15,1.25,0.4166666666666667,0
|
||||
Antonia Görtz,Sociology,Sociology,Researcher,A5066776558,2022,2025,3,4,2,2,1.0,0.5,1
|
||||
Friedrich Scheller,Sociology,Sociology,Researcher,A5072565080,2014,2020,6,7,2,2,1.0,0.2857142857142857,6
|
||||
Lara Altenstädter,Sociology,Sociology,Researcher,A5070117981,2019,2023,4,5,5,15,3.0,3.0,3
|
||||
Lisa Mansfeld,Sociology,Sociology,Researcher,A5018318930,2021,2026,5,6,5,9,1.8,1.5,0
|
||||
|
@@ -0,0 +1,61 @@
|
||||
name,discipline,discipline_group,known_status,openalex_author_id
|
||||
Barbara Saccà,Biology,Biology,Professor,A5075803366
|
||||
Bernd Sures,Biology,Biology,Professor,A5088631999
|
||||
Daniel Hering,Biology,Biology,Professor,A5031147249
|
||||
Daniel Hoffmann,Biology,Biology,Professor,A5074555350
|
||||
Peter Bayer,Biology,Biology,Professor,A5060566345
|
||||
Bianca Kamba,Biology,Biology,Researcher,A5036363877
|
||||
Daniel Grabner,Biology,Biology,Researcher,A5063959731
|
||||
Farnusch Kaschani,Biology,Biology,Researcher,A5078099512
|
||||
Kathrin Januschke,Biology,Biology,Researcher,A5064225981
|
||||
Richard Kosinski,Biology,Biology,Researcher,A5014403509
|
||||
Jens Krüger,Computer Graphics and Visualization,Computer Science,Professor,A5087449583
|
||||
Torben Weis,Distributed Systems,Computer Science,Professor,A5016729057
|
||||
Stefan Schneegaß,Human Computer Interaction,Computer Science,Professor,A5024328962
|
||||
Gregor Schiele,Intelligent Embedded Systems,Computer Science,Professor,A5028943371
|
||||
Pedro José Marrón,Networked Embedded Systems,Computer Science,Professor,A5047117780
|
||||
Lucas Davi,Secure Software Systems,Computer Science,Professor,A5089242868
|
||||
Volker Gruhn,Software Engineering,Computer Science,Professor,A5049739067
|
||||
Andreas Metzger,Software Systems Engineering,Computer Science,Professor,A5082025709
|
||||
Andreas Vogelsang,Software Systems Engineering,Computer Science,Professor,A5022998651
|
||||
Barbara König,Theoretical Computer Science,Computer Science,Professor,A5103103785
|
||||
Alexandra Dmitrienko,Vertrauenswürdige Systeme,Computer Science,Professor,A5042835341
|
||||
Carina Liebers,Human Computer Interaction,Computer Science,Researcher,A5004350173
|
||||
Jonas Keppel,Human Computer Interaction,Computer Science,Researcher,A5015767175
|
||||
Carlos Medina Sánchez,Networked Embedded Systems,Computer Science,Researcher,A5093479876
|
||||
Marcus Handte,Networked Embedded Systems,Computer Science,Researcher,A5007170803
|
||||
Simon Janzon,Networked Embedded Systems,Computer Science,Researcher,A5044472300
|
||||
Christian Niesler,Secure Software Systems,Computer Science,Researcher,A5069184110
|
||||
Christian Scholz,Secure Software Systems,Computer Science,Researcher,A5120610207
|
||||
Pascal Winkler,Secure Software Systems,Computer Science,Researcher,A5081189339
|
||||
Stefan Hanenberg,Software Engineering,Computer Science,Researcher,A5027034338
|
||||
Wilhelm Koop,Software Engineering,Computer Science,Researcher,A5019228221
|
||||
Venkata Marella,Vertrauenswürdige Systeme,Computer Science,Researcher,A5082156768
|
||||
Burak Atakan,Engineering,Engineering,Professor,A5041521847
|
||||
Corina Andronescu,Engineering,Engineering,Professor,A5082583063
|
||||
Gerd Bacher,Engineering,Engineering,Professor,A5056038758
|
||||
Miriam Böhm,Engineering,Engineering,Researcher,A5037448457
|
||||
Soheil Salighe,Steuerung Regelung und Systemdynamik,Engineering,Researcher,A5041884757
|
||||
Tobias Mikolas,Engineering,Engineering,Researcher,A5002909977
|
||||
Boris Hadaschik,Medicine,Medicine,Professor,A5077243123
|
||||
Hartmut Schmidt,Medicine,Medicine,Professor,A5015932441
|
||||
Matthias Gunzer,Medicine,Medicine,Professor,A5020520632
|
||||
Oliver Witzke,Medicine,Medicine,Professor,A5087456839
|
||||
Stephan Lang,Medicine,Medicine,Professor,A5030649192
|
||||
Tienush Rassaf,Medicine,Medicine,Professor,A5048609556
|
||||
Ulrike Bingel,Medicine,Medicine,Professor,A5002281474
|
||||
Birte Möhlendick,Medicine,Medicine,Researcher,A5030635588
|
||||
Julia Schwichtenberg,Medicine,Medicine,Researcher,A5119372151
|
||||
Katrin Schuldt,Medicine,Medicine,Researcher,A5002003996
|
||||
Sabrina Guckenbiehl,Medicine,Medicine,Researcher,A5008120333
|
||||
Zülal Cibir,Medicine,Medicine,Researcher,A5035081158
|
||||
Frank Kleemann,Sociology,Sociology,Professor,A5041694590
|
||||
Gregor Bongaerts,Sociology,Sociology,Professor,A5012265262
|
||||
Helen Baykara-Krumme,Sociology,Sociology,Professor,A5010111732
|
||||
Marcel Erlinghagen,Sociology,Sociology,Professor,A5021715937
|
||||
Ute Klammer,Sociology,Sociology,Professor,A5055077517
|
||||
Andreas Jansen,Sociology,Sociology,Researcher,A5030957194
|
||||
Antonia Görtz,Sociology,Sociology,Researcher,A5066776558
|
||||
Friedrich Scheller,Sociology,Sociology,Researcher,A5072565080
|
||||
Lara Altenstädter,Sociology,Sociology,Researcher,A5070117981
|
||||
Lisa Mansfeld,Sociology,Sociology,Researcher,A5018318930
|
||||
|
@@ -0,0 +1,633 @@
|
||||
from pathlib import Path
|
||||
from typing import Callable, Literal
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import pandas as pd
|
||||
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
INPUT_FILE = BASE_DIR / "career_stage_results.csv"
|
||||
PLOTS_DIR = BASE_DIR / "plots"
|
||||
SUMMARY_DIR = BASE_DIR / "summaries"
|
||||
|
||||
STATUS_ORDER = ["Professor", "Researcher"]
|
||||
METRICS = [
|
||||
"career_span",
|
||||
"active_years",
|
||||
"publication_count",
|
||||
"publications_per_active_year",
|
||||
"publications_per_career_year",
|
||||
"years_since_last_publication",
|
||||
]
|
||||
|
||||
NUMERIC_COLUMNS = [
|
||||
"first_publication_year",
|
||||
"last_publication_year",
|
||||
"career_age",
|
||||
*METRICS,
|
||||
]
|
||||
|
||||
METRIC_LABELS = {
|
||||
"career_span": "Career Span in Years",
|
||||
"active_years": "Active Publication Years",
|
||||
"publication_count": "Number of Publications",
|
||||
"publications_per_active_year": "Publications per Active Year",
|
||||
"publications_per_career_year": "Publications per Career Year",
|
||||
"years_since_last_publication": "Years Since Last Publication",
|
||||
}
|
||||
|
||||
METRIC_TITLES = {
|
||||
"career_span": "Career Span",
|
||||
"active_years": "Active Publication Years",
|
||||
"publication_count": "Publication Count",
|
||||
"publications_per_active_year": "Publications per Active Year",
|
||||
"publications_per_career_year": "Publications per Career Year",
|
||||
"years_since_last_publication": "Years Since Last Publication",
|
||||
}
|
||||
|
||||
|
||||
StatisticFunction = Callable[[pd.Series], float]
|
||||
ScatterLabelMode = Literal["none", "outliers", "all"]
|
||||
|
||||
|
||||
def prepare_data() -> pd.DataFrame:
|
||||
if not INPUT_FILE.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Input file not found: {INPUT_FILE}. "
|
||||
"Run career_stage_analysis.py first."
|
||||
)
|
||||
|
||||
df = pd.read_csv(INPUT_FILE)
|
||||
|
||||
if "discipline_group" not in df.columns:
|
||||
df["discipline_group"] = df.get("discipline", "Unknown")
|
||||
|
||||
df["discipline_group"] = df["discipline_group"].fillna("Unknown")
|
||||
df["known_status"] = df["known_status"].fillna("Unknown")
|
||||
|
||||
for column in NUMERIC_COLUMNS:
|
||||
if column in df.columns:
|
||||
df[column] = pd.to_numeric(df[column], errors="coerce")
|
||||
|
||||
return df
|
||||
|
||||
|
||||
def ordered_statuses(df: pd.DataFrame) -> list[str]:
|
||||
statuses = [status for status in STATUS_ORDER if status in df["known_status"].unique()]
|
||||
additional_statuses = sorted(
|
||||
status
|
||||
for status in df["known_status"].dropna().unique()
|
||||
if status not in STATUS_ORDER
|
||||
)
|
||||
return statuses + additional_statuses
|
||||
|
||||
|
||||
def ordered_discipline_groups(df: pd.DataFrame) -> list[str]:
|
||||
return sorted(df["discipline_group"].dropna().unique())
|
||||
|
||||
|
||||
def mean_value(series: pd.Series) -> float:
|
||||
return series.mean()
|
||||
|
||||
|
||||
def median_value(series: pd.Series) -> float:
|
||||
return series.median()
|
||||
|
||||
|
||||
def build_summary(df: pd.DataFrame, group_columns: list[str]) -> pd.DataFrame:
|
||||
rows: list[dict[str, object]] = []
|
||||
|
||||
for group_values, group in df.groupby(group_columns, dropna=False):
|
||||
if not isinstance(group_values, tuple):
|
||||
group_values = (group_values,)
|
||||
|
||||
row: dict[str, object] = {
|
||||
column: value for column, value in zip(group_columns, group_values)
|
||||
}
|
||||
row["sample_size"] = len(group)
|
||||
|
||||
for metric in METRICS:
|
||||
if metric not in group.columns:
|
||||
continue
|
||||
|
||||
values = group[metric].dropna()
|
||||
row[f"mean_{metric}"] = values.mean() if not values.empty else None
|
||||
row[f"median_{metric}"] = values.median() if not values.empty else None
|
||||
|
||||
rows.append(row)
|
||||
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def save_summary_tables(df: pd.DataFrame) -> None:
|
||||
SUMMARY_DIR.mkdir(exist_ok=True)
|
||||
|
||||
summary_by_status = build_summary(df, ["known_status"])
|
||||
summary_by_status.to_csv(
|
||||
SUMMARY_DIR / "summary_by_status.csv",
|
||||
index=False,
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
summary_by_discipline_group = build_summary(df, ["discipline_group"])
|
||||
summary_by_discipline_group.to_csv(
|
||||
SUMMARY_DIR / "summary_by_discipline_group.csv",
|
||||
index=False,
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
summary_by_discipline_group_and_status = build_summary(
|
||||
df,
|
||||
["discipline_group", "known_status"],
|
||||
)
|
||||
summary_by_discipline_group_and_status.to_csv(
|
||||
SUMMARY_DIR / "summary_by_discipline_group_and_status.csv",
|
||||
index=False,
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
|
||||
def save_bar_plot_by_status(
|
||||
df: pd.DataFrame,
|
||||
metric: str,
|
||||
statistic_name: str,
|
||||
statistic_function: StatisticFunction,
|
||||
title: str,
|
||||
ylabel: str,
|
||||
filename: str,
|
||||
) -> None:
|
||||
grouped = df.groupby("known_status")[metric].apply(statistic_function)
|
||||
grouped = grouped.reindex(ordered_statuses(df)).dropna()
|
||||
|
||||
plt.figure(figsize=(10, 6))
|
||||
grouped.plot(kind="bar")
|
||||
plt.title(title)
|
||||
plt.xlabel("Known Status")
|
||||
plt.ylabel(ylabel)
|
||||
plt.xticks(rotation=30, ha="right")
|
||||
plt.tight_layout()
|
||||
plt.savefig(PLOTS_DIR / filename)
|
||||
plt.close()
|
||||
|
||||
print(f"Saved {statistic_name} plot: {filename}")
|
||||
|
||||
|
||||
def save_grouped_bar_plot_by_discipline_group(
|
||||
df: pd.DataFrame,
|
||||
metric: str,
|
||||
statistic_name: str,
|
||||
statistic_function: StatisticFunction,
|
||||
title: str,
|
||||
ylabel: str,
|
||||
filename: str,
|
||||
) -> None:
|
||||
grouped = (
|
||||
df.groupby(["discipline_group", "known_status"])[metric]
|
||||
.apply(statistic_function)
|
||||
.unstack("known_status")
|
||||
)
|
||||
|
||||
grouped = grouped.reindex(ordered_discipline_groups(df))
|
||||
grouped = grouped.reindex(columns=ordered_statuses(df))
|
||||
|
||||
plt.figure(figsize=(12, 6))
|
||||
grouped.plot(kind="bar")
|
||||
plt.title(title)
|
||||
plt.xlabel("Discipline Group")
|
||||
plt.ylabel(ylabel)
|
||||
plt.xticks(rotation=30, ha="right")
|
||||
plt.legend(title="Known Status")
|
||||
plt.tight_layout()
|
||||
plt.savefig(PLOTS_DIR / filename)
|
||||
plt.close()
|
||||
|
||||
print(f"Saved {statistic_name} discipline group plot: {filename}")
|
||||
|
||||
|
||||
def save_box_plot_by_status(
|
||||
df: pd.DataFrame,
|
||||
metric: str,
|
||||
title: str,
|
||||
ylabel: str,
|
||||
filename: str,
|
||||
) -> None:
|
||||
statuses = ordered_statuses(df)
|
||||
data = [df.loc[df["known_status"] == status, metric].dropna() for status in statuses]
|
||||
|
||||
plt.figure(figsize=(10, 6))
|
||||
plt.boxplot(data, labels=statuses)
|
||||
plt.title(title)
|
||||
plt.xlabel("Known Status")
|
||||
plt.ylabel(ylabel)
|
||||
plt.xticks(rotation=30, ha="right")
|
||||
plt.tight_layout()
|
||||
plt.savefig(PLOTS_DIR / filename)
|
||||
plt.close()
|
||||
|
||||
|
||||
def save_box_plot_by_discipline_group_and_status(
|
||||
df: pd.DataFrame,
|
||||
metric: str,
|
||||
title: str,
|
||||
ylabel: str,
|
||||
filename: str,
|
||||
) -> None:
|
||||
labels: list[str] = []
|
||||
data: list[pd.Series] = []
|
||||
|
||||
for discipline_group in ordered_discipline_groups(df):
|
||||
discipline_group_data = df[df["discipline_group"] == discipline_group]
|
||||
|
||||
for status in ordered_statuses(discipline_group_data):
|
||||
values = discipline_group_data.loc[
|
||||
discipline_group_data["known_status"] == status,
|
||||
metric,
|
||||
].dropna()
|
||||
|
||||
if values.empty:
|
||||
continue
|
||||
|
||||
labels.append(f"{discipline_group}\n{status}")
|
||||
data.append(values)
|
||||
|
||||
if not data:
|
||||
return
|
||||
|
||||
plt.figure(figsize=(14, 6))
|
||||
plt.boxplot(data, labels=labels)
|
||||
plt.title(title)
|
||||
plt.xlabel("Discipline Group and Known Status")
|
||||
plt.ylabel(ylabel)
|
||||
plt.xticks(rotation=45, ha="right")
|
||||
plt.tight_layout()
|
||||
plt.savefig(PLOTS_DIR / filename)
|
||||
plt.close()
|
||||
|
||||
|
||||
def save_histogram(
|
||||
df: pd.DataFrame,
|
||||
metric: str,
|
||||
title: str,
|
||||
xlabel: str,
|
||||
filename: str,
|
||||
) -> None:
|
||||
plt.figure(figsize=(10, 6))
|
||||
df[metric].dropna().plot(kind="hist", bins=10)
|
||||
plt.title(title)
|
||||
plt.xlabel(xlabel)
|
||||
plt.ylabel("Number of Researchers")
|
||||
plt.tight_layout()
|
||||
plt.savefig(PLOTS_DIR / filename)
|
||||
plt.close()
|
||||
|
||||
|
||||
def is_outlier(row: pd.Series, df: pd.DataFrame, x_metric: str, y_metric: str) -> bool:
|
||||
x_values = df[x_metric].dropna()
|
||||
y_values = df[y_metric].dropna()
|
||||
|
||||
if x_values.empty or y_values.empty:
|
||||
return False
|
||||
|
||||
x_threshold = x_values.quantile(0.75) + 1.5 * (
|
||||
x_values.quantile(0.75) - x_values.quantile(0.25)
|
||||
)
|
||||
y_threshold = y_values.quantile(0.75) + 1.5 * (
|
||||
y_values.quantile(0.75) - y_values.quantile(0.25)
|
||||
)
|
||||
|
||||
x_value = row.get(x_metric)
|
||||
y_value = row.get(y_metric)
|
||||
|
||||
if pd.isna(x_value) or pd.isna(y_value):
|
||||
return False
|
||||
|
||||
is_statistical_outlier = x_value > x_threshold or y_value > y_threshold
|
||||
is_researcher_with_long_history = (
|
||||
row.get("known_status") == "Researcher"
|
||||
and (x_value > 20 or row.get("publication_count", 0) > 100)
|
||||
)
|
||||
is_suspiciously_old_first_publication = row.get("first_publication_year", 9999) < 1970
|
||||
|
||||
return bool(
|
||||
is_statistical_outlier
|
||||
or is_researcher_with_long_history
|
||||
or is_suspiciously_old_first_publication
|
||||
)
|
||||
|
||||
|
||||
def should_label_point(
|
||||
row: pd.Series,
|
||||
df: pd.DataFrame,
|
||||
x_metric: str,
|
||||
y_metric: str,
|
||||
label_mode: ScatterLabelMode,
|
||||
) -> bool:
|
||||
if label_mode == "none":
|
||||
return False
|
||||
|
||||
if label_mode == "all":
|
||||
return True
|
||||
|
||||
return is_outlier(row, df, x_metric, y_metric)
|
||||
|
||||
|
||||
def save_scatter_plot(
|
||||
df: pd.DataFrame,
|
||||
x_metric: str,
|
||||
y_metric: str,
|
||||
group_column: str,
|
||||
title: str,
|
||||
xlabel: str,
|
||||
ylabel: str,
|
||||
filename: str,
|
||||
label_mode: ScatterLabelMode = "none",
|
||||
) -> None:
|
||||
figure_width = 15 if label_mode == "all" else 11
|
||||
figure_height = 9 if label_mode == "all" else 7
|
||||
label_fontsize = 6 if label_mode == "all" else 8
|
||||
|
||||
plt.figure(figsize=(figure_width, figure_height))
|
||||
|
||||
for group_name, group in df.groupby(group_column):
|
||||
plt.scatter(group[x_metric], group[y_metric], label=group_name, alpha=0.8)
|
||||
|
||||
for _, row in group.iterrows():
|
||||
x_value = row.get(x_metric)
|
||||
y_value = row.get(y_metric)
|
||||
name = row.get("name")
|
||||
|
||||
if (
|
||||
pd.notna(name)
|
||||
and pd.notna(x_value)
|
||||
and pd.notna(y_value)
|
||||
and should_label_point(row, df, x_metric, y_metric, label_mode)
|
||||
):
|
||||
plt.annotate(
|
||||
str(name),
|
||||
(x_value, y_value),
|
||||
fontsize=label_fontsize,
|
||||
xytext=(5, 5),
|
||||
textcoords="offset points",
|
||||
)
|
||||
|
||||
plt.title(title)
|
||||
plt.xlabel(xlabel)
|
||||
plt.ylabel(ylabel)
|
||||
plt.legend(title=group_column)
|
||||
plt.tight_layout()
|
||||
plt.savefig(PLOTS_DIR / filename)
|
||||
plt.close()
|
||||
|
||||
|
||||
def create_status_plots(df: pd.DataFrame) -> None:
|
||||
for metric in ["career_span", "publication_count", "active_years"]:
|
||||
metric_title = METRIC_TITLES[metric]
|
||||
metric_label = METRIC_LABELS[metric]
|
||||
|
||||
save_bar_plot_by_status(
|
||||
df=df,
|
||||
metric=metric,
|
||||
statistic_name="average",
|
||||
statistic_function=mean_value,
|
||||
title=f"Average {metric_title} by Known Status",
|
||||
ylabel=f"Average {metric_label}",
|
||||
filename=f"average_{metric}_by_status.png",
|
||||
)
|
||||
|
||||
save_bar_plot_by_status(
|
||||
df=df,
|
||||
metric=metric,
|
||||
statistic_name="median",
|
||||
statistic_function=median_value,
|
||||
title=f"Median {metric_title} by Known Status",
|
||||
ylabel=f"Median {metric_label}",
|
||||
filename=f"median_{metric}_by_status.png",
|
||||
)
|
||||
|
||||
for metric in [
|
||||
"publications_per_active_year",
|
||||
"publications_per_career_year",
|
||||
"years_since_last_publication",
|
||||
]:
|
||||
metric_title = METRIC_TITLES[metric]
|
||||
metric_label = METRIC_LABELS[metric]
|
||||
|
||||
save_bar_plot_by_status(
|
||||
df=df,
|
||||
metric=metric,
|
||||
statistic_name="average",
|
||||
statistic_function=mean_value,
|
||||
title=f"Average {metric_title} by Known Status",
|
||||
ylabel=f"Average {metric_label}",
|
||||
filename=f"average_{metric}_by_status.png",
|
||||
)
|
||||
|
||||
save_box_plot_by_status(
|
||||
df=df,
|
||||
metric="career_span",
|
||||
title="Distribution of Career Span by Known Status",
|
||||
ylabel="Career Span in Years",
|
||||
filename="boxplot_career_span_by_status.png",
|
||||
)
|
||||
|
||||
save_box_plot_by_status(
|
||||
df=df,
|
||||
metric="publication_count",
|
||||
title="Distribution of Publication Count by Known Status",
|
||||
ylabel="Number of Publications",
|
||||
filename="boxplot_publication_count_by_status.png",
|
||||
)
|
||||
|
||||
save_box_plot_by_status(
|
||||
df=df,
|
||||
metric="active_years",
|
||||
title="Distribution of Active Publication Years by Known Status",
|
||||
ylabel="Active Publication Years",
|
||||
filename="boxplot_active_years_by_status.png",
|
||||
)
|
||||
|
||||
|
||||
def create_discipline_group_plots(df: pd.DataFrame) -> None:
|
||||
for metric in ["career_span", "publication_count", "active_years"]:
|
||||
metric_title = METRIC_TITLES[metric]
|
||||
metric_label = METRIC_LABELS[metric]
|
||||
|
||||
save_grouped_bar_plot_by_discipline_group(
|
||||
df=df,
|
||||
metric=metric,
|
||||
statistic_name="average",
|
||||
statistic_function=mean_value,
|
||||
title=f"Average {metric_title} by Discipline Group and Status",
|
||||
ylabel=f"Average {metric_label}",
|
||||
filename=f"average_{metric}_by_discipline_group_and_status.png",
|
||||
)
|
||||
|
||||
save_grouped_bar_plot_by_discipline_group(
|
||||
df=df,
|
||||
metric=metric,
|
||||
statistic_name="median",
|
||||
statistic_function=median_value,
|
||||
title=f"Median {metric_title} by Discipline Group and Status",
|
||||
ylabel=f"Median {metric_label}",
|
||||
filename=f"median_{metric}_by_discipline_group_and_status.png",
|
||||
)
|
||||
|
||||
save_box_plot_by_discipline_group_and_status(
|
||||
df=df,
|
||||
metric=metric,
|
||||
title=f"Distribution of {metric_title} by Discipline Group and Status",
|
||||
ylabel=metric_label,
|
||||
filename=f"boxplot_{metric}_by_discipline_group_and_status.png",
|
||||
)
|
||||
|
||||
|
||||
def create_distribution_plots(df: pd.DataFrame) -> None:
|
||||
save_histogram(
|
||||
df=df,
|
||||
metric="career_span",
|
||||
title="Career Span Distribution",
|
||||
xlabel="Career Span in Years",
|
||||
filename="histogram_career_span.png",
|
||||
)
|
||||
|
||||
save_histogram(
|
||||
df=df,
|
||||
metric="publication_count",
|
||||
title="Publication Count Distribution",
|
||||
xlabel="Number of Publications",
|
||||
filename="histogram_publication_count.png",
|
||||
)
|
||||
|
||||
|
||||
def create_scatter_plots(df: pd.DataFrame) -> None:
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publication_count",
|
||||
group_column="known_status",
|
||||
title="Career Span vs Publication Count by Status",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_career_span_vs_publication_count_by_status.png",
|
||||
label_mode="none",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publication_count",
|
||||
group_column="known_status",
|
||||
title="Career Span vs Publication Count by Status with Outlier Labels",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_career_span_vs_publication_count_by_status_outliers.png",
|
||||
label_mode="outliers",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publication_count",
|
||||
group_column="known_status",
|
||||
title="Career Span vs Publication Count by Status with All Names",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_career_span_vs_publication_count_by_status_all_names.png",
|
||||
label_mode="all",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publication_count",
|
||||
group_column="discipline_group",
|
||||
title="Career Span vs Publication Count by Discipline Group",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_career_span_vs_publication_count_by_discipline_group.png",
|
||||
label_mode="none",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publication_count",
|
||||
group_column="discipline_group",
|
||||
title="Career Span vs Publication Count by Discipline Group with All Names",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_career_span_vs_publication_count_by_discipline_group_all_names.png",
|
||||
label_mode="all",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="active_years",
|
||||
y_metric="publication_count",
|
||||
group_column="known_status",
|
||||
title="Active Publication Years vs Publication Count by Status",
|
||||
xlabel="Active Publication Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_active_years_vs_publication_count_by_status.png",
|
||||
label_mode="none",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="active_years",
|
||||
y_metric="publication_count",
|
||||
group_column="known_status",
|
||||
title="Active Publication Years vs Publication Count by Status with All Names",
|
||||
xlabel="Active Publication Years",
|
||||
ylabel="Number of Publications",
|
||||
filename="scatter_active_years_vs_publication_count_by_status_all_names.png",
|
||||
label_mode="all",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publications_per_active_year",
|
||||
group_column="known_status",
|
||||
title="Career Span vs Publications per Active Year by Status",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Publications per Active Year",
|
||||
filename="scatter_career_span_vs_publications_per_active_year_by_status.png",
|
||||
label_mode="none",
|
||||
)
|
||||
|
||||
save_scatter_plot(
|
||||
df=df,
|
||||
x_metric="career_span",
|
||||
y_metric="publications_per_active_year",
|
||||
group_column="known_status",
|
||||
title="Career Span vs Publications per Active Year by Status with All Names",
|
||||
xlabel="Career Span in Years",
|
||||
ylabel="Publications per Active Year",
|
||||
filename="scatter_career_span_vs_publications_per_active_year_by_status_all_names.png",
|
||||
label_mode="all",
|
||||
)
|
||||
|
||||
|
||||
def create_visualizations() -> None:
|
||||
PLOTS_DIR.mkdir(exist_ok=True)
|
||||
SUMMARY_DIR.mkdir(exist_ok=True)
|
||||
|
||||
df = prepare_data()
|
||||
|
||||
if df.empty:
|
||||
print("No data available for visualization.")
|
||||
return
|
||||
|
||||
save_summary_tables(df)
|
||||
create_status_plots(df)
|
||||
create_discipline_group_plots(df)
|
||||
create_distribution_plots(df)
|
||||
create_scatter_plots(df)
|
||||
|
||||
print(f"Visualizations saved to {PLOTS_DIR}")
|
||||
print(f"Summary tables saved to {SUMMARY_DIR}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
create_visualizations()
|
||||
@@ -0,0 +1,96 @@
|
||||
import json
|
||||
from typing import Any
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
OPENALEX_WORKS_URL = "https://api.openalex.org/works"
|
||||
REQUEST_TIMEOUT_SECONDS = 30
|
||||
PER_PAGE = 200
|
||||
|
||||
|
||||
def normalize_author_id(author_id: str) -> str:
|
||||
"""
|
||||
Normalizes OpenAlex author IDs.
|
||||
|
||||
Supported inputs:
|
||||
- A123456789
|
||||
- https://openalex.org/A123456789
|
||||
- https://api.openalex.org/authors/A123456789
|
||||
"""
|
||||
cleaned_author_id = author_id.strip()
|
||||
|
||||
if cleaned_author_id.startswith("https://api.openalex.org/authors/"):
|
||||
return cleaned_author_id.replace(
|
||||
"https://api.openalex.org/authors/",
|
||||
"https://openalex.org/",
|
||||
)
|
||||
|
||||
if cleaned_author_id.startswith("https://openalex.org/"):
|
||||
return cleaned_author_id
|
||||
|
||||
if cleaned_author_id.startswith("A"):
|
||||
return f"https://openalex.org/{cleaned_author_id}"
|
||||
|
||||
return cleaned_author_id
|
||||
|
||||
|
||||
def fetch_openalex_page(author_id: str, cursor: str) -> dict[str, Any]:
|
||||
normalized_author_id = normalize_author_id(author_id)
|
||||
|
||||
query_params = urlencode(
|
||||
{
|
||||
"filter": f"authorships.author.id:{normalized_author_id}",
|
||||
"per-page": PER_PAGE,
|
||||
"cursor": cursor,
|
||||
"sort": "publication_year:asc",
|
||||
}
|
||||
)
|
||||
|
||||
url = f"{OPENALEX_WORKS_URL}?{query_params}"
|
||||
|
||||
request = Request(
|
||||
url,
|
||||
headers={
|
||||
"Accept": "application/json",
|
||||
"User-Agent": "AIIS career stage analysis",
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
with urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
|
||||
response_body = response.read().decode("utf-8")
|
||||
return json.loads(response_body)
|
||||
|
||||
except HTTPError as error:
|
||||
raise RuntimeError(
|
||||
f"OpenAlex request failed with HTTP status {error.code}: {url}"
|
||||
) from error
|
||||
|
||||
except URLError as error:
|
||||
raise RuntimeError(f"OpenAlex request failed: {error}") from error
|
||||
|
||||
|
||||
def get_all_author_works(author_id: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Fetches all works for an OpenAlex author by using cursor pagination.
|
||||
"""
|
||||
works: list[dict[str, Any]] = []
|
||||
cursor = "*"
|
||||
|
||||
while cursor:
|
||||
data = fetch_openalex_page(author_id, cursor)
|
||||
|
||||
page_results = data.get("results", [])
|
||||
works.extend(page_results)
|
||||
|
||||
meta = data.get("meta", {})
|
||||
next_cursor = meta.get("next_cursor")
|
||||
|
||||
if not next_cursor or next_cursor == cursor:
|
||||
break
|
||||
|
||||
cursor = next_cursor
|
||||
|
||||
return works
|
||||
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 32 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 31 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 76 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 75 KiB |
|
After Width: | Height: | Size: 51 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 81 KiB |
@@ -0,0 +1,6 @@
|
||||
discipline_group,sample_size,mean_career_span,median_career_span,mean_active_years,median_active_years,mean_publication_count,median_publication_count,mean_publications_per_active_year,median_publications_per_active_year,mean_publications_per_career_year,median_publications_per_career_year,mean_years_since_last_publication,median_years_since_last_publication
|
||||
Biology,10,44.5,35.0,23.0,23.5,184.5,138.5,6.410136743886744,6.833333333333333,4.342828101969518,2.8414179104477615,0.7,0.0
|
||||
Computer Science,22,24.90909090909091,18.5,17.136363636363637,17.5,115.54545454545455,106.0,5.194674030118668,4.390697674418605,4.383304699676206,3.1192307692307693,0.4090909090909091,0.0
|
||||
Engineering,6,20.166666666666668,15.0,17.833333333333332,13.5,124.16666666666667,74.5,4.5022556390977435,3.6357142857142857,4.054259702286018,3.2033492822966507,1.6666666666666667,1.0
|
||||
Medicine,12,37.916666666666664,26.5,23.0,21.5,343.6666666666667,188.5,10.699183227664198,8.416666666666666,7.862918672933688,6.795662100456621,0.25,0.0
|
||||
Sociology,10,21.8,23.0,13.9,15.0,55.2,35.0,3.0017820858310875,3.0277777777777777,2.245860377439325,2.206815114709852,1.2,0.5
|
||||
|
@@ -0,0 +1,11 @@
|
||||
discipline_group,known_status,sample_size,mean_career_span,median_career_span,mean_active_years,median_active_years,mean_publication_count,median_publication_count,mean_publications_per_active_year,median_publications_per_active_year,mean_publications_per_career_year,median_publications_per_career_year,mean_years_since_last_publication,median_years_since_last_publication
|
||||
Biology,Professor,5,62.8,58.0,33.4,35.0,303.4,332.0,8.856940154440155,9.485714285714286,5.944422997812213,5.442622950819672,0.4,0.0
|
||||
Biology,Researcher,5,26.2,22.0,12.6,15.0,65.6,36.0,3.9633333333333334,2.4,2.741233206126823,2.021276595744681,1.0,0.0
|
||||
Computer Science,Professor,11,39.72727272727273,31.0,25.90909090909091,22.0,203.8181818181818,202.0,8.05960497723338,7.214285714285714,6.804834459316603,6.470588235294118,0.18181818181818182,0.0
|
||||
Computer Science,Researcher,11,10.090909090909092,6.0,8.363636363636363,5.0,27.272727272727273,11.0,2.3297430830039527,2.2,1.96177494003581,1.5,0.6363636363636364,0.0
|
||||
Engineering,Professor,3,33.0,38.0,30.666666666666668,35.0,241.33333333333334,202.0,7.704511278195487,7.2105263157894735,7.230994152046783,7.2105263157894735,0.0,0.0
|
||||
Engineering,Researcher,3,7.333333333333333,8.0,5.0,5.0,7.0,7.0,1.3,1.4,0.8775252525252525,0.875,3.3333333333333335,3.0
|
||||
Medicine,Professor,7,56.714285714285715,30.0,34.285714285714285,29.0,572.7142857142857,615.0,16.225810703206655,16.253968253968253,11.606273280584732,8.76530612244898,0.14285714285714285,0.0
|
||||
Medicine,Researcher,5,11.6,7.0,7.2,7.0,23.0,21.0,2.961904761904762,3.0,2.6222222222222222,3.0,0.4,0.0
|
||||
Sociology,Professor,5,32.0,27.0,22.6,22.0,101.8,106.0,4.393564171662176,4.517241379310345,3.3512445644024593,3.55,0.4,0.0
|
||||
Sociology,Researcher,5,11.6,6.0,5.2,5.0,8.6,9.0,1.61,1.25,1.1404761904761904,0.5,2.0,1.0
|
||||
|
@@ -0,0 +1,3 @@
|
||||
known_status,sample_size,mean_career_span,median_career_span,mean_active_years,median_active_years,mean_publication_count,median_publication_count,mean_publications_per_active_year,median_publications_per_active_year,mean_publications_per_career_year,median_publications_per_career_year,mean_years_since_last_publication,median_years_since_last_publication
|
||||
Professor,31,45.38709677419355,31.0,28.93548387096774,28.0,290.35483870967744,224.0,9.40652855281006,7.611111111111111,7.234464912380307,6.172413793103448,0.22580645161290322,0.0
|
||||
Researcher,29,13.10344827586207,7.0,8.0,5.0,27.82758620689655,11.0,2.4897711858356537,1.8,1.9562675238653737,1.5,1.1724137931034482,0.0
|
||||
|
@@ -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 AktuellItem(scrapy.Item):
|
||||
# define the fields for your item here like:
|
||||
# name = scrapy.Field()
|
||||
pass
|
||||
@@ -0,0 +1,103 @@
|
||||
# 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
|
||||
|
||||
|
||||
class AktuellSpiderMiddleware:
|
||||
# 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 AktuellDownloaderMiddleware:
|
||||
# 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)
|
||||
@@ -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 AktuellPipeline:
|
||||
def process_item(self, item, spider):
|
||||
return item
|
||||
@@ -0,0 +1,93 @@
|
||||
# Scrapy settings for aktuell 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
|
||||
|
||||
BOT_NAME = "aktuell"
|
||||
|
||||
SPIDER_MODULES = ["aktuell.spiders"]
|
||||
NEWSPIDER_MODULE = "aktuell.spiders"
|
||||
|
||||
|
||||
# Crawl responsibly by identifying yourself (and your website) on the user-agent
|
||||
#USER_AGENT = "aktuell (+http://www.yourdomain.com)"
|
||||
|
||||
# Obey robots.txt rules
|
||||
ROBOTSTXT_OBEY = True
|
||||
|
||||
# Configure maximum concurrent requests performed by Scrapy (default: 16)
|
||||
#CONCURRENT_REQUESTS = 32
|
||||
|
||||
# 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 = 5
|
||||
# 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 = {
|
||||
# "aktuell.middlewares.AktuellSpiderMiddleware": 543,
|
||||
#}
|
||||
|
||||
# Enable or disable downloader middlewares
|
||||
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
|
||||
#DOWNLOADER_MIDDLEWARES = {
|
||||
# "aktuell.middlewares.AktuellDownloaderMiddleware": 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 = {
|
||||
# "aktuell.pipelines.AktuellPipeline": 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"
|
||||
@@ -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,45 @@
|
||||
import scrapy
|
||||
|
||||
class LinksCrawler(scrapy.Spider):
|
||||
name = "aktuell-links"
|
||||
|
||||
current = 1
|
||||
first = True
|
||||
max_num = 100
|
||||
|
||||
def start_requests(self):
|
||||
url = 'https://www.uni-due.de/aktuell/?page=1&list_max=250'
|
||||
yield scrapy.Request(url=url, callback=self.parse)
|
||||
|
||||
def parse(self, response):
|
||||
if self.first:
|
||||
self.first = False
|
||||
max_num_text = response.selector.xpath('//div[contains(@id,"content__old__main")]/form/div/div/div[1]/div[1]/text()[2]').get()
|
||||
self.max_num = int(max_num_text[4:])
|
||||
|
||||
rows = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")]').getall()
|
||||
|
||||
for i in range(len(rows)):
|
||||
cols = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")][' + str(i + 1) + ']/div/div/div/div').getall()
|
||||
|
||||
for o in range(len(cols)):
|
||||
link = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")][' + str(i + 1) + ']/div/div/div/div[' + str(o + 1) + ']/div/a/@href').get()
|
||||
tags_num = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")][' + str(i + 1) + ']/div/div/div/div[' + str(o + 1) + ']/div/ul/li').getall()
|
||||
tags = []
|
||||
|
||||
for p in range(len(tags_num)):
|
||||
tag = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[contains(@class,"row")][' + str(i + 1) + ']/div/div/div/div[' + str(o + 1) + ']/div/ul/li[' + str(p + 1) + ']/a/text()').get()
|
||||
|
||||
if tag != None:
|
||||
tags.append(tag)
|
||||
|
||||
yield {
|
||||
"link": "https://www.uni-due.de" + link,
|
||||
"tags": tags
|
||||
}
|
||||
|
||||
self.current = self.current + 1
|
||||
if self.current <= self.max_num:
|
||||
next_page = "https://www.uni-due.de/aktuell/?page=" + str(self.current) + "&list_max=250"
|
||||
|
||||
yield response.follow(next_page, callback=self.parse)
|
||||
@@ -0,0 +1,153 @@
|
||||
import scrapy
|
||||
import json
|
||||
from scrapy.linkextractors import LinkExtractor
|
||||
import os
|
||||
|
||||
class MetaDataCrawler(scrapy.Spider):
|
||||
name = "aktuell-metadata"
|
||||
|
||||
link_extractor = LinkExtractor()
|
||||
log = {}
|
||||
|
||||
def start_requests(self):
|
||||
with open("out/links.json", "r") as file:
|
||||
urls = json.load(file)
|
||||
print("file loaded")
|
||||
|
||||
print("start logging")
|
||||
# start log
|
||||
if os.path.exists("out/aktuell_crawler_log.json"):
|
||||
# if json exists -> read in file
|
||||
with open('out/aktuell_crawler_log.json', 'r') as jsonfile:
|
||||
self.log = json.load(jsonfile)
|
||||
else:
|
||||
# if json doesn't exist -> #1 create json -> #2 write in initial structure -> #3 read it in
|
||||
# 1
|
||||
open("out/aktuell_crawler_log.json", "x")
|
||||
# 2
|
||||
initial_dict = {"done": []}
|
||||
with open("out/aktuell_crawler_log.json", "w") as jsonfile:
|
||||
jsonfile.write(json.dumps(initial_dict))
|
||||
# 3
|
||||
with open('out/aktuell_crawler_log.json', 'r') as jsonfile:
|
||||
self.log = json.load(jsonfile)
|
||||
|
||||
for url in urls:
|
||||
if url["link"] not in self.log["done"]:
|
||||
yield scrapy.Request(url=url["link"], callback=self.parse)
|
||||
self.log["done"].append(url["link"])
|
||||
with open("out/aktuell_crawler_log.json", "w") as jsonfile:
|
||||
jsonfile.write(json.dumps(self.log))
|
||||
else:
|
||||
continue
|
||||
|
||||
def parse(self, response):
|
||||
subtitle = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/h2[contains(@class, "card-subtitle")]/text()').get()
|
||||
maintitle = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/h2[contains(@class, "card-title")]/text()').get()
|
||||
|
||||
tags_num = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/ul/li').getall()
|
||||
tags = []
|
||||
|
||||
for p in range(len(tags_num)):
|
||||
tag = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/ul/li[' + str(p + 1) + ']/a/text()').get()
|
||||
|
||||
if tag != None:
|
||||
tags.append(tag)
|
||||
|
||||
author = ""
|
||||
date = ""
|
||||
if response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/ul/li[1]/text()').get() == "von ":
|
||||
author = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/ul/li[1]/b/text()').get()
|
||||
date = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/ul/li[2]/text()').get()
|
||||
else:
|
||||
date = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/ul/li[1]/text()').get()
|
||||
|
||||
content_num = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p').getall()
|
||||
main_content = ""
|
||||
intro_content = ""
|
||||
further_content = ""
|
||||
is_further = False
|
||||
redaktion = ""
|
||||
|
||||
for p in range(len(content_num)):
|
||||
if p == 0:
|
||||
current_content = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']/strong').get()
|
||||
check_h2 = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/h2').get()
|
||||
|
||||
if current_content is not None and check_h2 is None:
|
||||
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
|
||||
current_content = "".join(current_contents)
|
||||
intro_content = current_content + " "
|
||||
else:
|
||||
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
|
||||
current_content = "".join(current_contents)
|
||||
main_content = main_content + current_content + " "
|
||||
elif is_further:
|
||||
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
|
||||
current_content = "".join(current_contents)
|
||||
|
||||
if current_content.startswith("Redaktion: "):
|
||||
redaktion = current_content + " "
|
||||
else:
|
||||
further_content = further_content + current_content + " "
|
||||
else:
|
||||
current_content = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']/strong/text()').get()
|
||||
|
||||
if current_content is not None and current_content.startswith("Weitere Informationen"):
|
||||
is_further = True
|
||||
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
|
||||
current_content = "".join(current_contents)
|
||||
|
||||
if current_content.startswith("Redaktion: "):
|
||||
redaktion = current_content + " "
|
||||
else:
|
||||
further_content = further_content + current_content + " "
|
||||
else:
|
||||
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
|
||||
current_content = "".join(current_contents)
|
||||
|
||||
if current_content.startswith("Redaktion: "):
|
||||
current_contents = response.selector.xpath('//div[contains(@id,"content__old__main")]/div[1]/div/div[contains(@class, "card-text")]/p[' + str(p + 1) + ']//text()').getall()
|
||||
current_content = "".join(current_contents)
|
||||
redaktion = current_content + " "
|
||||
else:
|
||||
main_content = main_content + current_content + " "
|
||||
|
||||
full_content = intro_content + " " + main_content
|
||||
main_content = main_content.replace("\n", " ").replace("\r", " ").replace("\t", " ").replace("\b", " ")
|
||||
intro_content = intro_content.replace("\n", " ").replace("\r", " ").replace("\t", " ").replace("\b", " ")
|
||||
further_content = further_content.replace("\n", " ").replace("\r", " ").replace("\t", " ").replace("\b", " ")
|
||||
|
||||
links = self.link_extractor.extract_links(response)
|
||||
filtered_links = []
|
||||
for link in links:
|
||||
l = {"url": link.url, "text": link.text.replace("\n", " ").replace("\r", " ").replace("\t", " ").replace("\b", " ")}
|
||||
filtered_links.append(l)
|
||||
|
||||
date_year = ""
|
||||
if not date == "":
|
||||
date_year = date[-4:]
|
||||
|
||||
date_full = ""
|
||||
if not date == "":
|
||||
d1 = date[:2]
|
||||
d2 = date[3:5]
|
||||
d3 = date[6:]
|
||||
date_full = d3 + d2 + d1
|
||||
|
||||
yield {
|
||||
"subtitle": subtitle,
|
||||
"maintitle": maintitle,
|
||||
"tags": tags,
|
||||
"author": author,
|
||||
"date": date,
|
||||
"date_year": date_year,
|
||||
"date_full": date_full,
|
||||
"intro_content": intro_content,
|
||||
"main_content": main_content,
|
||||
"further_content": further_content,
|
||||
"redaktion": redaktion,
|
||||
"full_content": full_content,
|
||||
"links": filtered_links,
|
||||
"url": response.request.url
|
||||
}
|
||||
@@ -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 = aktuell.settings
|
||||
|
||||
[deploy]
|
||||
#url = http://localhost:6800/
|
||||
project = aktuell
|
||||
@@ -0,0 +1,153 @@
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.webdriver.firefox.options import Options
|
||||
from random import randint
|
||||
import time
|
||||
import sys
|
||||
from elasticsearch import Elasticsearch
|
||||
|
||||
es = Elasticsearch()
|
||||
|
||||
index_name = "aktuell-test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index
|
||||
|
||||
def getLinks(link, driver):
|
||||
print("--- Getting Links")
|
||||
driver.get(link)
|
||||
|
||||
time.sleep(randint(5, 7))
|
||||
|
||||
links = []
|
||||
dates = []
|
||||
dates_year = []
|
||||
dates_num = []
|
||||
counter = 1
|
||||
|
||||
while True:
|
||||
# increment counter (counter starts one lower than needed, so the increment is at the start instead of at the end)
|
||||
counter += 1
|
||||
|
||||
# check if end is reached
|
||||
try:
|
||||
elem = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/b").text
|
||||
if elem == "Zurück zum Gesamtüberblick":
|
||||
break
|
||||
except NoSuchElementException as nsee:
|
||||
break
|
||||
|
||||
# get date
|
||||
elem = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/span[1]/small").text
|
||||
y = elem[1:5]
|
||||
m = elem[6:8]
|
||||
d = elem[9:11]
|
||||
|
||||
# get link
|
||||
link = ""
|
||||
try:
|
||||
link = driver.find_element(By.XPATH, "/html/body/main/div[2]/div/div/div/div/div/div/div[" + str(counter) + "]/b/a").get_attribute('href')
|
||||
except NoSuchElementException as nsee:
|
||||
continue
|
||||
|
||||
links.append(link)
|
||||
dates.append(d + "." + m + "." + y)
|
||||
dates_year.append(y)
|
||||
dates_num.append(y + m + d)
|
||||
|
||||
print(f"--- Number of found links: {len(links)}")
|
||||
|
||||
return links, dates, dates_year, dates_num
|
||||
|
||||
def getData(driver, link, date, date_year, date_num):
|
||||
print(f"--- --- {link}")
|
||||
|
||||
driver.get(link)
|
||||
|
||||
time.sleep(randint(5, 7))
|
||||
|
||||
subtitle = ""
|
||||
try:
|
||||
subtitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h3").text
|
||||
except NoSuchElementException as nsee:
|
||||
pass
|
||||
maintitle = ""
|
||||
try:
|
||||
maintitle = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/hgroup/h2").text
|
||||
except NoSuchElementException as nsee:
|
||||
pass
|
||||
redaktion = ""
|
||||
try:
|
||||
redaktion = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[2]").text
|
||||
except NoSuchElementException as nsee:
|
||||
pass
|
||||
author = ""
|
||||
if redaktion != "":
|
||||
if redaktion.startswith("Redaktion: ") and redaktion.find(",") != -1:
|
||||
author = redaktion[11:redaktion.find(",")]
|
||||
main_content = ""
|
||||
try:
|
||||
main_content = driver.find_element(By.XPATH, "/html/body/main/div[3]/div/div/div/div[1]/div[1]/div/p[1]").text
|
||||
except NoSuchElementException as nsee:
|
||||
pass
|
||||
|
||||
full_content = main_content
|
||||
|
||||
dict = {
|
||||
"subtitle": subtitle,
|
||||
"maintitle": maintitle,
|
||||
"author": author,
|
||||
"date": date,
|
||||
"main_content": main_content,
|
||||
"redaktion": redaktion,
|
||||
"full_content": full_content,
|
||||
"date_year": date_year,
|
||||
"date_full": date_num,
|
||||
"url": link
|
||||
}
|
||||
|
||||
id = (str(date) + "_" + str(author) + "_" + str(maintitle)).replace(" ", "").replace("/", "").replace("ö", "").replace("ä", "").replace("ü", "").replace("Ö", "").replace("Ä", "").replace("Ü", "").replace(".", "").replace("?", "")
|
||||
id = id + "_archiv"
|
||||
|
||||
upload(dict, id)
|
||||
|
||||
|
||||
def upload(dict, id):
|
||||
print("--- Uploading")
|
||||
try:
|
||||
es.index(index=index_name, id=id, document=dict)
|
||||
except Exception as e:
|
||||
print("--- Error while uploading")
|
||||
print(e)
|
||||
|
||||
def check_elastic_online():
|
||||
if not es.ping():
|
||||
sys.exit("No connection to Elasticsearch")
|
||||
|
||||
# main - entry point
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
|
||||
check_elastic_online()
|
||||
|
||||
years = [2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016]
|
||||
link_1 = "https://www.uni-due.de/aktuell/archiv-"
|
||||
link_2 = ".php"
|
||||
|
||||
options = Options()
|
||||
options.add_argument("--headless")
|
||||
|
||||
driver = webdriver.Firefox(options=options)
|
||||
|
||||
for year in years:
|
||||
print(f"Crawling year {year}")
|
||||
link = link_1 + str(year) + link_2
|
||||
|
||||
# get year links
|
||||
links, dates, dates_year, dates_num = getLinks(link, driver)
|
||||
|
||||
for i in range(len(links)):
|
||||
print(f"--- Crawling Data for current year {year} at {i} / {len(links)}")
|
||||
getData(driver, links[i], dates[i], dates_year[i], dates_num[i])
|
||||
|
||||
driver.close()
|
||||
|
||||
print("Finished")
|
||||
@@ -0,0 +1,3 @@
|
||||
#please check for right versions of the packages in your environment and update them if necessary
|
||||
spacy
|
||||
selenium
|
||||
@@ -0,0 +1,49 @@
|
||||
import subprocess
|
||||
import sys
|
||||
import os
|
||||
import shutil
|
||||
import time
|
||||
|
||||
def run_command(command, cwd=None):
|
||||
"""Run a shell command and exit if it fails."""
|
||||
result = subprocess.run(command,
|
||||
shell=True,
|
||||
cwd=cwd,
|
||||
#capture_output=True, #supresses output from subprocess
|
||||
text=True)
|
||||
if result.returncode != 0:
|
||||
print(f"Command failed: {command}")
|
||||
print("Error output:\n", result.stderr)
|
||||
sys.exit(result.returncode)
|
||||
|
||||
if __name__ == "__main__":
|
||||
start_time = time.time()
|
||||
|
||||
base_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
crawler_dir = os.path.join(base_dir, "aktuell")
|
||||
out_dir = os.path.join(crawler_dir, "out")
|
||||
|
||||
if os.path.exists(out_dir):
|
||||
shutil.rmtree(out_dir)
|
||||
os.makedirs(out_dir)
|
||||
|
||||
output_file_links = os.path.join(out_dir, "links.json")
|
||||
output_file_meta = os.path.join(out_dir, "meta.json")
|
||||
|
||||
|
||||
print("Running Scrapy link crawler...")
|
||||
run_command(f"scrapy crawl aktuell-links -O \"{output_file_links}\"", cwd=crawler_dir)
|
||||
|
||||
print("Running Scrapy meta crawler...")
|
||||
run_command(f"scrapy crawl aktuell-metadata -O \"{output_file_meta}\"", cwd=crawler_dir)
|
||||
|
||||
print("Running upload script")
|
||||
run_command(f"{sys.executable} upload_aktuell.py {output_file_meta}", cwd=base_dir)
|
||||
|
||||
end_time = time.time()
|
||||
runtime_seconds = end_time - start_time
|
||||
runtime_hours = runtime_seconds / 3600
|
||||
|
||||
print(f"Runtime: {runtime_hours:.2f} hours")
|
||||
print("Finished crawling and uploading UDE news articles.")
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
from elasticsearch import Elasticsearch
|
||||
import sys
|
||||
import os
|
||||
import json
|
||||
from datetime import datetime
|
||||
import time
|
||||
|
||||
# elasticsearch-connection should be adjusted
|
||||
# uni-server
|
||||
es = Elasticsearch()
|
||||
|
||||
index_name = "aktuell-test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index
|
||||
|
||||
|
||||
# checks if elastic is up and creates the index if not already done
|
||||
def check_elastic():
|
||||
if not es.ping():
|
||||
sys.exit("No connection to Elasticsearch")
|
||||
|
||||
if not es.indices.exists(index=index_name):
|
||||
settings = {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"searchabilityAnalyzer": {
|
||||
"type": "custom",
|
||||
"tokenizer": "standard",
|
||||
"filter": [
|
||||
"lowercase",
|
||||
"asciifolding"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mappings = {
|
||||
"properties": {
|
||||
"subtitle": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"maintitle": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"author": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"date": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"date_year": {
|
||||
"type": "long",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"date_full": {
|
||||
"type": "long",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"intro_content": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"main_content": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"further_content": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"redaktion": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"full_content": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
},
|
||||
"tags_nested": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"tag": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 250
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
#"links": {
|
||||
# "type": "text",
|
||||
# "analyzer": "searchabilityAnalyzer",
|
||||
# "search_analyzer": "searchabilityAnalyzer",
|
||||
# "fields": {
|
||||
# "keyword": {
|
||||
# "type": "keyword",
|
||||
# "ignore_above": 256
|
||||
# }
|
||||
# }
|
||||
#},
|
||||
"links_nested": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"url": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 250
|
||||
}
|
||||
}
|
||||
},
|
||||
"text": {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 250
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
es.indices.create(index=index_name, mappings=mappings, settings=settings)
|
||||
|
||||
def upload(path):
|
||||
with open(path, "r", encoding='utf-8') as json_file:
|
||||
|
||||
try:
|
||||
json_loaded = json.load(json_file)
|
||||
|
||||
for news in json_loaded:
|
||||
time.sleep(10 / 1000)
|
||||
id = (str(news["date"]) + "_" + str(news["author"]) + "_" + str(news["maintitle"])).replace(" ", "").replace("/", "").replace("ö", "").replace("ä", "").replace("ü", "").replace("Ö", "").replace("Ä", "").replace("Ü", "").replace(".", "").replace("?", "")
|
||||
|
||||
links_nested = []
|
||||
links = news["links"]
|
||||
|
||||
for link in links:
|
||||
links_nested.append({"url": link["url"], "text": link["text"].replace(" ", "")})
|
||||
|
||||
tags_nested = []
|
||||
tags = news["tags"]
|
||||
for p in range(len(tags)):
|
||||
tags_nested.append({"tag": tags[p]})
|
||||
|
||||
dict = {
|
||||
"subtitle": news["subtitle"],
|
||||
"maintitle": news["maintitle"],
|
||||
"tags": news["tags"],
|
||||
"author": news["author"],
|
||||
"date": news["date"],
|
||||
"intro_content": news["intro_content"],
|
||||
"main_content": news["main_content"],
|
||||
"further_content": news["further_content"],
|
||||
"redaktion": news["redaktion"],
|
||||
"full_content": news["full_content"],
|
||||
"tags_nested": tags_nested,
|
||||
"date_year": news["date_year"],
|
||||
"date_full": news["date_full"],
|
||||
#"links": news["links"],
|
||||
"links_nested": links_nested,
|
||||
"url": news["url"]
|
||||
}
|
||||
|
||||
es.index(index=index_name, id=id, document=dict)
|
||||
|
||||
except Exception as e:
|
||||
print("--- Failed to upload news.")
|
||||
print(e)
|
||||
|
||||
# main - entry point
|
||||
if __name__ == '__main__':
|
||||
check_elastic()
|
||||
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit("No path given.")
|
||||
upload(sys.argv[1])
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"FKZ": "Förderkennzeichen",
|
||||
"Thema des geförderten Vorhabens": "Thema",
|
||||
"Ressort": "Ressort",
|
||||
"Ressort_fullname": "Ressort_fullname",
|
||||
"Referat": "Referat",
|
||||
"Administrierende Stelle": "Projektträger",
|
||||
"PT_fullname": "Projektträger_fullname",
|
||||
"Arb.-Einh.": "Arb.-Einh.",
|
||||
"Laufzeit von": "funding_start",
|
||||
"Laufzeit bis": "funding_end",
|
||||
"Laufzeit":"Laufzeit",
|
||||
"Förderart": "Förderart",
|
||||
"Förderempfänger /Auftragnehmer": "Zuwendungsempfänger",
|
||||
"Gemeindekennziffer": "Gemeindekennziffer",
|
||||
"Förder- / Auftragssumme (Anteil des Bundes) in EUR": "Fördersumme",
|
||||
"Stadt/Gemeinde": "Stadt/Gemeinde",
|
||||
"Ort": "Ort",
|
||||
"Bundesland": "Bundesland",
|
||||
"Staat": "Staat",
|
||||
"Leistungsplansystematik": "Leistungsplansystematik",
|
||||
"Leistungsplansystematik_fullname": "Leistungsplansystematik_fullname",
|
||||
"Klartext Leistungsplansystematik": "Klartext Leistungsplansystematik",
|
||||
"Förderprofil": "Förderprofil",
|
||||
"Projekt": "Verbundprojekt",
|
||||
"Ausführende Stelle": "Ausführende Stelle"
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
from selenium import webdriver
|
||||
from selenium.common.exceptions import NoSuchElementException
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from selenium.webdriver.common.by import By
|
||||
from selenium.webdriver.support.ui import WebDriverWait
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.webdriver.common.alert import Alert
|
||||
from random import randint
|
||||
import time
|
||||
import pandas as pd
|
||||
import json
|
||||
from datetime import datetime
|
||||
import sys
|
||||
from elasticsearch import Elasticsearch, helpers
|
||||
from elasticsearch.helpers import bulk,BulkIndexError
|
||||
import os
|
||||
import hashlib
|
||||
|
||||
|
||||
download_path=os.path.abspath(os.getcwd())
|
||||
es = Elasticsearch()
|
||||
|
||||
def crawl_data(link,driver):
|
||||
driver.get(link)
|
||||
search_field = driver.find_element(By.ID,"suche_schnellSuche")
|
||||
if search_field.is_displayed():
|
||||
# The element is visible, safe to interact
|
||||
search_field.send_keys("*")
|
||||
start_search_btn = driver.find_element(By.XPATH,'/html/body/div[1]/div/div/form[1]/div/fieldset/table/tbody/tr[1]/td[2]/input')
|
||||
start_search_btn.click()
|
||||
|
||||
WebDriverWait(driver, 30).until(
|
||||
EC.element_to_be_clickable((By.XPATH,'//*[@id="unterNavigation"]/ul/li[4]/div/a'))
|
||||
)
|
||||
|
||||
#Click the Export button to trigger data export
|
||||
export_button = driver.find_element(By.XPATH,'//*[@id="unterNavigation"]/ul/li[4]/div/a')
|
||||
export_button.click()
|
||||
# Wait for the prompt to appear
|
||||
time.sleep(2)
|
||||
# Switch to the alert and Clicks the "OK" button
|
||||
Alert(driver).accept()
|
||||
print("downloading data")
|
||||
else:
|
||||
# The element is likely a honeypot, do not interact
|
||||
print("Honeypot detected, skipping interaction")
|
||||
|
||||
|
||||
def check_elastic_online():
|
||||
if not es.ping():
|
||||
sys.exit("No connection to Elasticsearch")
|
||||
else :
|
||||
print("Elasticsearch connection established")
|
||||
|
||||
def check_elastic_index(df, index_name):
|
||||
|
||||
if not es.indices.exists(index=index_name):
|
||||
print(index_name + " index wasn't found. Creating a new one..")
|
||||
settings = {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"searchabilityAnalyzer": {
|
||||
"type": "custom",
|
||||
"tokenizer": "standard",
|
||||
"filter": [
|
||||
"lowercase",
|
||||
"asciifolding"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mappings = {}
|
||||
properties = {}
|
||||
|
||||
for key in list(df.columns):
|
||||
if key in ("funding_start", "funding_end", "datum"):
|
||||
properties[key] = {
|
||||
"type": "date",
|
||||
"format": "dd.MM.yyyy"
|
||||
}
|
||||
elif key == "Publikationsdatum":
|
||||
properties[key] = {
|
||||
"type": "date",
|
||||
"format": "yyyy"
|
||||
}
|
||||
elif key == "unix_timestamp":
|
||||
properties[key] = {
|
||||
"type": "long"
|
||||
}
|
||||
elif key == "Fördersumme":
|
||||
properties[key] = {
|
||||
"type": "float"
|
||||
}
|
||||
elif key == "new":
|
||||
properties[key] = {
|
||||
"type": "boolean"
|
||||
}
|
||||
else:
|
||||
properties[key] = {
|
||||
"type": "text",
|
||||
"analyzer": "searchabilityAnalyzer",
|
||||
"search_analyzer": "searchabilityAnalyzer",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword",
|
||||
"ignore_above": 256
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mappings["properties"] = properties
|
||||
|
||||
es.indices.create(index=index_name, mappings=mappings, settings=settings)
|
||||
es.indices.refresh(index=index_name)
|
||||
print("The new index '"+index_name+"' has been created")
|
||||
else:
|
||||
print(index_name + " already exists. Uploading data...")
|
||||
|
||||
def upload_data(df,index_name):
|
||||
def fill_docs_to_upload(row):
|
||||
doc_id = hashlib.sha256(str(row['Förderkennzeichen']).encode('utf-8')).hexdigest()
|
||||
doc = {
|
||||
"_op_type": "update", # Update existing documents
|
||||
"_index": index_name,
|
||||
"_id": doc_id,
|
||||
"doc": {
|
||||
"new":False
|
||||
},
|
||||
"upsert":{
|
||||
**row.to_dict(),
|
||||
"new":True
|
||||
}
|
||||
}
|
||||
|
||||
docs_to_upload.append(doc)
|
||||
print("Uploading data...")
|
||||
|
||||
try:
|
||||
check_elastic_index(df, index_name)
|
||||
except Exception as e:
|
||||
print("Error while creating index")
|
||||
print(e)
|
||||
|
||||
docs_to_upload = []
|
||||
df.apply(fill_docs_to_upload,axis=1)
|
||||
def bulk_docs(docs,data_rate):
|
||||
response_sum = 0
|
||||
for i in range(0, len(docs), data_rate):
|
||||
try:
|
||||
response = helpers.bulk(es,docs[i:i + data_rate])
|
||||
response_sum = response_sum + response[0]
|
||||
except BulkIndexError as e:
|
||||
print(f"{len(e.errors)} document(s) failed to index.")
|
||||
for error in e.errors:
|
||||
print("Error details:", error)
|
||||
print ("Upload is completed. "+ str(response_sum) +" documents have been uploaded." )
|
||||
data_rate = 200
|
||||
bulk_docs(docs_to_upload,data_rate)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def wait_for_file_complete(download_path,file_name):
|
||||
while True:
|
||||
file_path = os.path.join(download_path, file_name)
|
||||
if os.path.exists(file_path) and not any(
|
||||
fname.endswith(".part") or fname.endswith(".crdownload")
|
||||
for fname in os.listdir(download_path)
|
||||
):
|
||||
print(f"Download complete: {file_name}")
|
||||
return True
|
||||
if any(fname.endswith((".part", ".crdownload")) for fname in os.listdir(download_path)):
|
||||
time.sleep(1)
|
||||
else:
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
|
||||
def format_data(df):
|
||||
print("Formattind data...")
|
||||
df.drop(list(df.filter(regex='.1|Unnamed')), axis=1, inplace=True)
|
||||
def clean_format(text):
|
||||
if isinstance(text, str):
|
||||
if text.startswith('="') and text.endswith('"'):
|
||||
return text[2:-1]
|
||||
return text
|
||||
df.columns = [clean_format(col) for col in df.columns]
|
||||
|
||||
df = df.applymap(clean_format)
|
||||
df["FKZ"] = df["FKZ"].str.replace(' /','/')
|
||||
json_path = os.path.join(os.path.abspath(os.getcwd()), 'extendingColumns.json')
|
||||
|
||||
with open(json_path, 'r', encoding='utf-8') as f:
|
||||
columnsObj = json.load(f)
|
||||
for column_name, content in columnsObj.items():
|
||||
alias_map = content['aliases']
|
||||
df[content['column_alias']] = df[column_name].map(alias_map)
|
||||
|
||||
|
||||
|
||||
df['Publikationsdatum'] = df['Laufzeit von'].str.split('.').str[2]
|
||||
df['unix_timestamp'] = int(time.time())
|
||||
df['datum'] = datetime.now().strftime("%d.%m.%Y")
|
||||
df['new'] = True
|
||||
if len(df['Laufzeit von']) and len(df['Laufzeit bis']):
|
||||
df['Laufzeit'] = "von " + df['Laufzeit von'] + " bis " + df['Laufzeit bis']
|
||||
|
||||
config_path = os.path.join(os.path.abspath(os.getcwd()), 'data_config.json')
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
config = json.load(f)
|
||||
df.rename(columns=config,inplace=True)
|
||||
|
||||
df = df.where(pd.notnull(df), "")
|
||||
df['Fördersumme'] = pd.to_numeric(
|
||||
df['Fördersumme'].astype(str)
|
||||
.str.replace('.', '', regex=False)
|
||||
.str.replace(',', '.', regex=False),
|
||||
errors='coerce'
|
||||
)
|
||||
return df
|
||||
|
||||
def setup_chrome_driver(download_path):
|
||||
options = Options()
|
||||
options.add_argument("--headless")
|
||||
options.add_argument("--no-sandbox")
|
||||
options.add_argument("--disable-dev-shm-usage")
|
||||
options.add_experimental_option("prefs", {
|
||||
"download.default_directory": download_path,
|
||||
"download.prompt_for_download": False,
|
||||
"download.directory_upgrade": True,
|
||||
"plugins.always_open_pdf_externally": True,
|
||||
})
|
||||
chromedriver_path = "/home/inse/miniconda3/envs/airflow/bin/chromedriver"
|
||||
service = Service(executable_path=chromedriver_path)
|
||||
driver = webdriver.Chrome(service=service, options=options)
|
||||
return driver
|
||||
|
||||
|
||||
# main - entry point
|
||||
if __name__ == '__main__':
|
||||
print("Starting")
|
||||
file_path = os.path.join(os.path.abspath(os.getcwd()), 'Suchliste.csv')
|
||||
if not os.path.exists(file_path):
|
||||
driver = setup_chrome_driver(download_path)
|
||||
link_to_crawl= "https://foerderportal.bund.de/foekat/jsp/SucheAction.do?actionMode=searchreset"
|
||||
crawl_data(link_to_crawl,driver)
|
||||
wait_for_file_complete(download_path, "Suchliste.csv")
|
||||
driver.close()
|
||||
|
||||
|
||||
file = pd.read_csv(file_path,encoding = "latin1",sep=";")
|
||||
df = pd.DataFrame(file)
|
||||
df_formatted = format_data(df)
|
||||
|
||||
index_name = "projects_bund_test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index
|
||||
check_elastic_online()
|
||||
upload_data(df_formatted,index_name)
|
||||
os.remove(file_path)
|
||||
|
||||
@@ -49,7 +49,7 @@ import httpx
|
||||
from dotenv import load_dotenv
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from mapping import PROJECT_TOPICS_MAPPING
|
||||
from service.scripts.projects.topic_mapper.mapping import PROJECT_TOPICS_MAPPING
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -355,11 +355,13 @@
|
||||
}
|
||||
</div>
|
||||
|
||||
<app-data-table
|
||||
[columns]="workColumns"
|
||||
[data]="elements()"
|
||||
queryParamSortKey="sort_by"
|
||||
queryParamSortDirectionKey="sort_direction" />
|
||||
<div class="table-wrap">
|
||||
<app-data-table
|
||||
[columns]="workColumns"
|
||||
[data]="elements()"
|
||||
queryParamSortKey="sort_by"
|
||||
queryParamSortDirectionKey="sort_direction" />
|
||||
</div>
|
||||
<app-query-param-paginator
|
||||
[total]="totalElements()"
|
||||
queryParamPageKey="page"
|
||||
@@ -469,6 +471,12 @@
|
||||
institution.institution_country_code.toUpperCase()
|
||||
}}</span>
|
||||
}
|
||||
<mat-icon
|
||||
class="institution-open-icon"
|
||||
(click)="openInstitutionPage(institution.institution_id, $event)"
|
||||
aria-label="Institutionsseite öffnen"
|
||||
>open_in_new</mat-icon
|
||||
>
|
||||
</button>
|
||||
} @empty {
|
||||
<span class="empty-text">-</span>
|
||||
|
||||
@@ -494,23 +494,25 @@ table.is-hidden {
|
||||
}
|
||||
|
||||
.table-wrap ::ng-deep {
|
||||
.mat-column-type,
|
||||
.mat-column-year,
|
||||
.mat-column-language,
|
||||
.mat-column-citations,
|
||||
.mat-mdc-header-cell {
|
||||
text-align: center;
|
||||
}
|
||||
.mat-sort-header-container {
|
||||
justify-content: center;
|
||||
}
|
||||
.mat-mdc-cell:not(.mat-column-title) {
|
||||
text-align: center;
|
||||
}
|
||||
.mat-column-institutions .institution-tags,
|
||||
.mat-column-topics .topic-chips {
|
||||
justify-content: center;
|
||||
margin-inline: auto;
|
||||
}
|
||||
|
||||
.mat-mdc-cell:not(:last-child),
|
||||
.mat-mdc-header-cell:not(:last-child) {
|
||||
border-right: 1px solid var(--sg-border);
|
||||
}
|
||||
|
||||
.mat-column-institutions,
|
||||
.mat-column-topics {
|
||||
overflow: visible;
|
||||
}
|
||||
}
|
||||
|
||||
mat-paginator {
|
||||
|
||||
@@ -270,7 +270,6 @@ export class PersonPublicationsComponent implements OnInit {
|
||||
topicNames: 'publicationTopicName',
|
||||
topicFields: 'publicationTopicField',
|
||||
topicDomains: 'publicationTopicDomain',
|
||||
sort: 'publicationSort',
|
||||
} as const;
|
||||
|
||||
readonly typeOptions = [
|
||||
@@ -768,6 +767,19 @@ export class PersonPublicationsComponent implements OnInit {
|
||||
return id.split('/').filter(Boolean).pop() ?? null;
|
||||
}
|
||||
|
||||
openInstitutionPage(
|
||||
institutionId: string | null | undefined,
|
||||
event: Event,
|
||||
): void {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
|
||||
const id = this.extractRawId(institutionId);
|
||||
if (!id) return;
|
||||
|
||||
void this.router.navigate(['/institution', id]);
|
||||
}
|
||||
|
||||
getWorkTopicColor(topic: WorkTopic): string {
|
||||
return topicHierarchyColor({
|
||||
id: topic.id,
|
||||
|
||||