Files
2024-07-24 10:30:28 +02:00

75 lines
2.3 KiB
Python

import pandas as pd
from tqdm import tqdm as progress
from bertopic import BERTopic
def assign_highest_n_contribution(origin_df, model, highest_n):
topics_df = pd.DataFrame()
for index, row in progress(origin_df.iterrows(), total = origin_df.shape[0]):
title = row["title"]
topics, similarities = model.find_topics(title, top_n=highest_n)
for idx,tupel in enumerate(zip(topics, similarities)):
topic_num, similarity = tupel
topic_keywords = ", ".join([word[0] for word in model.get_topic(topic_num)])
topics_df = topics_df.append({"dominant_topic": topic_num,
"topic_contribution": round(similarity,4),
"topic_keywords": topic_keywords,
"id": row["id"],
"title": row["title"],
"year": row["year"],
"doi": row["doi"],
"conference": row["conference"],
"genre": row["genre"],
"isbn": row["isbn"],
"author": row["author"],
"research_area": row["research_area"],
"institute": row["insitute"],
"faculty": row["faculty"],
"group": row["group"],
"language": row["language"]}, ignore_index=True)
topics_df.reset_index(drop=True, inplace=True)
return topics_df
print("Start")
# read in csv
print("Load CSV")
df = pd.read_csv("pubs_2000_2024.csv")
# split csv into en and de
print("Split")
df_en = df[df["language"] == "en"]
df_de = df[df["language"] == "de"]
# load models
print("Load models")
print("1")
model_en = BERTopic.load("model_en_600.bertopic", embedding_model="all-MiniLM-L6-v2")
print("2")
model_de = BERTopic.load("model_de_600.bertopic", embedding_model="paraphrase-multilingual-MiniLM-L12-v2")
# run en
print("----------------")
print("en")
print(df_en.info())
doc_topics_df_en = assign_highest_n_contribution(df_en, model_en, 10)
print("write en")
doc_topics_df_en.to_csv("doc_topic_en.csv",index=False)
# run de
print("----------------")
print("de")
print(df_de.info())
doc_topics_df_de = assign_highest_n_contribution(df_de, model_de, 10)
print("write de")
doc_topics_df_de.to_csv("doc_topic_de.csv",index=False)
print("Done")