ude organization upload added
This commit is contained in:
@@ -42,6 +42,13 @@ Within a single point you have to do the scripts from top to bottom.
|
||||
* Analysis: aktuell_spacy.py
|
||||
* Archiv: Done - not needed again
|
||||
|
||||
#### UDE Organization:
|
||||
* Info: Needs much disc space and time
|
||||
* Path: inse-internal-external-scripts\intern\ude_organization
|
||||
* Crawl:
|
||||
* Upload: upload_ude_pages.py
|
||||
+ Parameter: path to "warc_zips"-folder (should be in the same directory)
|
||||
|
||||
### Extern:
|
||||
|
||||
#### Common Crawl:
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
import warcio
|
||||
import sys
|
||||
import langdetect
|
||||
import trafilatura
|
||||
import os
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import html
|
||||
from elasticsearch import Elasticsearch
|
||||
import yake
|
||||
#inse elastic instance
|
||||
es = Elasticsearch('https://inse.nes.uni-due.de:443/elastic', basic_auth=('elastic', 'RLldUaJgbGeoqd3KCX3p'), request_timeout=60, max_retries=5, retry_on_timeout=True)
|
||||
#es = Elasticsearch({'host':'localhost', 'port': 9200, 'scheme': 'http'})
|
||||
#es = Elasticsearch('http://localhost:9200',verify_certs=True, basic_auth=('elastic', '+JFa3xVIF0g_YAhpgTLl'), max_retries=5, retry_on_timeout=True)
|
||||
|
||||
|
||||
|
||||
index_name = "ude_organization"
|
||||
|
||||
|
||||
def check_elastic_status():
|
||||
if not es.ping():
|
||||
print("Elasticsearch connection not found")
|
||||
return False
|
||||
|
||||
#if es.indices.exists(index=index_name):
|
||||
# es.indices.delete(index=index_name, ignore=[400, 404])
|
||||
|
||||
settings = {
|
||||
"analysis": {
|
||||
"analyzer": {
|
||||
"customanalyzer": {
|
||||
"type": "custom",
|
||||
"tokenizer": "standard",
|
||||
"filter": [
|
||||
"lowercase",
|
||||
"asciifolding"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mappings = {
|
||||
|
||||
"properties": {
|
||||
"uri": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword"
|
||||
}
|
||||
}
|
||||
},
|
||||
"domain": {
|
||||
"type": "keyword"
|
||||
},
|
||||
"subdomain": {
|
||||
"type": "keyword"
|
||||
},
|
||||
"path": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword"
|
||||
}
|
||||
}
|
||||
},
|
||||
"query": {
|
||||
"type": "text",
|
||||
"fields": {
|
||||
"keyword": {
|
||||
"type": "keyword"
|
||||
}
|
||||
}
|
||||
},
|
||||
"host": {
|
||||
"type": "keyword"
|
||||
},
|
||||
"body": {
|
||||
"type": "text",
|
||||
"analyzer": "customanalyzer",
|
||||
"search_analyzer": "customanalyzer"
|
||||
},
|
||||
"lang": {
|
||||
"type": "keyword"
|
||||
},
|
||||
"tags": {
|
||||
"type": "nested",
|
||||
"properties": {
|
||||
"value": { "type": "keyword" },
|
||||
"score": { "type": "double" }
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
try:
|
||||
if not es.indices.exists(index=index_name):
|
||||
es.indices.create(index=index_name, mappings=mappings, settings=settings)
|
||||
print(f"INDEX {index_name} created...")
|
||||
else:
|
||||
print(f"INDEX {index_name} already exists...")
|
||||
|
||||
|
||||
except Exception as e:
|
||||
print("failed to create index mapping")
|
||||
print(e)
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def getGroups(match):
|
||||
uri={'protocol':"",
|
||||
'subdomain':"",
|
||||
'domain':"",
|
||||
'port':"",
|
||||
'path':"",
|
||||
'query':""}
|
||||
if match:
|
||||
uri['protocol'] = match.group(1) if match.group(1) else ""
|
||||
uri['subdomain'] = match.group(2) if match.group(2) else ""
|
||||
uri['domain'] = match.group(3) if match.group(3) else ""
|
||||
uri['port'] = match.group(4) if match.group(4) else ""
|
||||
uri['path'] = match.group(5) if match.group(5) else ""
|
||||
uri['query'] = match.group(6) if match.group(6) else ""
|
||||
|
||||
return uri
|
||||
|
||||
|
||||
def process_file(filename,total_records):
|
||||
print("Searching file", filename)
|
||||
records = 0
|
||||
bodies = []
|
||||
regex_for_link_parts = r'^(\w+):\/\/(?:((?:[^\/:.]+\.)+))?([^\/:.]+(?:\.[^\/:.]+)+)(?::(\d+))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$'
|
||||
with open(filename, 'rb') as stream:
|
||||
for record in warcio.ArchiveIterator(stream):
|
||||
if record.rec_type == 'response':
|
||||
content_type = record.http_headers.get_header('Content-Type')
|
||||
if not bool(content_type):
|
||||
continue
|
||||
if 'text/html' in content_type.lower():
|
||||
tokens = content_type.split(";")
|
||||
encoding = "iso-8859-1"
|
||||
for token in tokens:
|
||||
trimmed = token.strip()
|
||||
if trimmed.startswith("charset="):
|
||||
encoding = trimmed[8:].lower()
|
||||
|
||||
try:
|
||||
decoded = record.content_stream().read().decode(encoding)
|
||||
except:
|
||||
continue
|
||||
|
||||
text = trafilatura.extract(decoded, output_format="txt")
|
||||
try:
|
||||
lang = langdetect.detect(text)
|
||||
except:
|
||||
lang = ''
|
||||
try:
|
||||
title = html.unescape(re.search(r"<title>(.*?)<\/title>", decoded).group(1))
|
||||
except:
|
||||
title=''
|
||||
keywords = []
|
||||
if lang == "de":
|
||||
keyword_extractor = yake.KeywordExtractor(
|
||||
dedupFunc="seqm",
|
||||
dedupLim=0.9,
|
||||
top=15,
|
||||
lan="de")
|
||||
yake_keywords = keyword_extractor.extract_keywords(text)
|
||||
|
||||
else:
|
||||
keyword_extractor = yake.KeywordExtractor(
|
||||
dedupFunc="seqm",
|
||||
dedupLim=0.9,
|
||||
top=15,
|
||||
lan="en")
|
||||
yake_keywords = keyword_extractor.extract_keywords(text)
|
||||
keywords = [{'value':x[0],'score':x[1]} for x in yake_keywords]
|
||||
if lang == "en" or lang == 'de':
|
||||
total_records += 1
|
||||
print("#######################################")
|
||||
|
||||
# print(record.rec_headers.get_header('WARC-Target-URI'))
|
||||
# print(text)
|
||||
|
||||
lower = text.lower()
|
||||
uri = record.rec_headers.get_header('WARC-Target-URI')
|
||||
match = re.search(regex_for_link_parts, uri)
|
||||
|
||||
uri_parts = getGroups(match)
|
||||
|
||||
|
||||
lower = lower.replace('\r', '')
|
||||
lower = lower.rstrip()
|
||||
|
||||
print("persisting...")
|
||||
|
||||
element = {}
|
||||
element['uri'] = uri
|
||||
element['protocol'] = uri_parts['protocol']
|
||||
element['subdomain'] = uri_parts['subdomain'].replace('www.','')
|
||||
element['domain'] = uri_parts['domain']
|
||||
element['port'] = uri_parts['port']
|
||||
element['path'] = uri_parts['path']
|
||||
element['query'] = uri_parts['query']
|
||||
element['title'] = title
|
||||
element['body'] = lower
|
||||
element['lang'] = lang
|
||||
element['keywords'] = keywords
|
||||
#element['year'] = int(filename[filename.find("CC-NEWS-") + 8:filename.find("CC-NEWS-") + 12])
|
||||
|
||||
json_obj = json.dumps(element)
|
||||
try:
|
||||
es.index(index=index_name,body=json_obj)
|
||||
except Exception as e:
|
||||
print("upload failed....")
|
||||
print(e)
|
||||
continue
|
||||
|
||||
else:
|
||||
print(content_type)
|
||||
print(record.content_stream().read())
|
||||
print('')
|
||||
return total_records
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
if (len(sys.argv) < 2):
|
||||
print("Usage:", sys.argv[0], "<warc dir>*")
|
||||
exit(1)
|
||||
|
||||
if check_elastic_status():
|
||||
start = time.perf_counter()
|
||||
total_records = 0
|
||||
for directory, subdirectories, files in os.walk(sys.argv[1]):
|
||||
for file in files:
|
||||
full_file_dir = os.path.join(directory, file)
|
||||
print("+++++++DIR: ", full_file_dir)
|
||||
total_records += process_file(full_file_dir,total_records)
|
||||
end = time.perf_counter()
|
||||
print(f"Total records: {total_records}, within: {end-start:0.4f} seconds.")
|
||||
|
||||
|
||||
Reference in New Issue
Block a user