File size: 2,284 Bytes
65f4385
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gzip
import sys
import os
import tqdm
import requests
import json

import fasttext
fasttext.FastText.eprint = lambda x: None   #Silence useless warning: https://github.com/facebookresearch/fastText/issues/1067

def http_get(url, path):
    """

    Downloads a URL to a given path on disc

    """
    if os.path.dirname(path) != '':
        os.makedirs(os.path.dirname(path), exist_ok=True)

    req = requests.get(url, stream=True)
    if req.status_code != 200:
        print("Exception when trying to download {}. Response {}".format(url, req.status_code), file=sys.stderr)
        req.raise_for_status()
        return

    download_filepath = path+"_part"
    with open(download_filepath, "wb") as file_binary:
        content_length = req.headers.get('Content-Length')
        total = int(content_length) if content_length is not None else None
        progress = tqdm.tqdm(unit="B", total=total, unit_scale=True)
        for chunk in req.iter_content(chunk_size=1024):
            if chunk: # filter out keep-alive new chunks
                progress.update(len(chunk))
                file_binary.write(chunk)

    os.rename(download_filepath, path)
    progress.close()


model_path = 'lid.176.bin'
if not os.path.exists(model_path):
    http_get('https://dl.fbaipublicfiles.com/fasttext/supervised-models/'+model_path, model_path)
global_fasttext_lang_id = fasttext.load_model(model_path)

def lang_detect(text: str) -> str:
    return global_fasttext_lang_id.predict(text.lower().replace("\r\n", " ").replace("\n", " ").strip())[0][0].split('__')[-1]

filepaths = sorted(sys.argv[1:])

output_folder = "question_best_answer_lang"
output_files = {}

try:
    for filepath in filepaths:
        with gzip.open(filepath, 'rt') as fIn:
            for line in tqdm.tqdm(fIn, desc=filepath):
                data = json.loads(line)
                text = data['title']+" "+data['body']
                lang = lang_detect(text)

                if lang not in output_files:
                    output_files[lang] = gzip.open(f"{output_folder}/{lang}.jsonl.gz", "wt")
                
                output_files[lang].write(line)
finally:
    for outfile in output_files.values():
        outfile.close()