content extractor updated: source, keywords, links fields added.

This commit is contained in:
2025-06-18 14:21:23 +02:00
parent e8012a1f95
commit b5cce5aecd
@@ -17,43 +17,80 @@ es = Elasticsearch('https://inse.nes.uni-due.de:443/elastic', basic_auth=('elas
ude_organization_categorized = "ude_organization_categorized"
new_index_name = "ude_organization_content"
total_succeeds = 0
total_failures = 0
URL = "https://project.nes.uni-due.de/llm1/v1/chat/completions"
HEADERS = {"Content-Type": "application/json"}
prompt_staff = """You are a Named Entity Recognizer. You will be given a text about PERSONS. Recognize and extract from the text the following informations for ALL persons:
1. NAME (The full name of the person).
2. TELEFON (The person's phone number).
3. EMAIL (The person's email address).
4. RESEARCH_INTERESTS (Keywords or phrases describing the research areas or fields that the person is interested in. e.g., "machine learning," "quantum computing," "sustainable energy").Separate multiple interests with commas.
prompt_staff = """You are a Named Entity Recognizer.
Important:
If 3 of 4 fields are missing. DO NOT include the persons to the resulting array.
If any field (name, phone number, email, or research interests) is missing, use an empty string for that field.
- Your output must be a valid, stringified JSON array with the format:
[{"name": name1, "telefon": telefon1, "email": email1, "research_interests": "interest1, interest2"}, {"name": name2, "telefon": telefon2, "email": email2, "research_interests": "interest1, interest2"}]
Do not add any comments or explanations. Just return the JSON array.
Example Output:[{"name": "John Doe", "telefon": "123-456-7890", "email": "john.doe@example.com", "research_interests": "machine learning, computer vision"}, {"name": "Jane Smith", "telefon": "", "email": "jane.smith@example.com", "research_interests": "quantum computing"}]"""
Given a text, extract information about all persons mentioned. For each person, extract the following fields:
1. name - The full name.
2. telefon - Phone number.
3. email - Email address.
4. research_interests - Keywords or phrases describing research areas (e.g., "machine learning", "quantum computing"). Separate multiple interests with commas.
Rules:
- If a person has fewer than two non-empty fields, do not include them.
- For missing fields, use an empty string ("").
- Your output must be a valid, stringified JSON array in this format:
[{"name": "", "telefon": "", "email": "", "research_interests": ""}, ...]
prompt_projects ="""You are a Named Entity Recognizer. You will be given a text about PROJECTS .Recognize and extract from the text the following informations for ALL projects: TITLE(Name of the project),TOPIC,NAMES(people involved to projects, concatenated by ','),PROJECT_TYPE ("student" for bachelor or master projects or project groups, "BUND" for all Bundesministeriums, "EU" for European Union fundings or "DFG" for Deutsche Forschungsgemeinschaft. "Other" for all other fundings.).
Respond ONLY with stringified valid JSON array with the following format [{"title":title1,"topic":topic1,"names":names1,"project_type":"student"},{"title":title2,"topic":topic2,"names":names2,"project_type":"DFG"}]. Important: Use empty string if no informations given. Add no comments"""
prompt_news ="""You are a Named Entity Recognizer. You will be given a text about NEWS. Recognize and extract from the text the following informations for ALL news: TITLE(Name of the new),TOPIC,DATE(date of publishing in format *dd.mm.yyyy*).
Respond ONLY with a stringified valid JSON array with the following format [{"title":title1,"topic":topic1,"date":date1},{"title":title2,"topic":topic2,"date":date2}]. Important: Use empty string if no informations given. Add no comments."""
Do not include any explanation or extra output. Return only the JSON array.
Example output:
[{"name": "John Doe", "telefon": "123-456-7890", "email": "john.doe@example.com", "research_interests": "machine learning, computer vision"}, {"name": "Jane Smith", "telefon": "", "email": "jane.smith@example.com", "research_interests": "quantum computing"}]
"""
prompt_projects ="""You are a Named Entity Recognizer.
You will be given a text about research projects. Extract the following information for each project mentioned:
1. title - Name of the project.
2. topic - The main subject or theme of the project.
3. names - People involved in the project, as a single string of names separated by commas.
4. project_type - One of the following:
- "student" for bachelor/master projects or project groups,
- "BUND" for Bundesministerium-funded projects,
- "EU" for European Union-funded projects,
- "DFG" for Deutsche Forschungsgemeinschaft-funded projects,
- "Other" for all other types of funding.
Rules:
- If a field is missing, use an empty string ("").
- Respond ONLY with a valid, stringified JSON array in this format:
[{"title": "", "topic": "", "names": "", "project_type": ""}, ...]
- Do not add any comments or explanations.
Example output:
[{"title": "GreenAI", "topic": "sustainable AI", "names": "Alice Smith, Bob Johnson", "project_type": "EU"}, {"title": "Quantum Simulators", "topic": "", "names": "Dr. Jane Doe", "project_type": "DFG"}]
"""
prompt_news ="""You are a Named Entity Recognizer.
You will be given a text about news items. Extract the following information for each piece of news:
1. title - The title or name of the news item.
2. topic - The main subject or theme.
3. date - The publishing date. Convert it in the format **dd.mm.yyyy**. if not possible return empty string ("").
Rules:
- Use an empty string ("") for any missing field.
- Respond ONLY with a valid, stringified JSON array in this format:
[{"title": "", "topic": "", "date": ""}, ...]
Do not include any comments or explanations.
Example output:
[{"title": "New AI Lab Opens", "topic": "artificial intelligence", "date": "12.06.2025"}, {"title": "Climate Conference 2025", "topic": "environment", "date": ""}]
"""
prompt_staff_clean = """
You are given a JSON array of objects, each representing a person with the fields "name", "telefon" "email" and "research_interests".
You are given a JSON array of objects, each representing a person with the fields "name", "telefon" "email" , "research_interests" and "source".
Identify duplicates based only on the "name" field.
For each set of duplicates, merge them into a single object by combining non-empty values:
- If one object has an "email" and another has a "telefon", combine them.
Merge unique research_interests for duplicates.
Important: Discard any objects where both "email" and "telefon" are empty.
DO NOT MODIFY "source" fields.
Return only unique persons (by name) with the merged available information.
Respond ONLY with a valid stringified array of unique JSON objects. Do not include any comments or extra text.
@@ -61,23 +98,23 @@ Respond ONLY with a valid stringified array of unique JSON objects. Do not inclu
prompt_clean = """You are given an array of JSON objects. Identify and remove duplicates based on the "title" field. For each set of duplicates, keep only the objects having all fields non-empty. Respond ONLY with a valid stringified array of unique JSON objects. Do not include any comments or extra text."""
def goDeep(d,urls):
def go_deep(d,urls):
skipNodes = ['faculty','institutes','chairs']
if d['type'] in skipNodes:
for child in d['children']:
goDeep(child, urls )
go_deep(child, urls )
elif (d['type'] == 'leaf') and ('children' in d):
for child in d['children']:
goDeep(child, urls )
go_deep(child, urls )
elif (d['type'] == 'leaf'):
urls.add(d['link_de'])
def getUrls(path_to_hierarchy):
def get_urls(path_to_hierarchy):
urls = set()
with open(path_to_hierarchy, 'r', encoding='utf-8') as orgs:
data = json.load(orgs)
for faculty in data:
goDeep(faculty,urls)
go_deep(faculty,urls)
return list(urls)
def check_format(array_of_dicts, valid_keys):
@@ -89,6 +126,9 @@ def check_format(array_of_dicts, valid_keys):
if ('date' in d) and (len(d['date'])>0):
if not is_valid_german_date(d['date']):
return False
if ('source' in d):
if not (isinstance(d['source'],str)):
return False
return True
except:
@@ -97,6 +137,7 @@ def extract_entitites(prompt,array, valid_keys, max_retries = 5):
entities = []
successes = 0
fails = 0
failed_pages = []
for page in array:
retries = 0
body = normalize_for_ner(page['_source']['body'])
@@ -105,12 +146,12 @@ def extract_entitites(prompt,array, valid_keys, max_retries = 5):
#print(body)
print(f"Extracting {page['_source']['uri']} with {num_tokens} tokens.")
#print(page['_source']['body'])
time.sleep(1)
while True:
if (retries > max_retries):
print(f"Couldnt extract content for {page['_source']['uri']} ... Skipping it...")
fails +=1
failed_pages.append(page['_source']['uri'])
break
time.sleep(1)
response_array = []
@@ -150,7 +191,7 @@ def extract_entitites(prompt,array, valid_keys, max_retries = 5):
print(f"Invalid JSON format. Retrying... Retries left:{max_retries - retries}\n {content}")
time.sleep(1)
if not check_format(response_array,valid_keys=valid_keys):
print("Wrong data format! Retrying...",response_array)
print("Wrong data format! Retrying...")
continue
if ('email' in valid_keys and 'telefon' in valid_keys):
@@ -161,10 +202,18 @@ def extract_entitites(prompt,array, valid_keys, max_retries = 5):
time.sleep(1)
continue
break
#print(response_array)
for entry in response_array:
entry['source'] = page['_source']['uri']
successes+=1
entities += response_array
return entities ,successes, fails
return entities ,successes, fails, failed_pages
def add_keywords_and_links(array_of_dicts):
result = []
for d in array_of_dicts:
d['keywords'] = []
d['links'] = []
result.append(d)
return result
def cleanData(prompt,data,valid_keys):
input_data = json.dumps(data)
@@ -172,7 +221,6 @@ def cleanData(prompt,data,valid_keys):
print(f"Cleaning with {num_tokens} tokens.")
while True:
data = {
"model": "tgi",
"messages": [
@@ -218,6 +266,8 @@ def cleanData(prompt,data,valid_keys):
if ('date' in valid_keys) :
clean_data = handle_date(clean_data)
return clean_data
def split_interests(persons):
result = []
@@ -237,9 +287,11 @@ def handle_date(news):
def is_valid_german_date(date_str):
try:
datetime.strptime(date_str, "%d.%m.%Y")
datetime.strptime(date_str.strip(), "%d.%m.%Y")
return True
except ValueError:
print("wrong date format!", date_str)
return False
def count_tokens(content):
@@ -254,7 +306,7 @@ def normalize_for_ner(text):
text = re.sub(r'\s+', ' ', text).strip()
return text
def getRelevantKeywords(orgs,max_keywords=20):
def get_relevant_keywords(orgs,max_keywords=20):
keywords_arrs = [org['_source']['keywords'] for org in orgs]
keywords = []
for kw_arr in keywords_arrs:
@@ -307,25 +359,24 @@ def check_elastic_status(index_name):
}
},
"body": {
"type": "text",
"analyzer": "customanalyzer",
"search_analyzer": "customanalyzer"
},
"staff": {
"type": "nested",
"properties": {
"name": { "type": "text" },
"telefon": { "type": "text" },
"email": { "type": "text" },
"research_interests": { "type": "text" }
"research_interests": { "type": "text" },
"keywords": { "type": "text" },
"links": { "type": "text" }
}
}, "projects": {
"type": "nested",
"properties": {
"title": { "type": "text" },
"topic": { "type": "text" },
"names": { "type": "text" }
"names": { "type": "text" },
"keywords": { "type": "text" },
"links": { "type": "text" }
}
}, "news": {
"type": "nested",
@@ -337,6 +388,8 @@ def check_elastic_status(index_name):
"format": "dd.MM.yyyy",
"null_value": "01.01.0001"
},
"keywords": { "type": "text" },
"links": { "type": "text" }
}
},
"tags": {
@@ -371,7 +424,9 @@ if __name__ == '__main__':
if (len(sys.argv) < 2):
print("The path for hierarchy was not given.")
exit(1)
urls = getUrls(sys.argv[1])
urls = get_urls(sys.argv[1])[-3:]
if (check_elastic_status(new_index_name)):
for idx,url in enumerate(urls):
print(f'Extracting Organization:{idx + 1} of {len(urls)}: {url}')
@@ -394,7 +449,7 @@ if __name__ == '__main__':
result = es.search(index=ude_organization_categorized, body=body)['hits']['hits']
organization = {"uri":url,"staff":[],"projects":[],"news":[]}
organization['keywords'] = getRelevantKeywords(result)
organization['keywords'] = get_relevant_keywords(result)
staff = [org for org in result if org['_source']['category']=="Staff"]
projects = [org for org in result if org['_source']['category']=="Projects"]
@@ -402,18 +457,22 @@ if __name__ == '__main__':
succeededExtractions = 0
failedExtractions = 0
failedPages = []
print(f'Exracting staff ({len(staff)}):')
staff_data, successes, fails = extract_entitites(prompt=prompt_staff,array = staff,valid_keys=['name','email','telefon','research_interests'])
staff_data, successes, fails, failed_pages = extract_entitites(prompt=prompt_staff,array = staff,valid_keys=['name','email','telefon','research_interests'])
succeededExtractions += successes
failedExtractions += fails
failedPages += failed_pages
print(f'Exracting projects ({len(projects)}):')
projects_data, successes, fails = extract_entitites(prompt=prompt_projects,array = projects,valid_keys=['title','topic','names','project_type'])
projects_data, successes, fails, failed_pages = extract_entitites(prompt=prompt_projects,array = projects,valid_keys=['title','topic','names','project_type'])
succeededExtractions += successes
failedExtractions += fails
failedPages += failed_pages
print(f'Exracting news ({len(news)}):')
news_data, successes, fails = extract_entitites(prompt=prompt_news,array = news,valid_keys=['title','topic','date'])
news_data, successes, fails, failed_pages = extract_entitites(prompt=prompt_news,array = news,valid_keys=['title','topic','date'])
succeededExtractions += successes
failedExtractions += fails
failedPages += failed_pages
totalExtractions = len(staff) + len(projects) + len(news)
@@ -427,6 +486,9 @@ if __name__ == '__main__':
cleaned_projects = cleanData(prompt=prompt_clean, data=projects_data,valid_keys=['title','topic','names','project_type'],)
cleaned_news = cleanData(prompt=prompt_clean, data=news_data,valid_keys=['title','topic','date'])
cleaned_staff = add_keywords_and_links(cleaned_staff)
cleaned_projects = add_keywords_and_links(cleaned_projects)
cleaned_news = add_keywords_and_links(cleaned_news)
organization['staff'] = cleaned_staff if cleaned_staff else []
organization['projects'] = cleaned_projects if cleaned_projects else []
@@ -439,4 +501,6 @@ if __name__ == '__main__':
es.index(index=new_index_name, document=organization)
print('Organization uploaded.')
print(f'Total pages extracted: {total_succeeds}')
print(f'Total failed extractions: {total_failures}')
print(f'Total failed extractions: {total_failures}')
if (len(failedPages)>0):
print('Could not extract data from pages ',failedPages)