File size: 8,284 Bytes
40c1311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f981be
 
40c1311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f981be
 
 
40c1311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f981be
40c1311
 
 
 
 
 
 
1f981be
40c1311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f981be
40c1311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f981be
 
 
 
 
 
 
 
 
 
 
40c1311
1f981be
40c1311
 
 
 
 
 
 
 
1f981be
40c1311
 
 
 
 
 
1f981be
40c1311
 
 
 
 
 
1f981be
40c1311
 
 
 
 
 
1f981be
40c1311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f981be
40c1311
 
 
 
 
 
 
1f981be
40c1311
 
 
1f981be
40c1311
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f981be
40c1311
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
"""
Cellar text and eurovoc extraction

	python update.py 10000 dataset.jsonl

will extract for the last 10,000 days text in english and eurovoc labels in the JSON line file.


requirements:
beautifulsoup4==4.12.2
docx2txt==0.8
ipython==8.14.0
jinja2==3.1.2
joblib==1.3.1
pdfminer.six==20221105
pip-chill==1.0.3
pycryptodome==3.18.0
requests==2.31.0
tqdm==4.65.0
xmltodict==0.13.0
"""
import datetime
import json
from concurrent.futures import ProcessPoolExecutor

from bs4 import BeautifulSoup
import logging
import re
import sys

from tqdm import tqdm
from io import BytesIO
import jinja2
from joblib import Memory

location = './cache'
memory = Memory(location, verbose=0)

log = logging.getLogger(__name__)
log.addHandler(logging.FileHandler('collect.log'))
log.setLevel(logging.DEBUG)

import xmltodict

import docx2txt as docx2txt
import requests
from joblib import expires_after
from pdfminer.high_level import extract_text

user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36'


def clean_text(func):
    """
    Decorator used to clean the text
    :param func:
    :return:
    """

    def inner(*args, **kwargs):
        text = func(*args, **kwargs)
        text = text.replace("\n", " ")
        text = text.replace(" .", ".")
        text = re.sub(' +', ' ', text)
        text = re.sub(' *[.] *', '. ', text)
        text = re.sub('\.\s*\.\s*\.+', '. ', text)
        text = '. '.join([s.strip() for s in text.split(".") if len(s.strip())])
        return text

    return inner


@memory.cache(cache_validation_callback=expires_after(minutes=120))
def get_eurovoc_terms_and_id():
    eurovoc_terms_and_id = {}
    response = requests.get('http://publications.europa.eu/resource/dataset/eurovoc',
                            headers={'Accept': 'application/xml',
                                     'Accept-Language': 'en',
                                     'User-Agent': user_agent
                                     }
                            )
    data = xmltodict.parse(response.content)
    for term in data['xs:schema']['xs:simpleType']['xs:restriction']['xs:enumeration']:
        try:
            name = term['xs:annotation']['xs:documentation'].split('/')[0].strip()
            for r in term['xs:annotation']['xs:appinfo']['record']:
                if r['@thesaurus_id'] != '':
                    eurovoc_terms_and_id[name.lower()] = r['@thesaurus_id']
        except KeyError as e:
            log.warning("⚠️ Could not parse", term)
    return eurovoc_terms_and_id


def get_sparql_query(d):
    start = d.strftime('%Y-%m-%d')
    end = d + datetime.timedelta(days=2)
    end = end.strftime('%Y-%m-%d')
    environment = jinja2.Environment()
    template = environment.from_string(open("query.j2", 'r').read())
    return template.render(start=start, end=end)


def get_json_response(d):
    url = "https://publications.europa.eu/webapi/rdf/sparql"
    headers = {'User-Agent': user_agent}
    params = {"default-graph-uri": "",
              "query": get_sparql_query(d),
              "format": "application/sparql-results+json",
              "timeout": "0",
              "debug": "on",
              "run": "Run Query"}

    response = requests.get(url, headers=headers, params=params)
    assert response.status_code == 200
    return response.json()


def get_concepts_id(list_of_eurovoc_terms):
    terms = get_eurovoc_terms_and_id()
    for e in list_of_eurovoc_terms:
        try:
            yield terms[e.strip().lower()]
        except KeyError:
            log.warning(f"⚠️ Could not find {e} in Eurovoc")


def get_docs(d):
    results = get_json_response(d)
    for r in results['results']['bindings']:
        terms = r['subjects']['value'].replace(u'\xa0', u' ').split(',')
        r['eurovoc_concepts'] = terms  # list(get_concepts_id(terms))
        r['url'] = r['cellarURIs']['value']
        r['title'] = r['title']['value']
        r['date'] = r['date']['value']
        r['lang'] = r['langIdentifier']['value'].lower()
        r['formats'] = [t for t in r['mtypes']['value'].split(',')]
        for c in ['cellarURIs', 'mtypes', 'langIdentifier', 'subjects', 'authors', 'workTypes', 'workIds']:
            del r[c]
        yield r


def get_docs_text(d):
    docs = list(get_docs(d))
    print(f"Processing documents ... {len(docs)}")
    with ProcessPoolExecutor(max_workers=16) as executor:
        for v in tqdm(executor.map(get_body, docs), total=len(docs), colour='green'):
            yield v


def get_body(r):
    try:
        if 'pdf' in r['formats']:
            r['text'] = get_pdf_body(r)
        elif 'docx' in r['formats']:
            r['text'] = get_docx_body(r)
        elif 'doc' in r['formats']:
            r['text'] = get_doc_body(r)
        elif 'xhtml' in r['formats']:
            r['text'] = get_xhtml_body(r)
        else:
            log.warning(f"⚠️ Could not find a parser for {r['formats']}")
        return r
    except Exception as e:
        log.error(str(e) + str(r))


@clean_text
@memory.cache()
def get_pdf_body(r):
    url = r['url']
    language = r['lang']
    accept = 'application/pdf'
    response = requests.get(url, headers={'Accept': accept, 'Accept-Language': language, 'User-Agent': user_agent})
    if response.status_code == 300:
        return " ".join(_multiple_choice(get_pdf_body, response, accept, language))
    elif response.status_code == 200:
        mem = BytesIO(response.content)
        return extract_text(mem)


@clean_text
@memory.cache()
def get_xhtml_body(r):
    url = r['url']
    language = r['lang']
    accept = 'application/xhtml+xml'
    response = requests.get(url, headers={'Accept': accept, 'Accept-Language': language, 'User-Agent': user_agent})
    if response.status_code == 300:
        return " ".join(_multiple_choice(get_xhtml_body, response, accept, language))
    elif response.status_code == 200:
        soup = BeautifulSoup(response.content, 'html.parser')
        return soup.get_text()


def get_docx_body(r):
    accept = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml'
    url = r['url']
    lang = r['lang']
    try:
        return _get_doc_body(url, accept, lang)
    except AssertionError as e:
        log.warning(f"⚠️ Could not download {url} {e}")
        print(f"⚠️ Could not download {r} --- {accept} {e}")
        return ""


def get_doc_body(r):
    accept = 'application/msword'
    url = r['url']
    lang = r['lang']
    try:
        return _get_doc_body(url, accept, lang)
    except AssertionError as e:
        log.warning(f"⚠️ Could not download {url} {e}")
        print(f"⚠️ Could not download {r} --- {accept} {e}")
        return ""


def _multiple_choice(func, response, accept, language):
    soup = BeautifulSoup(response.text, 'html.parser')
    for link in soup.find_all('a'):
        if 'href' in link.attrs:
            url = link.attrs['href']
            yield func(url, accept, language)


@clean_text
@memory.cache()
def _get_doc_body(url, accept, language='en'):
    response = requests.get(url, headers={'Accept': accept, 'Accept-Language': language, 'User-Agent': user_agent})
    if response.status_code == 300:
        return " ".join(_multiple_choice(_get_doc_body, response, accept, language))
    elif response.status_code == 200:
        mem = BytesIO(response.content)
        log.info(f"📄 MS Word doc download and parsed {url}")
        return docx2txt.process(mem)
    else:
        raise AssertionError(f"📄 MS Word doc download failed {url} {response.status_code} {response.content}")


if __name__ == '__main__':
    output = sys.argv[1]
    max = int(sys.argv[2])
    ofiles = {}
    for i in range(max):
        d = datetime.date.today() - datetime.timedelta(days=i)
        print(d)
        ym = d.strftime('%Y-%m')
        if ym not in ofiles:
            ofiles[ym] = open(output + ym + '.jsonl', 'w')
        try:
            for d in get_docs_text(d):
                ofiles[ym].write(json.dumps(d) + '\n')
                ofiles[ym].flush()
        except Exception as e:
            log.error('Day ' + str(d) + ' ' + str(e))
            print('Day ' + str(d) + ' ' + str(e))
    for f in ofiles.values():
        f.close()