How to Autostart Apps on Your Server

[TOC] Title: How to Autostart Apps on Your Server Review Date: Fri, Apr 12, 2024 url: - How to Autostart Apps on Your Server we can try systemd --user modules First of all, write the service in the ~/.config/systemd/user/ folder 1 2 3 4 5 6 7 8 9 10 11 12 [Unit] Description=My TorchSErve Server Wants=network-online.target After=network-online.target [Service] Type=forking ExecStart=/datadrive/run_torchserve.sh [Install] WantedBy=multi-user.target Note that Type=forking is important if you want to maintain the session, especially when you want to maintain a tmux ...

<span title='2024-04-12 12:23:29 +1000 AEST'>April 12, 2024</span>&nbsp;·&nbsp;6 min&nbsp;·&nbsp;1109 words&nbsp;·&nbsp;Sukai Huang

Using Kedro And Optuna for Your Project

[TOC] Title: Using Kedro And Optuna for Your Project Review Date: Wed, Mar 27, 2024 url: https://neptune.ai/blog/kedro-pipelines-with-optuna-hyperparameter-sweeps Use Kedro and Optuan for your ML project Kedro - manage the ML pipeline Optuna - hyperparameter tuning tool Example pyproject.toml 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 [build-system] requires = [ "setuptools",] build-backend = "setuptools.build_meta" [project] name = "kedro_hyperparameter_sweep_test" authors = [ {name = "Sukai Huang", email = "hsk6808065@163.com"} ] readme = "README.md" dynamic = [ "dependencies", "version",] [project.scripts] kedro-hyperparameter-sweep-test = "kedro_hyperparameter_sweep_test.__main__:main" [project.optional-dependencies] docs = [ "docutils<0.18.0", "sphinx~=3.4.3", "sphinx_rtd_theme==0.5.1", "nbsphinx==0.8.1", "sphinx-autodoc-typehints==1.11.1", "sphinx_copybutton==0.3.1", "ipykernel>=5.3, <7.0", "Jinja2<3.1.0", "myst-parser~=0.17.2",] [tool.kedro] package_name = "kedro_hyperparameter_sweep_test" project_name = "kedro_hyperparameter_sweep_test" kedro_init_version = "0.19.3" tools = [ "Linting", "Custom Logging", "Documentation", "Data Structure", "Kedro Viz",] example_pipeline = "False" source_dir = "src" [tool.ruff] line-length = 88 show-fixes = true select = [ "F", "W", "E", "I", "UP", "PL", "T201",] ignore = [ "E501",] [project.entry-points."kedro.hooks"] [tool.ruff.format] docstring-code-format = true [tool.setuptools.dynamic.dependencies] file = "requirements.txt" [tool.setuptools.dynamic.version] attr = "kedro_hyperparameter_sweep_test.__version__" [tool.setuptools.packages.find] where = [ "src",] namespaces = false [tool.setuptools.package-data] kedro_hyperparameter_sweep_test = ["*.csv", "*.md", "*.log"] The default Kedro project structure is as follows: 1 2 3 4 5 6 7 8 9 project-dir # Parent directory of the template ├── .gitignore # Hidden file that prevents staging of unnecessary files to `git` ├── conf # Project configuration files ├── data # Local project data (not committed to version control) ├── docs # Project documentation ├── notebooks # Project-related Jupyter notebooks (can be used for experimental code before moving the code to src) ├── pyproject.toml # Identifies the project root and contains configuration information ├── README.md # Project README └── src # Project source code Use Jupyter lab ref: https://docs.kedro.org/en/stable/notebooks_and_ipython/kedro_and_notebooks.html ...

<span title='2024-03-27 21:50:10 +1100 AEDT'>March 27, 2024</span>&nbsp;·&nbsp;4 min&nbsp;·&nbsp;641 words&nbsp;·&nbsp;Sukai Huang

How to Design Your Research Project Structure

[TOC] Title: How to Design Your Research Project Structure Review Date: Fri, Feb 2, 2024 Basic Component Policy model Environment Reward model Evaluation Logging and Result Postprocess Training train reward train policy Dataloader Utils Logging Setup Multiprocessing Helper etc it’s better to have interface class in the __init__.py Separate subproject for Data collection and PreTraining Environment simulation running how to save label, how to save images, align with the requirement of dali. how to generate tasks, how to generate text Pretrained CLIP/XLIP model Dataloader Model Finetuning reward model Training Evaluation Dataloader How to git ignore data above 1M Open your terminal. Use the find command to list all files over 1M in size in your repository directory and append them to .gitignore: 1 find . -size +1M | sed 's|^\./||' >> .gitignore This command works as follows: ...

<span title='2024-02-02 19:50:31 +1100 AEDT'>February 2, 2024</span>&nbsp;·&nbsp;2 min&nbsp;·&nbsp;237 words&nbsp;·&nbsp;Sukai Huang

React Js Development 2024

[TOC] Title: React Js Development 2024 Review Date: Sun, Jan 21, 2024 url: React JS development (Typescript + Vite + React) VSC extension ES7 + React NPM support for VS Coe Vite JavaScript and TypeScript Init 1 2 3 4 5 6 7 8 9 10 11 curl -fsSL https://deb.nodesource.com/setup_21.x | sudo -E bash - &&\ sudo apt-get install -y nodejs npm create vite@latest npm create vite@latest yourapp -- --template react-ts cd yourapp npm install npm install antd react-redux react-router-dom redux sass reset-css # can also add them to package npm i -D @types/node npm run dev add path hint in tsconfig add resolve alias @ in vite.config.ts Things to remember how to import module rather than global import think about what you want to show, layout and data think about nested route think about how to CURD with database

<span title='2024-01-21 17:40:43 +1100 AEDT'>January 21, 2024</span>&nbsp;·&nbsp;1 min&nbsp;·&nbsp;140 words&nbsp;·&nbsp;Sukai Huang

Python and Os Utils 2024

[TOC] Title: Python and Os Utils 2024 Review Date: Thu, Jan 18, 2024 Useful Programming Tips What does " 2>&1 " mean? To combine stderr and stdout into the stdout stream, we append this to a command: 1 2>&1 Answer File descriptor 1 is the standard output (stdout). File descriptor 2 is the standard error (stderr). At first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as “redirect stderr to a file named 1”. ...

<span title='2024-01-18 18:51:51 +1100 AEDT'>January 18, 2024</span>&nbsp;·&nbsp;2 min&nbsp;·&nbsp;325 words&nbsp;·&nbsp;Sukai Huang

Python Logger

[TOC] Title: Python Logger Review Date: Mon, Dec 4, 2023 Python Logger python logging library is a good way to logging the progress Common use case 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # console handler stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.DEBUG) stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) # file handler logging_folder = Path(yourfolder) logging_fp = os.path.join(logging_folder, "your_logging_fp") # unlink previous one Path(logging_fp).unlink(missing_ok=True) file_handler = logging.FileHandler(logging_fp) file_handler.setLevel(logging.INFO) file_handler.setFormatter(formatter) logger.addHandler(file_handler) logger.removeHandler(file_handler) Common setupLogger function, tqdm logger, json formatter 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 import json import logging from logging.handlers import RotatingFileHandler from logging import FileHandler from tqdm.auto import tqdm import multiprocessing as mp from pythonjsonlogger import jsonlogger import atexit import os from utils import convert_partial_to_json def setupLogger(loggername, loggingfile = None, logginglevel = logging.INFO, loggingqueue = None, file_handler_class=FileHandler, if_json=False): """ Set up a logger with the specified name and optional logging file. Parameters: loggername (str): The name of the logger. loggingfile (str): The path to the logging file (optional). Returns: logging.Logger: The configured logger. """ if loggername not in logging.Logger.manager.loggerDict: # Create a logger in the main process logger = logging.getLogger(loggername) logger.setLevel(logginglevel) streamhandler = logging.StreamHandler() if loggingfile is not None: if if_json: loggingfile = loggingfile.replace('.log', '.json') loggingfile = loggingfile + ".partial" # register itexit atexit.register(convert_partial_to_json, loggingfile) if file_handler_class == FileHandler: filehandler = FileHandler(loggingfile, delay=True) elif file_handler_class == RotatingFileHandler: filehandler = RotatingFileHandler(loggingfile, maxBytes=1000000, backupCount=3, delay=True) else: raise ValueError(f"Unknown file_handler_class {file_handler_class}") processname = mp.current_process().name if processname == 'MainProcess': # clear the log file with open(loggingfile, 'w'): pass formatter = logging.Formatter('%(asctime)s [%(processName)s] [%(levelname)s] %(message)s') streamhandler.setFormatter(formatter) if if_json: jsonformatter = jsonlogger.JsonFormatter('%(asctime)s [%(processName)s] [%(levelname)s] %(message)s') filehandler.setFormatter(jsonformatter) else: filehandler.setFormatter(formatter) logger.addHandler(streamhandler) if loggingfile is not None: logger.addHandler(filehandler) if loggingqueue is not None: queuehandler = logging.handlers.QueueHandler(loggingqueue) logger.addHandler(queuehandler) return logger else: return logging.getLogger(loggername) class logging_tqdm(tqdm): def __init__( self, *args, loggername="logging_tqdm_logger", loggingfile = None, logginglevel = logging.INFO, loggingqueue = None, mininterval: float = 1, bar_format: str = '{desc}{percentage:3.0f}%{r_bar}', desc: str = 'progress: ', **kwargs): self._loggername = loggername self._loggingfile = loggingfile self._logginglevel = logginglevel self._loggingqueue = loggingqueue self._logger = setupLogger(loggername, loggingfile, logginglevel, loggingqueue) super().__init__( *args, mininterval=mininterval, bar_format=bar_format, desc=desc, **kwargs ) @property def logger(self): if self._logger is not None: return self._logger return setupLogger(self._loggername, self._loggingfile, self._logginglevel, self._loggingqueue) def display(self, msg=None, pos=None): if not self.n: # skip progress bar before having processed anything return if not msg: msg = self.__str__() self.logger.info(f'%s', msg)

<span title='2023-12-04 20:25:12 +1100 AEDT'>December 4, 2023</span>&nbsp;·&nbsp;3 min&nbsp;·&nbsp;496 words&nbsp;·&nbsp;Sukai Huang

Langchain Use Cases 2023

[TOC] Title: Langchain Use Cases 2023 Review Date: Sat, Aug 26, 2023 url: https://python.langchain.com/docs/get_started/quickstart Langchain quickstart The core building block of LangChain applications is the LLMChain. This combines three things: LLM: The language model is the core reasoning engine here. In order to work with LangChain, you need to understand the different types of language models and how to work with them. Prompt Templates: This provides instructions to the language model. This controls what the language model outputs, so understanding how to construct prompts and different prompting strategies is crucial. Output Parsers: These translate the raw response from the LLM to a more workable format, making it easy to use the output downstream. PromptTemplate modify prompt format easily Chains: Combine LLMs and prompts in multi-step workflows 1 2 from langchain.chains import LLMChain chain = LLMChain(llm=llm, prompt=prompt) Agents: dynamically call chains based on user input 1 2 3 from langchain.agents import load_tools from langchain.agents import initialize_agent from langchain.llms import OpenAI we can connect Google AI with ChatGPT ...

<span title='2023-08-26 17:36:47 +1000 AEST'>August 26, 2023</span>&nbsp;·&nbsp;4 min&nbsp;·&nbsp;700 words&nbsp;·&nbsp;Sukai Huang

Pytorch Multiprocessing 2023

[TOC] Title: Pytorch Multiprocessing 2023 Review Date: Tue, Jul 18, 2023 url: https://pytorch.org/docs/stable/multiprocessing.html Best Practices for Pytorch multiprocessing 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 from torch import multiprocessing from torch.multiprocessing import Pipe multiprocessing.set_start_method('spawn') # for torch multiprocessing, spawn method is required model = Model() model.share_memory() p_conn, c_conn = Pipe() tensor_1 = torch.tensor([1]) tensor_1.share_memory() # need to pass tensor to shared memeory p_conn.send(tensor_1) # the receiver end tensor_1_sub = c_conn.receive() # after using it del tensor_1_sub # safe del

<span title='2023-07-18 16:48:13 +1000 AEST'>July 18, 2023</span>&nbsp;·&nbsp;1 min&nbsp;·&nbsp;93 words&nbsp;·&nbsp;Sukai Huang

Remote Server, Tmux and Joshuto 2023

[TOC] Title: Remote Server and Tmux 2023 Review Date: Sun, Jul 16, 2023 url: https://tmuxcheatsheet.com/ url: https://explainshell.com When you want to have a long-run Jupyter notebook when you ssh to a remote server and have a long-run program (e.g., using jupyter notebook for training deep learning models ) you need to detach your job to background otherwise the program will stop when you exit ssh. you need tmux some useful tmux shortcut 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 tmux new -s <yourname> # start a new session with the name <yourname> tmux kill-session -t <sname> # kill session with name <sname> tmux ls # list all sessions tmux a # attach the last session tmux a -t <sname> # attach the session with name <sname> # in the tmux ctrl + b + $ # rename the session name ctrl + b + d # detach session ctrl + b + w # list windows ctrl + b + c # new window ctrl + b + % # split a new pane # panes ctrl + b + [ # scroll mode ctrl + b + arrow # switch pane focus ctrl + b + x # close pane tqdm to file for long-run jobs when you want to have a long-run jupyter and you cannot directly use tqdm to monitor. Every time you want to reconnect to the jupyter kernel, the tqdm progress bar will be cleared. to solve this, you need to store it to file also for long-run jobs, always save your data regularly 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 # example from tqdm import tqdm a_dict = dict() save_interval = 20000 a_dict_count = len(a_dict) with open('preprocess_log.txt', 'w') as log_f: for key, val in tqdm(b_dict.items(), file=log_f, mininterval=3): # temp save if len(a_dict) % save_interval == 0: with open('a_dict.pkl', 'wb') as save_f: pickle.dump(a_dict, save_f) if key not in a_dict: a_dict[key] = extract_info(val) assert len(a_dict) == a_dict_count + 1 a_dict_count = len(a_dict) Joshuto - advanced terminal file manager you want a good file manager when you are in cli, joshuto is what you want. https://github.com/kamiyaa/joshuto ...

<span title='2023-07-16 18:45:57 +1000 AEST'>July 16, 2023</span>&nbsp;·&nbsp;3 min&nbsp;·&nbsp;557 words&nbsp;·&nbsp;Sukai Huang

Undetected Chromedriver Use Case

[TOC] Parsing a Property website in multiprocessing way 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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 # %% import sqlite3 from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException, NoSuchElementException import logging from pathlib import Path from tqdm.auto import tqdm import os import pickle import csv import time import threading from glob import glob import argparse import random # %% [markdown] # ## Multiprocessing version # %% from tqdm.contrib.concurrent import process_map, thread_map from multiprocessing import Pool, Process, Manager, Lock import multiprocessing as mp from multiprocessing.dummy import Pool as DummyPool from webdriver_manager.chrome import ChromeDriverManager from logging.handlers import RotatingFileHandler HEADLESS = False VERSION = 120 PROCESS_NUM = 4 CHUNK_SIZE = 300 IMPLICIT_WAIT_TIME = 5 def setupLogger(loggername, loggingfile = None, logginglevel = logging.INFO, loggingqueue = None): """ Set up a logger with the specified name and optional logging file. Parameters: loggername (str): The name of the logger. loggingfile (str): The path to the logging file (optional). Returns: logging.Logger: The configured logger. """ if loggername not in logging.Logger.manager.loggerDict: # Create a logger in the main process logger = logging.getLogger(loggername) logger.setLevel(logginglevel) handler = logging.StreamHandler() if loggingfile is not None: filehandler = RotatingFileHandler(loggingfile, maxBytes=1000000, backupCount=3, delay=True) processname = mp.current_process().name if processname == 'MainProcess': # clear the log file with open(loggingfile, 'w'): pass formatter = logging.Formatter('%(asctime)s [%(processName)s] [%(levelname)s] %(message)s') handler.setFormatter(formatter) filehandler.setFormatter(formatter) if loggingqueue is not None: queuehandler = logging.handlers.QueueHandler(loggingqueue) logger.addHandler(queuehandler) logger.addHandler(handler) if loggingfile is not None: logger.addHandler(filehandler) return logger else: return logging.getLogger(loggername) class logging_tqdm(tqdm): def __init__( self, *args, loggername="logging_tqdm_logger", loggingfile = None, logginglevel = logging.INFO, loggingqueue = None, mininterval: float = 1, bar_format: str = '{desc}{percentage:3.0f}%{r_bar}', desc: str = 'progress: ', **kwargs): self._loggername = loggername self._loggingfile = loggingfile self._logginglevel = logginglevel self._loggingqueue = loggingqueue self._logger = setupLogger(loggername, loggingfile, logginglevel, loggingqueue) super().__init__( *args, mininterval=mininterval, bar_format=bar_format, desc=desc, **kwargs ) @property def logger(self): if self._logger is not None: return self._logger return setupLogger(self._loggername, self._loggingfile, self._logginglevel, self._loggingqueue) def display(self, msg=None, pos=None): if not self.n: # skip progress bar before having processed anything return if not msg: msg = self.__str__() self.logger.info(f'%s', msg) def sleepy_find_element(browser, by_query_list, attempt_count :int =30, sleep_duration =0.3): ''' Finds the web element using the locator and query. This function attempts to find the element multiple times with a specified sleep duration between attempts. If the element is found, the function returns the element. Args: by (selenium.webdriver.common.by.By): The method used to locate the element. query (str): The query string to locate the element. attempt_count (int, optional): The number of attempts to find the element. Default: 20. sleep_duration (int, optional): The duration to sleep between attempts. Default: 1. Returns: selenium.webdriver.remote.webelement.WebElement: Web element or None if not found. ''' if not isinstance(by_query_list[0], (list, tuple)): by_query_list = [by_query_list] item = [] browser.implicitly_wait(0.3) for _count in range(attempt_count): for (by, query) in by_query_list: item = browser.find_elements(by, query) if len(item) > 0: item = item[0] # logging.info(f'Element {query} has found') break if item == []: # logging.info(f'Element {query} is not present, attempt: {_count+1}') time.sleep(sleep_duration) else: break if item is list: logging.warning("Element not find!") browser.implicitly_wait(IMPLICIT_WAIT_TIME) return item def collect_data_multiprocessing(postcode_chunk, chromelock,nodatalock,savedpstcdlock,loggingqueue, chrome_profile_path_lst, loggername, loggingfile, data_index ): import undetected_chromedriver as uc # local import due to memory leak # setuplogger logger = setupLogger(loggername, loggingfile, loggingqueue=loggingqueue) saved_postcode_lst = [] no_data_lst = [] # variables website_url = "https://propertydata.co.uk/internal-area-lookup" website_login_url = "https://propertydata.co.uk/login" postcode_input_xp = '//input[contains(@name, "postcode")]' submit_but_xp = '//input[contains(@name, "postcode")]/../following-sibling::label/input[contains(@type, "submit")]' back_but_xp = '//a[contains(.,"Look up another postcode")]' not_found_xp = '//p[contains(., "No energy performance")]' not_found_xp_2 = '//p[contains(., "enter a valid")]' anchor_td_xp = '//td[contains(., "Inspection date")]' data_tr_xp = anchor_td_xp + '/../../tr' # init browser with chromelock: chrome_profile_path = chrome_profile_path_lst.pop() logger.info(f"Chrome profile path: {chrome_profile_path}") # todo options = uc.ChromeOptions() options.page_load_strategy = 'eager' # options.add_argument("--auto-open-devtools-for-tabs") # help to avoid cloudfare human verify check options.add_argument("--disable-popup-blocking") options.add_argument("--window-size=800,600") # options.add_argument("--start-maximized") # options.add_argument('--disable-gpu') options.add_argument("--no-sandbox") options.add_argument("--disable-setuid-sandbox") options.add_argument("--disable-extensions") options.add_argument('--disable-application-cache') options.add_argument("--disable-dev-shm-usage") if HEADLESS: options.add_argument("--headless=new") driver = None # get process name thread_name = mp.current_process().name def init_and_login_localf(): driver.get("https://www.google.com/") time.sleep(1) driver.get(website_url) time.sleep(1) acc_eles = sleepy_find_element(driver, (By.XPATH, '//a[@href ="/account"]')) if acc_eles == []: logger.warning("Try to ReLogin") try: driver.get(website_login_url) except TimeoutException as e: logger.error(f"{e}") logger.error("Cannot Open Login Page!!!!") raise e address_ele = sleepy_find_element(driver, [By.XPATH, '//input[contains(@name, "email")]']) address_ele.click() time.sleep(1) time.sleep(1) passwd_ele = sleepy_find_element(driver, [By.XPATH, '//input[contains(@name, "password")]']) passwd_ele.click() time.sleep(1) time.sleep(1) remember_me_ele = sleepy_find_element(driver, [By.XPATH, '//input[contains(@name, "remember")]']) remember_me_ele.click() submit_ele = sleepy_find_element(driver, [By.XPATH, '//input[contains(@type, "submit")]']) submit_ele.click() WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//a[@href ="/account"]'))) driver.get(website_url) WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, '//a[@href ="/account"]'))) try: # check os system if os.name == "posix": time.sleep(0.3) # wait for chrome profile to be ready driver = uc.Chrome(options=options, driver_executable_path=ChromeDriverManager().install(), user_data_dir=chrome_profile_path, # version_main=VERSION, user_multi_procs=True) elif os.name == "nt": time.sleep(0.3) # wait for chrome profile to be ready # options.add_argument(f"--user-data-dir={chrome_profile_path}") driver = uc.Chrome(options=options, driver_executable_path=ChromeDriverManager().install(), # driver_executable_path=os.path.join(os.path.abspath(os.getcwd()), 'chromedriver-win64/chromedriver-win64/chromedriver.exe'), user_multi_procs=True, ) else: raise Exception("Unknown OS") driver.implicitly_wait(IMPLICIT_WAIT_TIME) the_id_num = int(chrome_profile_path.split("_")[-1]) if the_id_num == 0: x_offset = 0 y_offset = 0 elif the_id_num == 1: x_offset = 750 y_offset = 0 elif the_id_num == 2: x_offset = 0 y_offset = 450 elif the_id_num == 3: x_offset = 750 y_offset = 450 else: x_offset = 0 y_offset = 0 driver.set_window_size(900, 700, windowHandle ='current') time.sleep(1.5) driver.set_window_position(random.randint(40,80) + x_offset, random.randint(40,80) + y_offset, windowHandle ='current') time.sleep(2.5) init_and_login_localf() # loop for ind in tqdm(range(len(postcode_chunk)), desc="Working in "+thread_name): cur_postcode_name = postcode_chunk[ind] try: try_limit = 3 try_count = 0 while try_count < try_limit: # load loopup result time.sleep(0.3) postcode_input_ele = sleepy_find_element(driver, [By.XPATH, postcode_input_xp]) submit_but_ele = sleepy_find_element(driver, [By.XPATH, submit_but_xp]) time.sleep(0.2) postcode_input_ele.click() postcode_input_ele.send_keys(cur_postcode_name) time.sleep(1) submit_but_ele.click() # collect data # ancor_or_not_found_ele = WebDriverWait(driver, 30).until(EC.any_of( # EC.presence_of_element_located((By.XPATH, not_found_xp)), # EC.presence_of_element_located((By.XPATH, not_found_xp_2)), # EC.presence_of_element_located((By.XPATH, anchor_td_xp)) # )) time.sleep(0.4) ancor_or_not_found_ele = sleepy_find_element(driver, [(By.XPATH, anchor_td_xp),(By.XPATH, not_found_xp), (By.XPATH, not_found_xp_2), (By.XPATH, submit_but_xp) ], 20) if ancor_or_not_found_ele == []: try_count += 1 continue if ancor_or_not_found_ele.tag_name == 'input': try_count += 1 continue break ancor_or_not_found_ele = sleepy_find_element(driver, [(By.XPATH, anchor_td_xp),(By.XPATH, not_found_xp), (By.XPATH, not_found_xp_2), ], 20) if ancor_or_not_found_ele == []: raise TimeoutException # check if no data elif ancor_or_not_found_ele.tag_name == 'p': no_data_lst.append(cur_postcode_name) if len(no_data_lst) > 0: # save to file with nodatalock: with open('./running_input/postcode_no_data_lst.txt', 'a') as f: for pcl in no_data_lst: f.write(str(pcl)+"\n") no_data_lst[:] = [] # manager list remove all init_and_login_localf() continue time.sleep(random.randint(4,8)) # data_tr_eles = WebDriverWait(driver, 2).until( # EC.presence_of_all_elements_located((By.XPATH, data_tr_xp))) data_tr_eles = driver.find_elements(By.XPATH, data_tr_xp) data_tr_eles = data_tr_eles[1:] # remove first row except (NoSuchElementException, TimeoutException) as e: # try to skip cloudflare # driver.execute_script('''window.open("http://nowsecure.nl","_blank");''') # open page in new tab try: sleeptimeforcd = 30 logger.warning(f"Blocked by {type(e)}, Try to Sleep {sleeptimeforcd}s.") WebDriverWait(driver, sleeptimeforcd).until(EC.presence_of_element_located((By.XPATH, '//a[@href ="/account"]'))) except TimeoutException: init_and_login_localf() continue row_total_lst = [] for temp_data_tr_ele in data_tr_eles: all_eles = temp_data_tr_ele.find_elements(By.XPATH, "./td") if len(all_eles) != 6: continue inspection_date = all_eles[0].text address = all_eles[1].text floor_area = all_eles[2].text habitable_room = all_eles[3].text energyrate = all_eles[4].text energyrate_val = all_eles[5].text irow = [inspection_date, address, floor_area, habitable_room, energyrate, energyrate_val, cur_postcode_name] row_total_lst.append(irow) # save to file # with open("./postcode_lookup_info.csv", 'a') as f: # wt = csv.writer(f) # wt.writerows(row_total_lst) # we need database conn = sqlite3.connect(f'./running_output/postcode_lookup_info.db') curser = conn.cursor() with conn: sql_create_table = f""" CREATE TABLE IF NOT EXISTS postcode_info_data_table_{data_index} ( inspection_date TEXT, address TEXT UNIQUE, floor_area TEXT, habitable_room TEXT, energyrate TEXT, energyrate_val TEXT, postcode TEXT, PRIMARY KEY(address) ) WITHOUT ROWID; """ curser.execute(sql_create_table) curser.executemany(f"INSERT OR REPLACE INTO postcode_info_data_table_{data_index} (inspection_date, address, floor_area, habitable_room, energyrate, energyrate_val, postcode) VALUES (?,?,?,?,?,?,?)", row_total_lst) conn.close() # add row to saved_postcode_lst saved_postcode_lst.append(cur_postcode_name) if len(saved_postcode_lst) > CHUNK_SIZE // 10: # save to file immediately with savedpstcdlock: with open('./running_input/postcode_alr_saved_lst.txt', 'a') as f: for pcl in saved_postcode_lst: f.write(str(pcl)+"\n") saved_postcode_lst[:] = [] # manager list remove all # backto search bar back_but_ele = sleepy_find_element(driver, [By.XPATH, back_but_xp]) back_but_ele.click() except Exception as e: logger.error(f"Unsovable Error: {e}") if driver is not None: driver.close() time.sleep(0.2) driver.quit() time.sleep(0.2) driver = None finally: with chromelock: chrome_profile_path_lst.append(chrome_profile_path) # return profile path to list time.sleep(3) if driver is not None: driver.close() time.sleep(2) driver.quit() time.sleep(2) driver = None if len(saved_postcode_lst) > 0: with savedpstcdlock: with open('./running_input/postcode_alr_saved_lst.txt', 'a') as f: for pcl in saved_postcode_lst: f.write(str(pcl)+"\n") saved_postcode_lst[:] = [] # manager list remove all if len(no_data_lst) > 0: logger.info(f"No Data list {no_data_lst}") with nodatalock: with open('./running_input/postcode_no_data_lst.txt', 'a') as f: for pcl in no_data_lst: f.write(str(pcl)+"\n") no_data_lst[:] = [] # manager list remove all # %% def helperf(args): return collect_data_multiprocessing(*args) if __name__ == '__main__': if os.name == "nt": mp.set_start_method('spawn', force=True) else: mp.set_start_method('fork', force=True) manager = Manager() # Manager dictionary must be used for multiprocessing # m_saved_postcode_lst = manager.list(saved_postcode_lst) # m_no_data_lst = manager.list(no_data_lst) m_chromelock = manager.Lock() m_nodatalock = manager.Lock() m_savedpstcdlock = manager.Lock() m_loggingqueue = manager.Queue() parser = argparse.ArgumentParser() parser.add_argument('--data_index', type=int, required=True, choices=[1,2,3]) args = parser.parse_args() data_index = args.data_index # make chrome profile for i in range(PROCESS_NUM): chrome_profile_path = f"./chrome_profile/chrome_profile_propertydata_co_uk_{i+1}" if not os.path.exists(chrome_profile_path): Path(chrome_profile_path).mkdir(parents=True, exist_ok=True) # setup logger loggername = "web_scraping_status_logger" loggingfile = "web_scraping_status.log" logger = setupLogger(loggername, loggingfile, loggingqueue=m_loggingqueue) if os.path.exists('./running_input/postcode_no_data_lst.txt'): with open('./running_input/postcode_no_data_lst.txt', 'r') as f: no_data_lst = f.read() no_data_lst = no_data_lst.split('\n') else: no_data_lst = [] logger.info(f"No Data list len {len(no_data_lst)}") # make running_output dir Path('./running_output').mkdir(parents=True, exist_ok=True) # %% # get postcode list from local with open(f"./running_input/postcode_list_sub_{data_index}.pkl", 'rb') as f: postcode_list = pickle.load(f) logger.info(f'Postcode_list len raw: {len(postcode_list)}') if os.path.exists('./running_input/postcode_alr_saved_lst.txt'): with open('./running_input/postcode_alr_saved_lst.txt', 'r') as f: alr_saved_pstcd_list = f.read() alr_saved_pstcd_list = alr_saved_pstcd_list.split('\n') # to dict alr_saved_pstcd_dct = {x:None for x in alr_saved_pstcd_list} no_data_dict = {x:None for x in no_data_lst} postcode_list_temp = [] for pc in tqdm(postcode_list): if pc not in alr_saved_pstcd_dct and pc not in no_data_dict: postcode_list_temp.append(pc) postcode_list = postcode_list_temp logger.info(f'Postcode_list len after filtering: {len(postcode_list)}') # %% saved_postcode_lst = [] profile_path_list = glob(os.path.join(os.path.abspath(os.getcwd()), "chrome_profile", "chrome_profile_propertydata_co_uk_*")) m_profile_path_list = manager.list(profile_path_list) # %% postcode_list_chunks = [postcode_list[x:x+CHUNK_SIZE] for x in range(0, len(postcode_list), CHUNK_SIZE)] # %% args = [(chunk, m_chromelock,m_nodatalock,m_savedpstcdlock,m_loggingqueue, m_profile_path_list, loggername, loggingfile, data_index) for chunk in postcode_list_chunks] try: with mp.Pool(PROCESS_NUM) as pool: results = list(logging_tqdm(pool.imap(helperf, args, chunksize=1), total=len(args), loggername=loggername, loggingfile=loggingfile, loggingqueue=m_loggingqueue, desc="Progress Status in Main Process")) except Exception as e: logger.error(e) raise e finally: active_children = mp.active_children() for p in active_children: p.kill() p.join() logger.info("Killing all processes")

<span title='2023-06-22 22:38:28 +1000 AEST'>June 22, 2023</span>&nbsp;·&nbsp;10 min&nbsp;·&nbsp;2086 words&nbsp;·&nbsp;Sukai Huang

Web Scrawler Using Selenium 2023

[TOC] Title: Web Scrawler Using Selenium 2023 Review Date: Thu, Jun 22, 2023 Web scrawler, ticket buying as a case study Preparation: python venv check https://www.youtube.com/watch?v=Kg1Yvry_Ydk 1 2 3 4 5 6 7 8 9 python -m venv venv source venv/bin/activate # install the following using pip selenium==4.9.1 undetected-chromedriver>=3.4.6 webdriver-manager jupyterlab pyopenssl known where is the Google Chrome user file location 1 2 MAC ~/Library/Application Support/Google/Chrome Linux ~/.config/google-chrome 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 # load options options = uc.ChromeOptions() options.page_load_strategy = 'eager' # options.add_argument("--auto-open-devtools-for-tabs") # help to avoid cloudfare human verify check options.add_argument("--disable-popup-blocking") options.add_argument("--window-size=800,600") options.add_argument("--start-maximized") options.add_argument('--disable-gpu') options.add_argument("--no-sandbox") options.add_argument("--disable-setuid-sandbox") options.add_argument("--disable-extensions") options.add_argument('--disable-application-cache') options.add_argument("--disable-dev-shm-usage") if HEADLESS: options.add_argument("--headless=new") try: # check os system if os.name == "posix": time.sleep(3) # wait for chrome profile to be ready driver = uc.Chrome(options=options, driver_executable_path=ChromeDriverManager().install(), user_data_dir=chrome_profile_path, # version_main=VERSION, user_multi_procs=True) elif os.name == "nt": time.sleep(3) # wait for chrome profile to be ready options.add_argument(f"--user-data-dir={chrome_profile_path}") driver = uc.Chrome(options=options, driver_executable_path=ChromeDriverManager().install(), # driver_executable_path=os.path.join(os.path.abspath(os.getcwd()), 'chromedriver-win64/chromedriver-win64/chromedriver.exe'), user_multi_procs=True, ) else: raise Exception("Unknown OS") driver.implicitly_wait(5) Some known issue about selenium to avoid memory leak in multiprocessing env, please import the driver inside the subprocess (e.g., inside the function) wait until presence is very slow, try the sleepy find element we need to setup logging queue to avoid crash for multiprocessing logging module list(tqdm(pool.imap(*), total = len(*))) is a good way to record multiprocess progress Utils functions sleep find element 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 def sleepy_find_element(by, query, attempt_count :int =30, sleep_duration =0.3): ''' Finds the web element using the locator and query. This function attempts to find the element multiple times with a specified sleep duration between attempts. If the element is found, the function returns the element. Args: by (selenium.webdriver.common.by.By): The method used to locate the element. query (str): The query string to locate the element. attempt_count (int, optional): The number of attempts to find the element. Default: 20. sleep_duration (int, optional): The duration to sleep between attempts. Default: 1. Returns: selenium.webdriver.remote.webelement.WebElement: Web element or None if not found. ''' global browser for _count in range(attempt_count): item = browser.find_elements(by, query) if len(item) > 0: item = item[0] logging.info(f'Element {query} has found') break logging.info(f'Element {query} is not present, attempt: {_count+1}') time.sleep(sleep_duration) if item is list: logging.warning("Element not find!") return item move to element 1 2 3 4 5 6 7 8 # import Action chains from selenium.webdriver import ActionChains #element source = driver.find_element_by_id("name") #action chain object action = ActionChains(driver) # move to element operation action.move_to_element(source).click().perform() useful imports 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException, NoSuchElementException import logging from pathlib import Path from tqdm.auto import tqdm import os import pickle import csv import time import threading from glob import glob import argparse lxml html xpath with requests used for requests (simpler and faster in some cases) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from lxml import html response = requests.get(complete_url) content = response.content tree = html.fromstring(content) # read byte content # print("start loading") # latitude latitude_xp = '//h3[contains(text(), "Coordinates")]/following-sibling::p[contains(text(), "Latitude")]' latitude_ele = tree.xpath(latitude_xp) if latitude_ele: latitude_ele = latitude_ele[0] latitude_info = latitude_ele.text_content().strip().split("Latitude: ")[1] # print('latitude_info', latitude_info) temp = dict() temp['latitude'] = latitude_info else: return text_content() will get all the text in the node, which is same as .text in selenium multiprocessing with tqdm 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 from tqdm.contrib.concurrent import process_map from multiprocessing import Pool, Process, Manager, Lock manager = Manager() # Manager dictionary must be used for multiprocessing # m_saved_postcode_lst = manager.list(saved_postcode_lst) # m_no_data_lst = manager.list(no_data_lst) m_chromelock = manager.Lock() m_nodatalock = manager.Lock() m_savedpstcdlock = manager.Lock() m_profile_path_list = manager.list(profile_path_list) # %% postcode_list_chunks = [postcode_list[x:x+CHUNK_SIZE] for x in range(0, len(postcode_list), CHUNK_SIZE)] # %% args = [(chunk, m_chromelock,m_nodatalock,m_savedpstcdlock, m_profile_path_list, loggername, loggingfile, data_index) for chunk in postcode_list_chunks] try: with mp.Pool(PROCESS_NUM) as pool: results = list(logging_tqdm(pool.imap(helperf, args, chunksize=1), total=len(args), loggername=loggername, loggingfile=loggingfile, desc="Progress Status in Main Process")) except Exception as e: logger.error(e) raise e finally: active_children = mp.active_children() for p in active_children: p.kill() p.join() logger.info("Killing all processes") # IMPORTANT we must attach dict to the manager dict, nest dict update is banned in multiprocessing temp = { "United States": "New York", "Italy": "Naples", "England": "London" } postcode_info_dict[postcode] = temp # OK postcode_info_dict[postcode]['United States'] = "New York" # BAD

<span title='2023-06-22 22:38:28 +1000 AEST'>June 22, 2023</span>&nbsp;·&nbsp;4 min&nbsp;·&nbsp;813 words&nbsp;·&nbsp;Sukai Huang

Xpath-cheatsheet

[TOC] Xpath cheatsheet Previous Next Page: /

<span title='2023-06-22 22:38:28 +1000 AEST'>June 22, 2023</span>&nbsp;·&nbsp;1 min&nbsp;·&nbsp;7 words&nbsp;·&nbsp;Sukai Huang

Python Module and Package Management 2023

[TOC] Title: Python Module and Package Management 2023 url: https://www.youtube.com/watch?v=v6tALyc4C10 Python module common issue 1: python -m dir vs python dir python dir will use the dir as the PYTHONPATH as run __main__.py file. however, python -m dir will not use the dir as PYTHONPATH but rather it will search the local library. thus ModuleNotFoundError may appear Standard way of import when you want to create a module use absolute path -> from moduledir/packagename import filename avoid using relative path e.g., from .xxx import yyy if within the same module, you can just use from xxx import yyy However, in a complicated project where there are too many modules. one workaround is that we still make it a module, but try to append folder path to the system path. 1 2 import os, sys sys.path.append(os.path.dirname(os.path.realpath(__file__))) always use it as the last resort. Solution: setup pyproject.toml and install it as a proper module python -m venv .venv ...

<span title='2023-05-28 11:56:47 +1000 AEST'>May 28, 2023</span>&nbsp;·&nbsp;5 min&nbsp;·&nbsp;1024 words&nbsp;·&nbsp;Sukai Huang