yklibpy 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
yklibpy/db/__init__.py ADDED
@@ -0,0 +1,27 @@
1
+ from .db_yaml import DbYaml
2
+
3
+ def get_or_create(kind, fname):
4
+ if kind.lower() == "yaml":
5
+ db = DbYaml(fname)
6
+ else:
7
+ db = None
8
+ return db
9
+
10
+ def db_yaml():
11
+ db = get_or_create("yaml","db.yaml")
12
+ db.load()
13
+ db.set_item("name", "John")
14
+ print(f'db={db.dump()}')
15
+ return db
16
+
17
+ __all__ = [
18
+ "DbYaml",
19
+ "get_or_create",
20
+ "db_yaml"
21
+ ]
22
+
23
+ if __name__ == "__main__":
24
+ fname = "db.yaml"
25
+ db = get_or_create("db_yaml", fname)
26
+ print(f'db={db}')
27
+
yklibpy/db/db_base.py ADDED
@@ -0,0 +1,6 @@
1
+
2
+ class DbBase():
3
+ def __init__(self):
4
+ self.assoc = {}
5
+
6
+
yklibpy/db/db_yaml.py ADDED
@@ -0,0 +1,61 @@
1
+ from .db_base import DbBase
2
+ import sys
3
+ import yaml
4
+ import chardet
5
+ from pathlib import Path
6
+ from ..common.util import Util
7
+
8
+ class DbYaml(DbBase):
9
+ def __init__(self, fname):
10
+ DbBase.__init__(self)
11
+ self.fname = fname
12
+ self.fname_path = Path(fname)
13
+ self.data = {}
14
+
15
+ def load(self, encoding=None):
16
+ Util.ensure_file_path(self.fname_path)
17
+
18
+ if encoding is None:
19
+ encoding = Util.detect_encoding(self.fname_path)
20
+ if encoding is None:
21
+ encoding = Util.get_default_encoding()
22
+
23
+ with open(self.fname_path, 'r', encoding=encoding) as f:
24
+ self.data = yaml.safe_load(f)
25
+ if self.data is None:
26
+ self.data = {}
27
+
28
+ return self.data
29
+
30
+ def save(self):
31
+ Util.save_yaml(self.data, self.fname_path)
32
+ return True
33
+
34
+ def get_data(self):
35
+ return self.data
36
+
37
+ def set_data(self, data):
38
+ self.data = data
39
+ return True
40
+
41
+ def get_item(self, key):
42
+ return self.data[key]
43
+
44
+ def set_item(self, key, value):
45
+ self.data[key] = value
46
+ return True
47
+
48
+ def clear(self):
49
+ self.data = {}
50
+ return True
51
+
52
+ def count(self):
53
+ return len(self.data)
54
+
55
+ def list_text(self, key):
56
+ return [value[key] for value in list(self.data.values())]
57
+
58
+ if __name__ == "__main__":
59
+ if len(sys.argv) > 1:
60
+ print('DBファイルが指定されていません')
61
+ exit(10)
@@ -0,0 +1,37 @@
1
+ from .app import App
2
+ from .amazonsavedcartscraper import AmazonSavedCartScraper
3
+ from .ascraper import AScraper
4
+ from .fanzadoujinpurchasedscraper import FanzaDoujinPurchasedScraper
5
+ from .fanzadoujinscraper import FanzaDoujinScraper
6
+ from .h3scraper import H3Scraper
7
+ from .kuscraper import KUScraper
8
+ from .progress import Progress
9
+ from .scraper import Scraper
10
+ from .udemyscraper import UdemyScraper
11
+ from .preparex import Preparex
12
+
13
+ def xmain() -> str:
14
+ print("Hello from yklibpy!")
15
+ return "Hello from yklibpy!"
16
+
17
+ def ymain() -> str:
18
+ print("Y Hello from yklibpy!")
19
+ return "Y Hello from yklibpy!"
20
+
21
+ __all__ = [
22
+ "App",
23
+ "AmazonSavedCartScraper",
24
+ "AScraper",
25
+ "FanzaDoujinPurchasedScraper",
26
+ "FanzaDoujinScraper",
27
+ "FanzaDoujindScraper",
28
+ "H3Scraper",
29
+ "KUScraper",
30
+ "Progress",
31
+ "Scraper",
32
+ "UdemyScraper",
33
+ "Preparex"
34
+ ]
35
+
36
+ if __name__ == "__main__":
37
+ xmain()
@@ -0,0 +1,3 @@
1
+ class Amazon:
2
+ def __init__(self):
3
+ self.asin = None
@@ -0,0 +1,106 @@
1
+ from typing import Dict, List
2
+ from urllib.parse import parse_qs, urlparse
3
+
4
+ from bs4 import BeautifulSoup
5
+ from bs4.element import NavigableString
6
+ from ..common.info import Info
7
+ from .progress import Progress
8
+ from .scraper import Scraper
9
+ from ..common.util import Util
10
+
11
+ class AmazonSavedCartScraper(Scraper):
12
+ class WorkInfo:
13
+ def __init__(self, asin: str, target: str, url: str, title: str):
14
+ self.asin = asin
15
+ self.target = target
16
+ self.title = title
17
+
18
+ result = Util.isValidUrls([url])
19
+ if result:
20
+ self.url = url
21
+ else:
22
+ self.url = None
23
+
24
+ def to_assoc(self):
25
+ return {
26
+ "asin": self.asin,
27
+ "target": self.target,
28
+ "url": self.url,
29
+ "title": self.title,
30
+ }
31
+
32
+ def __init__(self):
33
+ """Initialize Udemy-specific scraper state.
34
+
35
+ Returns:
36
+ None
37
+ """
38
+ super().__init__()
39
+
40
+ def scrape(self, info: Info) -> List[Dict[str, str]]:
41
+ """Extract Udemy dashboard cards and convert them into records.
42
+
43
+ Args:
44
+ info (Info): Parsed HTML container and counters for the current file.
45
+
46
+ Returns:
47
+ List[Dict[str, str]]: List of record dictionaries appended this run.
48
+ """
49
+ print("amazonsavedcart scrape")
50
+ soup = info.soup
51
+ append_count = 0
52
+ no_append_count = 0
53
+ """divの処理"""
54
+ print("--- 子要素の列挙 ---")
55
+
56
+ for div_tag in soup.find_all("div", {"id": "sc-saved-cart-items"}):
57
+ # print(div_tag)
58
+ list = div_tag.find_all('div', {'data-asin': True})
59
+ # print(list)
60
+ for div_tag_2 in list:
61
+ # print(f'div_tag_2={div_tag_2}')
62
+ asin = div_tag_2.get("data-asin", "")
63
+ # print(f'asin={asin}')
64
+ div_tag_3 = div_tag_2.find("div", {"class": "sc-list-item-removed-msg"})
65
+ # print(f"div_tag_3={div_tag_3}")
66
+ if div_tag_3 is not None:
67
+ a_tag = div_tag_2.find("a")
68
+ if a_tag is None:
69
+ continue
70
+ url = a_tag.get("href", "#")
71
+ title = "".join(
72
+ s for s in a_tag.contents if isinstance(s, NavigableString)
73
+ ).strip()
74
+ # course_id = self.get_course_id_from_url(url)
75
+ # print(f'asin={asin}')
76
+ # print(f'url={url}')
77
+ # print(f'text={text}')
78
+ # print("====")
79
+ work_info = self.WorkInfo(asin=asin, target="savedcart", url=url, title=title)
80
+ result = self.add_list_and_assoc(work_info)
81
+
82
+ if result:
83
+ append_count += 1
84
+ else:
85
+ no_append_count += 1
86
+
87
+ print("--- 子要素の列挙終了 ---")
88
+
89
+ info.append_count = append_count
90
+ info.no_append_count = no_append_count
91
+ self.append_count += append_count
92
+ self.no_append_count += no_append_count
93
+ print(f"############### amazonsavedcart scrape len( self.links_list )={len(self.links_list)}")
94
+ print(f"############### amazonsavedcart scrape len( self.links_assoc )={len(self.links_assoc)}")
95
+ return self.links_list
96
+
97
+ def add_list_and_assoc( self, work_info: WorkInfo ) -> bool:
98
+ result = False
99
+ if work_info.asin not in self.links_assoc.keys():
100
+ self.links_assoc[work_info.asin] = work_info
101
+ self.links_list.append(work_info)
102
+ result = True
103
+ else:
104
+ pass
105
+
106
+ return result
@@ -0,0 +1,101 @@
1
+ import sys
2
+ from pathlib import Path
3
+ from typing import List
4
+
5
+ # from .ascraper import AScraper
6
+ from .ascraper import AScraper
7
+ from .amazonsavedcartscraper import AmazonSavedCartScraper
8
+ from ..common.env import Env
9
+ from .h3scraper import H3Scraper
10
+ from .kuscraper import KUScraper
11
+ from .fanzadoujinscraper import FanzaDoujinScraper
12
+ from .fanzadoujinpurchasedscraper import FanzaDoujinPurchasedScraper
13
+ from .scraper import Scraper
14
+
15
+ # from progress import Progress
16
+ from .udemyscraper import UdemyScraper
17
+
18
+ class App:
19
+ """
20
+ HTMLファイルからリンクを抽出するアプリケーションクラス
21
+ """
22
+
23
+ def __init__(self):
24
+ """Reset link buffers, metadata, and counters for a fresh run.
25
+
26
+ Returns:
27
+ None
28
+ """
29
+ self.links_list = []
30
+ self.links_assoc = {}
31
+ self.info = {}
32
+ self.append_count = 0
33
+ self.no_append_count = 0
34
+
35
+ def create_scraper(self, mode: str) -> Scraper:
36
+ """Build the appropriate scraper implementation for the requested mode.
37
+
38
+ Args:
39
+ mode (str): Logical identifier such as ``"udemy"`` or ``"h3"``.
40
+
41
+ Returns:
42
+ Scraper: Concrete scraper that knows how to parse the given site, or
43
+ ``None`` when the mode is unsupported.
44
+ """
45
+ if mode == "udemy":
46
+ return UdemyScraper()
47
+ # return H3Scraper()
48
+ # return AScraper()
49
+ elif mode == "h3":
50
+ return H3Scraper()
51
+ elif mode == "a":
52
+ return AScraper()
53
+ elif mode == "ku":
54
+ return KUScraper()
55
+ elif mode == "fanza_doujin":
56
+ return FanzaDoujinScraper()
57
+ elif mode == "fanza_doujin_purchased":
58
+ return FanzaDoujinPurchasedScraper()
59
+ elif mode == "amazon_saved_cart":
60
+ # print(f'mode={mode}')
61
+ return AmazonSavedCartScraper()
62
+ else:
63
+ print(f'mode={mode} is not supported')
64
+ return None
65
+
66
+ def loop(self, files: List[Path], mode: str):
67
+ """Iterate through HTML files and accumulate extracted link metadata.
68
+
69
+ Args:
70
+ files (List[Path]): Collection of HTML paths to inspect.
71
+ mode (str): Scraper mode passed through to :meth:`create_scraper`.
72
+
73
+ Returns:
74
+ dict: Mapping of link identifiers to their structured attributes.
75
+ """
76
+ assoc = {}
77
+ for file in files:
78
+ scraper = self.create_scraper(mode)
79
+ extracted_links_assoc = scraper.get_links_assoc_from_html(file)
80
+ if extracted_links_assoc:
81
+ if len(extracted_links_assoc) > 0:
82
+ assoc.update(extracted_links_assoc)
83
+ return assoc
84
+
85
+ def run(self, env: Env):
86
+ """Fetch file paths from the environment and scrape each one.
87
+
88
+ Args:
89
+ env (Env): Environment descriptor that supplies file lists and mode.
90
+
91
+ Returns:
92
+ None
93
+ """
94
+ path_array = env.get_files()
95
+ mode = env.mode()
96
+
97
+ assoc = self.loop(path_array, mode)
98
+ self.links_assoc.update(assoc)
99
+
100
+ if __name__ == "__main__":
101
+ ymain()
@@ -0,0 +1,77 @@
1
+ from typing import Dict, List
2
+
3
+ from ..common.info import Info
4
+ from .udemyscraper import UdemyScraper
5
+
6
+
7
+ class AScraper(UdemyScraper):
8
+ def __init__(self):
9
+ """Initialize the Amazon scraper with Udemy defaults.
10
+
11
+ Returns:
12
+ None
13
+ """
14
+ super().__init__()
15
+
16
+ def scrape(self, info: Info) -> List[Dict[str, str]]:
17
+ """Collect course-like links from Amazon-style listings.
18
+
19
+ Args:
20
+ info (Info): Parsed HTML metadata and bookkeeping container.
21
+
22
+ Returns:
23
+ List[Dict[str, str]]: Records appended during this scrape run.
24
+ """
25
+ print("ascraper scrape")
26
+ soup = info.soup
27
+ append_count = 0
28
+ no_append_count = 0
29
+ """ aタグでは部分的な情報しか取得できない """
30
+ """ クラスが"a-link-normal"でない場合はcontinue """
31
+ """aの処理"""
32
+ for a_tag in soup.find_all("a"):
33
+ # print(f'a_tag={a_tag}')
34
+
35
+ # classが"a-link-normal"でない場合はcontinue
36
+ if a_tag.get("class") != ["a-link-normal"]:
37
+ # print(f'continue a_tag.get("class")={a_tag.get("class")}')
38
+ continue
39
+ print(f'Not continuea_tag.get("class")={a_tag.get("class")}')
40
+ # classが"a-link-normal"の場合、anchorタグの子要素のimgタグのalt属性を取得
41
+ url = a_tag.get("href", "#")
42
+ # print(f'url={url}')
43
+ img_tag = a_tag.find("img")
44
+ # print(f'img_tag={img_tag}')
45
+ if img_tag:
46
+ text = img_tag.get("alt", "")
47
+ else:
48
+ text = a_tag.get_text(strip=True)
49
+ # Extract course_id from URL parameters
50
+ course_id = self.get_course_id_from_url(url)
51
+ instructors = {"-"}
52
+ result = self.add_list_and_assoc(url=url, text=text, course_id=course_id, instructors=instructors)
53
+ if result:
54
+ append_count += 1
55
+ else:
56
+ no_append_count += 1
57
+
58
+ info.append_count = append_count
59
+ info.no_append_count = no_append_count
60
+ self.append_count += append_count
61
+ self.no_append_count += no_append_count
62
+
63
+ return self.links_list
64
+
65
+ def _extract_links_from_info(self, info: Info) -> List[Dict[str, str]]:
66
+ """Override Udemy extraction by leveraging :meth:`scrape`.
67
+
68
+ Args:
69
+ info (Info): Parsed HTML payload for the current file.
70
+
71
+ Returns:
72
+ List[Dict[str, str]]: Newly extracted link records.
73
+ """
74
+ super()._extract_links_from_info(info)
75
+ links_list = self.scrape(info)
76
+
77
+ return links_list
@@ -0,0 +1,29 @@
1
+ class ConfigPrepare:
2
+ def __init__(self, parent_file_path: Path, assoc: dict):
3
+ self.parent_file_path = parent_file_path
4
+ self.assoc = assoc
5
+
6
+ def get(self, key):
7
+ return self.assoc[key]
8
+
9
+ def get_command(self):
10
+ return self.assoc["command"]
11
+
12
+ def get_command_dir(self):
13
+ return self.assoc["command"]["dir"]
14
+
15
+ def get_category_config_file_extname(self):
16
+ return self.assoc["category-config-file-extname"]
17
+
18
+ def get_utility_category(self):
19
+ return self.assoc["command"]["utility-category"]
20
+
21
+ def get_utility_root(self):
22
+ return self.assoc["command"]["utility-root"]
23
+
24
+ def get_category(self):
25
+ return self.assoc["category"]
26
+
27
+ def get_htmlparser(self):
28
+ return self.assoc["category"]["htmlparser"]
29
+
@@ -0,0 +1,80 @@
1
+ from typing import Dict, List
2
+ from urllib.parse import urlparse
3
+
4
+ from ..common.info import Info
5
+ from .scraper import Scraper
6
+ from ..common.util import Util
7
+ from .htmlop import HtmlOp
8
+
9
+ class FanzaDoujinPurchasedScraper(Scraper):
10
+ class WorkInfo:
11
+ def __init__(self, target: str, product_id: str, url:str, purchased_date: str, kind: str, title: str, circle_name: str):
12
+ self.target=target
13
+ self.product_id=product_id
14
+ self.url=url
15
+ self.purchased_date=purchased_date
16
+ self.kind=kind
17
+ self.title=title
18
+ self.circle_name=circle_name
19
+
20
+ def to_assoc(self):
21
+ return {
22
+ "product_id": self.product_id,
23
+ "target": self.target,
24
+ "url": self.url,
25
+ "purchased_date": self.purchased_date,
26
+ "kind": self.kind,
27
+ "title": self.title,
28
+ "circle_name": self.circle_name,
29
+ }
30
+
31
+ def __init__(self):
32
+ super().__init__()
33
+
34
+ def add_list_and_assoc(self, work_info: WorkInfo):
35
+ result = False
36
+ if work_info.product_id not in self.links_assoc.keys():
37
+
38
+ self.links_assoc[work_info.product_id] = work_info.to_assoc()
39
+ self.links_list.append(work_info.to_assoc())
40
+ result = True
41
+ else:
42
+ pass
43
+
44
+ return result
45
+
46
+ def scrape(self, info: Info) -> List[Dict[str, str]]:
47
+ soup = info.soup
48
+ append_count = 0
49
+ no_append_count = 0
50
+ id_str = "mylibrary-app"
51
+ target = "purchased"
52
+ for top in soup.find_all("div", {"id": id_str}):
53
+ for purchased_date in top.find_all("p", {"class": "purchasedListTitleiBWYR"}):
54
+ purchased_date_text = purchased_date.text
55
+ parent = purchased_date.parent
56
+ for div_tag in parent.find_all("div", {"class": "localListProductzKID2"}):
57
+ anchor_tag = div_tag.find("a")
58
+ url = anchor_tag.get("href","")
59
+ product_id = Util.extract_base("product_id", url)
60
+ span_tag = anchor_tag.find("span", {"class": "defaultClassmE6be"} )
61
+ kind = span_tag.text
62
+ namex = anchor_tag.find("div", {"class": "productTitleCMVya"} )
63
+ title = namex.text
64
+ p_tag = anchor_tag.find("p", {"class": "circleNameGWNom"})
65
+ circle_name = p_tag.text
66
+ work_info = self.WorkInfo(target=target, url=url, product_id=product_id, purchased_date=purchased_date_text, kind=kind, title=title, circle_name=circle_name)
67
+ result = self.add_list_and_assoc(work_info)
68
+ if result:
69
+ append_count += 1
70
+ else:
71
+ no_append_count += 1
72
+
73
+ info.append_count = append_count
74
+ info.no_append_count = no_append_count
75
+ self.append_count += append_count
76
+ self.no_append_count += no_append_count
77
+ return self.links_list
78
+
79
+
80
+