File size: 12,926 Bytes
26c0bd4
 
 
 
1ba23ad
26c0bd4
 
4399cc2
26c0bd4
 
4399cc2
7e6b2aa
26c0bd4
358152e
 
 
 
 
4399cc2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26c0bd4
 
 
 
 
 
 
4399cc2
26c0bd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
415a1a3
 
 
26c0bd4
 
 
 
 
 
 
f528f56
26c0bd4
 
415a1a3
 
 
 
 
 
 
 
 
 
26c0bd4
 
 
 
 
 
f528f56
26c0bd4
 
415a1a3
26c0bd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4399cc2
26c0bd4
 
4399cc2
 
 
26c0bd4
7e6b2aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26c0bd4
 
 
 
 
7e6b2aa
 
6562ef8
358152e
 
7e6b2aa
26c0bd4
 
 
 
 
 
 
 
 
 
 
 
7e6b2aa
26c0bd4
 
7e6b2aa
26c0bd4
358152e
26c0bd4
 
 
 
 
 
 
 
 
 
358152e
26c0bd4
 
 
 
 
 
 
 
ec89685
26c0bd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f528f56
26c0bd4
 
 
 
 
 
 
 
358152e
26c0bd4
 
358152e
 
 
 
633684b
358152e
26c0bd4
1ba23ad
 
 
 
 
 
 
 
 
26c0bd4
1ba23ad
 
ec89685
1ba23ad
26c0bd4
 
 
 
4399cc2
 
 
26c0bd4
 
 
 
 
 
 
 
 
 
 
1126ea1
7b35b3b
 
 
358152e
 
26c0bd4
 
 
358152e
 
 
26c0bd4
 
 
 
 
 
 
 
 
 
 
 
1126ea1
4399cc2
26c0bd4
4399cc2
26c0bd4
 
 
358152e
 
26c0bd4
 
 
 
 
 
 
 
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import os
import argparse
from datetime import datetime
import shlex
import subprocess
import tarfile
from time import sleep
from urllib.request import urlopen, Request, ProxyHandler, build_opener
import zipfile
from bs4 import BeautifulSoup as soup
from pypdl import Pypdl
from tqdm import tqdm

is_verbose = False
def vprint(*values: object, sep: str | None = " ", end: str | None = "\n", file = None, flush: bool=False):
    if is_verbose:
        print(*values, sep=sep, end=end, file=file, flush=flush)
    

def get_url_opener():
    # Read proxy from environment variables if they exist
    http_proxy = os.getenv('HTTP_PROXY')
    https_proxy = os.getenv('HTTPS_PROXY')
    proxy_dict = {}
    if http_proxy:
        proxy_dict['http'] = http_proxy
    if https_proxy:
        proxy_dict['https'] = https_proxy
    
    # Check if any proxies were set
    if proxy_dict:
        # Create a ProxyHandler with the proxy settings
        proxy_handler = ProxyHandler(proxy_dict)
        opener = build_opener(proxy_handler)
    else:
        # Use the default opener if no proxies are set
        opener = build_opener()
    return opener

#  scrape_uspto modified from https://github.com/learningmatter-mit/PatentChem/blob/main/download.py (MIT License Copyright (c) 2022 Kevin Greenman)
def scrape_uspto(patent_year):
    # Define the USPTO web page according to the year:
    patent_url = f"https://bulkdata.uspto.gov/data/patent/grant/redbook/{patent_year}/" # xiegeo: added ending slash to avoid redirect/disconnect'
    
    print(f"Scraping {patent_url} for patent files")

    # Open a connection and download the webpage:
    uClient = get_url_opener().open(Request(patent_url))

    # Read the html of the page:
    page_html = uClient.read()

    # Close the webpage:
    uClient.close()

    # Parse the html using Beautiful Soup:
    page_soup = soup(page_html, "html.parser")

    # Get all the attributes of the page, containing the link to the weekly patent files
    patent_weekly_releases = page_soup.findAll("a")

    # Here, the link are selected from containers (ex: 'I20180102.tar').
    # They can be used to complete the url for download, e.g.
    # https://bulkdata.uspto.gov/data/patent/grant/redbook/2018/I20180102.tar
    patent_link = []
    for release in patent_weekly_releases:
        match = [s for s in release if ".tar" in s]
        matchzip = [s for s in release if ((".zip" in s) or (".ZIP" in s))]
        if match != []:
            if (match[0].endswith(".tar")
                and ("testData" not in match[0])
            ):
                patent_link.append(match)
        if matchzip != []:
            if (
                matchzip[0].lower().endswith(".zip")
                and ("SUPP" not in matchzip[0])
                and ("Grant" not in matchzip[0]) 
                and ("Red Book Viewer Public" not in matchzip[0])
                and ("Sample" not in matchzip[0])
            ):
                patent_link.append(matchzip)
                
    patent_link = [link[0] for link in patent_link] # flatten list
    # remove duplicates with _r1
    all_links = patent_link
    for link in all_links:
        #print(link)
        if "_r1" in link:
            remove = link.replace("_r1", "")
            #print(f"Removing {remove} from {all_links}")
            patent_link.remove(remove)

    print(f"Found {len(patent_link)} releases from {patent_year}")
    
    # xiegeo: added assertion to make sure we have the right weekly links
    if len(patent_link) != 52 and len(patent_link) != 53 and patent_year != str(datetime.now().year):
        print(patent_weekly_releases, patent_link)
        raise ValueError(
            f"Error: Found {len(patent_link)} releases in {patent_year}, expected 52 or 53"
        )
    patent_link = [patent_url + link for link in patent_link]
    return patent_link

# class DownloadProgressBar(tqdm):
#     # Progression bar for the download
#     def update_to(self, b=1, bsize=1, tsize=None):
#         if tsize is not None:
#             self.total = tsize
#         self.update(b * bsize - self.n)

# def download_url(url, output_path):
#     with DownloadProgressBar(unit="B", unit_scale=True, miniters=1, desc=url.split("/")[-1]) as t:
#         urllib.request.urlretrieve(url, filename=output_path, reporthook=t.update_to)
# end of copied code

def download_url(url, output_path):
    if os.path.exists(output_path) and os.path.getsize(output_path) != 0: # there is a case where the output file is created but not written to by Pypdl
        print(f"Skipping download_url {output_path}, already exists")
        return
    #wget.download(url, out=output_path)
    Pypdl().start(url=url, file_path=output_path, segments=5, retries=5, clear_terminal=False)
    

def extract_all(ref, folder_name):
    if type(ref) == str:
        file_type = ref.split(".")[1].upper()
        if file_type == "ZIP":
            with zipfile.ZipFile(ref, 'r') as zip_ref:
                extract_all(zip_ref, folder_name)
        elif file_type == "TAR":
            with tarfile.open(ref, 'r') as tar_ref:
                extract_all(tar_ref, folder_name)
        else:
            raise ValueError(f"Unsupported file {ref}")
        return
    if type(ref) == zipfile.ZipFile:
        members = ref.infolist()
    elif type(ref) == tarfile.TarFile:
        members = ref.getmembers()
    else:
        raise ValueError(f"Unsupported file type {type(ref)}")
    for member in tqdm(members, desc=f"Extracting {folder_name}", unit="file"):
        ref.extract(member, folder_name)

def extract_link(link):
    packed_file = link.split("/")[-1]
    folder_name = packed_file.split(".")[0]
    #print(f"Downloading {link}")
    download_url(link, link.split("/")[-1])
    extract_all(packed_file, folder_name)
    return folder_name
    #if os.path.exists(folder_name): # there might be partial extraction of file, use this only to speed up debugging
    #    print(f"Skipping extract_link {folder_name}, already exists")
    #    return folder_name
    file_type = ref.split(".")[1].upper()
    if file_type == "ZIP":
        with zipfile.ZipFile(packed_file, 'r') as zip_ref:
            zip_ref.extractall(folder_name)
    elif file_type == "TAR":
        with tarfile.open(packed_file, 'r') as tar_ref:
            tar_ref.extractall(folder_name)
    return folder_name

def remove_unwanted_files(root_path):
    keep_zip_count = 0
    remove_zip_count = 0
    keep_mol_count = 0
    progress_bar = tqdm(desc="Removing unwanted files", unit="file")
    for subdir, dirs, files in os.walk(root_path):
        for file in files:
            progress_bar.update(1)
            if file.upper().endswith('.ZIP'):
                vprint(f"Processing zip file: {file}")
                zip_file_path = os.path.join(subdir, file)
                found_mol_files = False
                with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
                    for zip_info in zip_ref.infolist():
                        if zip_info.filename.endswith('.MOL'):
                            found_mol_files = True
                            keep_mol_count += 1
                if found_mol_files:
                    keep_zip_count += 1
                else:
                    vprint(f"No mol files found in {zip_file_path}, delete it!")
                    remove_zip_count += 1
                    #print(zip_ref.infolist())
                    try:
                        os.remove(zip_file_path)
                    except Exception as e: 
                        print(f"Error deleting {zip_file_path}: {e}")
            else:
                print(f"unexpected file: {file}")
                sleep(10)
    return {"keep_zip_count": keep_zip_count, "keep_mol_count": keep_mol_count, "remove_zip_count": remove_zip_count}

def move_to_data(root_folder, year):
    os.makedirs(f"data/{year}", exist_ok=True)
    source_folder = root_folder
    root_basename = os.path.basename(root_folder)
    possible_inner_folder = os.path.join(root_folder, root_basename)
    if os.path.isdir(possible_inner_folder):
        source_folder = possible_inner_folder
    print(f"Moving files from {source_folder} to data/{year}/{root_basename}")
    # move all files in source_folder to data/year, keeping the same structure
    for subdir, dirs, files in os.walk(source_folder):
        if len(files) == 0:
            continue # skip empty directories
        target_subdir = subdir
        if root_folder != source_folder and subdir.startswith(source_folder):
            target_subdir = root_basename + subdir[len(source_folder):]
        os.makedirs(os.path.join("data", year, target_subdir), exist_ok=True)
        for file in files:
            vprint(f"Moving {subdir}/{file}")
            file_path = os.path.join(subdir, file)
            new_path = os.path.join("data", year, target_subdir, file)
            try:
                os.rename(file_path, new_path)
            except FileExistsError:
                print(f"File {new_path} already exists, skipping")
    return os.path.join("data", year, root_basename)
                
def run_command(cmd, retry=0):
    return_code = os.system(cmd)
    if return_code != 0:
        if retry <= 0:
            raise Exception(f"Failed to run command {cmd}, return code {return_code}")
        else:
            print(f"Retrying {cmd} in 5 seconds (retries left {retry})")
            sleep(5)
            run_command(cmd, retry=retry-1)

def check_staged_files():
    result = subprocess.run(["git", "diff", "--cached", "--name-only"], capture_output=True, text=True)
    if result.stdout.strip():
        print("There are staged files ready to be committed.")
        return True
    else:
        vprint("No staged files found.")
        return False

def add_to_git(change_message, commit_message, root_folder = "data"):
    while check_staged_files():
        print("Please commit or reset the staged files before continuing")
        sleep(10)
    run_command(f"git add {root_folder}")
    with open("DATA-CHANGELOG.md", "a") as f:
        f.write(f"## {datetime.now().astimezone().isoformat()}\n{change_message}\n")
    run_command(f"git add DATA-CHANGELOG.md")
    run_command(f"git commit -m \"{shlex.quote(commit_message)}\"")
    #return False # not pushed
    run_command("git push", retry=0)
    return True
    

def is_processed(folder_name):
    try:
        with open("DATA-CHANGELOG.md") as f:
            return folder_name in f.read()
    except FileNotFoundError:
        return False

def get_parser():
    parser = argparse.ArgumentParser(description="Downloads and filters patent files for mol files from USPTO website, then adds them to a dataset")
    parser.add_argument("--quick", action='store_true', help="only processed at most one new weekly file, you can also create a file named 'quick' (touch quick) to enable this flag during runtime to exit after finishing processing the current weekly file")
    parser.add_argument("--keep", action='store_true', help="keep the original downloaded files")
    parser.add_argument("--stream", action='store_true', help="remove all pushed lfs files and objects locally. DO NOT USE WHEN RUNNING PARALLEL SCRIPTS")
    parser.add_argument("--verbose", action='store_true', help="print verbose logs")
    parser.add_argument("--from_year", default=2001, type=int, help="start from this year (default 2001 is the earliest available)")
    parser.add_argument("--to_year", default=datetime.now().year, type=int, help="end at this year (default current year)")
    return parser

def main(args):
    global is_verbose
    is_verbose = args.verbose
    years = [str(i) for i in range(args.from_year, args.to_year + 1)]
    for year in years:
        patent_link = scrape_uspto(year)
        for link in patent_link:
            packed_file = link.split("/")[-1]
            folder_name = packed_file.split(".")[0]
            if is_processed(folder_name):
                print(f"Skipping {folder_name}, already logged in DATA-CHANGELOG.md")
                continue
            folder_name = extract_link(link)
            stats = remove_unwanted_files(folder_name)
            print(stats)
            data_location = move_to_data(folder_name, year)
            pushed = add_to_git(f'Added data from {folder_name}\n{stats}', f'Added data from {folder_name}',data_location)
            if pushed and args.stream:
                os.system(f"rm -r {data_location}")
                os.system(f"rm -r .git/lfs/objects")
            if not args.keep:
                os.system(f"rm -r {folder_name}")
                os.system(f"rm {packed_file}")
            if os.path.exists("quick"): # create this file to stop the script most gracefully
                args.quick = True
            if args.quick:
                break
        if args.quick:
            break

if __name__ == "__main__":
    args = get_parser().parse_args()
    main(args)