pixBoards 2.4__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.

Potentially problematic release.


This version of pixBoards might be problematic. Click here for more details.

boards/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ import subprocess
2
+
3
+
4
+ def get_git_version():
5
+ try:
6
+ commit_hash = (
7
+ subprocess.check_output(["git", "rev-parse", "--short", "HEAD"])
8
+ .decode()
9
+ .strip()
10
+ )
11
+ return commit_hash
12
+ except Exception:
13
+ return "untracked"
14
+
15
+
16
+ __version__ = get_git_version()
boards/arguments.py ADDED
@@ -0,0 +1,34 @@
1
+ import argparse
2
+
3
+ # Parse arguments
4
+ parser = argparse.ArgumentParser(description="Generate HTML for media directories.")
5
+ parser.add_argument(
6
+ "--random",
7
+ type=int,
8
+ help="number of images to sample from all boards. use a number higher than the number of total images to shuffle instead",
9
+ )
10
+ parser.add_argument(
11
+ "--ranDir",
12
+ type=str,
13
+ help="Directory to search images in for --random",
14
+ )
15
+ parser.add_argument("--dir", type=str, help="Directory to use for the images")
16
+ # parser.add_argument("--csvs", nargs="+", help="List of CSV files to use")
17
+ parser.add_argument(
18
+ "--useLists", action="store_true", help="Use list files from config"
19
+ )
20
+ parser.add_argument("--imageLists", nargs="+", help="List of imagelist files to use.")
21
+ parser.add_argument("--col", type=int, help="Number of columns to default to")
22
+ parser.add_argument("--margin", type=int, help="Margin in px")
23
+ # parser.add_argument("--rancount", type=int, help="number of images to sample from all boards. use a number higher than the number of total images to shuffle instead")
24
+ parser.add_argument("--upload", action="store_true", help="Upload images to Imgchest")
25
+ parser.add_argument("--config", type=str, help="config file to use")
26
+ parser.add_argument(
27
+ "--saveBoards", action="store_true", help="Save generated boards to PostgreSQL"
28
+ )
29
+ parser.add_argument(
30
+ "--gitPush", action="store_true", help="Push outputDir to existing Git repo"
31
+ )
32
+ parser.add_argument("--useSaved", action="store_true", help="use only saved images")
33
+
34
+ args = parser.parse_args()
boards/boardmakers.py ADDED
@@ -0,0 +1,257 @@
1
+ import os
2
+ import random
3
+ from pathlib import Path
4
+
5
+ import psycopg2
6
+ import yaml
7
+
8
+ from pixBoards.arguments import args
9
+ from pixBoards.classes import board
10
+ from pixBoards.imgchest import process_images
11
+ from pixBoards.log_utils import setup_logger
12
+
13
+ logger = setup_logger(__name__)
14
+
15
+
16
+ def load_config(yml_path):
17
+ with open(yml_path, "r", encoding="utf-8") as f:
18
+ return yaml.safe_load(f)
19
+
20
+
21
+ if args.config:
22
+ configFile = args.config
23
+ else:
24
+ configFile = "config.yml"
25
+ config = load_config(configFile)
26
+
27
+
28
+ def boardsForImglist(imgList_List, listDir, paginate):
29
+ # Now I might need to sanitise the image list
30
+ # so that there aren't instances with the same name.
31
+ # But as the imagelist files are in the same folder,
32
+ # they won't have the same name, so I leave this for the future me.
33
+ os.makedirs(listDir, exist_ok=True)
34
+
35
+ boards = []
36
+
37
+ for idx, imgListFile in enumerate(imgList_List):
38
+ boardName = os.path.splitext(os.path.basename(imgListFile))[0]
39
+
40
+ with open(imgListFile, "r", encoding="utf-8") as f:
41
+ images = [line.strip() for line in f if line.strip()]
42
+
43
+ outputFile = os.path.join(listDir, boardName)
44
+ logger.info(f"output file = {outputFile}")
45
+
46
+ b = board(
47
+ name=boardName,
48
+ output_file_loc=outputFile + ".html",
49
+ image_paths=images,
50
+ paginate=paginate,
51
+ images_per_page=config["page_size"] if paginate else 10000,
52
+ img_list_status=True,
53
+ )
54
+ b.paginate_board()
55
+ boards.append(b)
56
+
57
+ return boards
58
+
59
+
60
+ def standardBoards(directories, outputDir, paginate, upload):
61
+ boards = []
62
+ outputDir = Path(outputDir)
63
+ outputDir.mkdir(parents=True, exist_ok=True)
64
+
65
+ media_extensions = (
66
+ ".jpg",
67
+ ".jpeg",
68
+ ".png",
69
+ ".gif",
70
+ ".bmp",
71
+ ".webp",
72
+ # ".heic", # you need to convert these to normal images to display in browser
73
+ ".mp4",
74
+ ".avi",
75
+ ".webm",
76
+ ".mov",
77
+ )
78
+
79
+ for d in directories:
80
+ # normalize to a Path
81
+ src_dir = Path(d)
82
+
83
+ if not src_dir.exists():
84
+ logger.warning(f"Skipping non-existent directory: {src_dir}")
85
+ continue
86
+
87
+ for root, dirs, files in os.walk(src_dir):
88
+ image_paths = []
89
+
90
+ for fname in sorted(files):
91
+ if fname.lower().endswith(media_extensions):
92
+ abs_path = Path(root) / fname
93
+ image_paths.append(abs_path.resolve().as_uri())
94
+
95
+ logger.debug(f"Processing {root} with {len(image_paths)} images.")
96
+
97
+ # skip the top‑level folder itself if you don’t want a board for it.
98
+ # I want a board so I won't be skipping
99
+ # dummy = False
100
+
101
+ rel = Path(root).relative_to(os.path.dirname(src_dir))
102
+ # if str(rel) == ".":
103
+ # board_name = src_dir.name # dummy boards too
104
+ # dummy = True
105
+
106
+ # continue
107
+
108
+ board_name = str(rel).replace(os.sep, "_~")
109
+ output_path = outputDir # everything writes into this one folder
110
+ # collect local files
111
+ local_files = [
112
+ Path(root) / f
113
+ for f in sorted(files)
114
+ if f.lower().endswith(media_extensions)
115
+ ]
116
+ if not local_files:
117
+ logger.debug(f"No media in {root}, creating empty board.")
118
+ b = board(
119
+ name=board_name,
120
+ output_file_loc=str(outputDir),
121
+ image_paths=[],
122
+ paginate=paginate,
123
+ images_per_page=(config["page_size"] if paginate else 10000),
124
+ upload=upload,
125
+ dummy_status=True,
126
+ # outputDir=outputDir
127
+ )
128
+ else:
129
+ # create a Board object and paginate it
130
+ b = board(
131
+ name=board_name,
132
+ output_file_loc=str(output_path),
133
+ image_paths=image_paths,
134
+ paginate=paginate,
135
+ images_per_page=(config["page_size"] if paginate else 10000),
136
+ upload=upload,
137
+ dummy_status=False,
138
+ )
139
+
140
+ b.paginate_board()
141
+ boards.append(b)
142
+
143
+ logger.debug(f"Board created: {board_name} ({len(image_paths)} images)")
144
+
145
+ return boards
146
+
147
+
148
+ def uploadBoards(directories, outputDir, paginate, upload=True):
149
+ def connect_db():
150
+ return psycopg2.connect(
151
+ dbname="boards",
152
+ user="postgres",
153
+ password="password",
154
+ host="localhost",
155
+ )
156
+
157
+ conn = connect_db()
158
+ boards = []
159
+ outputDir = Path(outputDir)
160
+ outputDir.mkdir(parents=True, exist_ok=True)
161
+
162
+ media_extensions = (
163
+ ".jpg",
164
+ ".jpeg",
165
+ ".png",
166
+ ".gif",
167
+ ".bmp",
168
+ ".webp",
169
+ ".mp4",
170
+ ".avi",
171
+ ".webm",
172
+ )
173
+
174
+ for d in directories:
175
+ src_dir = Path(d)
176
+ if not src_dir.exists():
177
+ logger.warning(f"Skipping non-existent directory: {src_dir}")
178
+ continue
179
+
180
+ for root, _, files in os.walk(src_dir):
181
+ rel = Path(root).relative_to(os.path.dirname(src_dir))
182
+ board_name = (
183
+ src_dir.name if rel == Path(".") else str(rel).replace(os.sep, "_~")
184
+ )
185
+
186
+ local_files = [
187
+ Path(root) / f
188
+ for f in sorted(files)
189
+ if f.lower().endswith(media_extensions)
190
+ ]
191
+
192
+ if not local_files:
193
+ logger.debug(f"No media in {root}, creating empty board.")
194
+ boards.append(
195
+ board(
196
+ name=board_name,
197
+ output_file_loc=str(outputDir),
198
+ image_paths=[],
199
+ paginate=paginate,
200
+ images_per_page=(config["page_size"] if paginate else 10000),
201
+ upload=upload,
202
+ # outputDir=outputDir,
203
+ dummy_status=True,
204
+ )
205
+ )
206
+ continue
207
+
208
+ logger.debug(f"Uploading {len(local_files)} images from {root}…")
209
+ try:
210
+ http_links, hash_map = process_images(local_files, conn)
211
+ except Exception as e:
212
+ logger.error(f"Failed to upload images in {root}: {e}")
213
+ continue
214
+
215
+ b = board(
216
+ name=board_name,
217
+ output_file_loc=str(outputDir),
218
+ image_paths=http_links,
219
+ paginate=paginate,
220
+ images_per_page=(config["page_size"] if paginate else 10000),
221
+ upload=upload,
222
+ # outputDir=outputDir
223
+ )
224
+ b.link_hash_map = hash_map
225
+ b.paginate_board()
226
+ boards.append(b)
227
+ logger.debug(
228
+ f"Uploaded board created: {board_name} ({len(http_links)} images)"
229
+ )
230
+
231
+ conn.close()
232
+ return boards
233
+
234
+
235
+ def randomBoard(boards, count, outputDir, paginate, upload):
236
+ images = []
237
+ for b in boards:
238
+ images.extend(b.image_paths)
239
+
240
+ try:
241
+ ran_images = random.sample(images, count)
242
+ except:
243
+ random.shuffle(images)
244
+ ran_images = images
245
+
246
+ ranBoard = board(
247
+ name="randomised_set",
248
+ output_file_loc=outputDir,
249
+ image_paths=ran_images,
250
+ paginate=paginate,
251
+ upload=upload,
252
+ dummy_status=False,
253
+ )
254
+
255
+ ranBoard.paginate_board()
256
+
257
+ return ranBoard
boards/classes.py ADDED
@@ -0,0 +1,103 @@
1
+ import os
2
+ from datetime import date
3
+
4
+ # set up logger
5
+ today = date.today()
6
+ from pixBoards.log_utils import setup_logger
7
+
8
+ logger = setup_logger(__name__)
9
+
10
+ import yaml
11
+
12
+ from pixBoards.arguments import args
13
+
14
+
15
+ def load_config(yml_path):
16
+ with open(yml_path, "r", encoding="utf-8") as f:
17
+ return yaml.safe_load(f)
18
+
19
+
20
+ if args.config:
21
+ configFile = args.config
22
+ # print('configfile is ' + configFile)
23
+ else:
24
+ configFile = "config.yml"
25
+ config = load_config(configFile)
26
+
27
+ # masterDir = config["masterDir"]
28
+
29
+ padding = config["padding"]
30
+ imgs_per_page = config["page_size"]
31
+ # print(f'imgs per page are {imgs_per_page}' )
32
+
33
+
34
+ class page:
35
+ def __init__(self, page_number, total_pages, images, file_location):
36
+ self.page_number = page_number # Current page number
37
+ self.images = images # image list for the page
38
+ self.total_pages = total_pages
39
+ self.file_location = file_location
40
+
41
+
42
+ from math import ceil
43
+
44
+
45
+ class board:
46
+ def __init__(
47
+ self,
48
+ name,
49
+ output_file_loc,
50
+ image_paths,
51
+ # outputDir,
52
+ images_per_page=None, # deprecated
53
+ paginate=True,
54
+ upload=False,
55
+ dummy_status=False,
56
+ img_list_status=False,
57
+ ):
58
+ self.name = name
59
+ self.image_paths = image_paths
60
+ self.pages = [] # will be storing a list of instances of class, page.
61
+ self.images_per_page = imgs_per_page
62
+ self.output_file_loc = output_file_loc
63
+ self.upload_status = upload
64
+ self.paginate_status = paginate
65
+ self.link_hash_map = {} if self.upload_status else None
66
+ # self.outputDir = outputDir
67
+ # self.subfolders = []
68
+ self.nested_boards = []
69
+ self.dummy_status = dummy_status
70
+ self.img_list_status = img_list_status
71
+
72
+ def paginate_board(self):
73
+ total_images = len(self.image_paths)
74
+ # logger.info(f'total images = {total_images}')
75
+ total_pages = ceil(total_images / self.images_per_page)
76
+ output_base = self.output_file_loc
77
+ for i in range(total_pages):
78
+
79
+ start = i * self.images_per_page
80
+ end = start + self.images_per_page
81
+ page_images = self.image_paths[start:end]
82
+
83
+ # if self.output_file_loc[-5:] == '.html':
84
+ # file_loc = self.output_file_loc.replace('.html', f'_{(i+1):0{padding}}.html') # padded to 3 digits.
85
+ # logger.info('output loc has .html')
86
+ # else:
87
+ # # file_loc = self.output_file_loc + f'_{(i+1):0{padding}}.html'
88
+ # file_loc = os.path.join(self.output_file_loc, self.name) + f'_{(i+1):0{padding}}.html'
89
+ # logger.info('output loc doesn\' have .html' + file_loc)
90
+ # logger.info('board name is ' + self.name)
91
+ file_loc = (
92
+ os.path.join(output_base, self.name) + f"_{(i+1):0{padding}}.html"
93
+ )
94
+ Page = page(
95
+ page_number=i + 1,
96
+ total_pages=total_pages,
97
+ images=page_images,
98
+ file_location=file_loc,
99
+ )
100
+ self.pages.append(Page)
101
+ logger.debug(
102
+ f"Finished with - Board: {self.name}, page {i + 1} of {total_pages}"
103
+ )
boards/cli.py ADDED
@@ -0,0 +1,104 @@
1
+ import time
2
+ from datetime import date
3
+
4
+ from pixBoards.boardmakers import (
5
+ boardsForImglist,
6
+ randomBoard,
7
+ standardBoards,
8
+ uploadBoards,
9
+ )
10
+ from pixBoards.log_utils import setup_logger
11
+
12
+ logger = setup_logger(__name__)
13
+
14
+
15
+ from pixBoards.arguments import args
16
+ from pixBoards.config_loader import config, outputDir
17
+ from pixBoards.db import create_boards_table, create_conn
18
+
19
+
20
+ def main():
21
+
22
+ start_time = time.time()
23
+ today = date.today()
24
+ conn = create_conn()
25
+ logger.info(f"Today is {today}, Starting ...")
26
+
27
+ if args.saveBoards:
28
+ create_boards_table(conn)
29
+
30
+ paginate = config.get("paginate", True) is True
31
+ boards = []
32
+
33
+ # Handle imagelist mode
34
+ if args.useLists or args.imageLists:
35
+ usingLists = True
36
+ imgList_List = (
37
+ args.imageLists if args.imageLists else config.get("imageLists", [])
38
+ )
39
+ boards.extend(boardsForImglist(imgList_List, outputDir, paginate))
40
+
41
+ if input("Do you want to include local images as well? (y/N)") == "y":
42
+ usingLists = False
43
+ else:
44
+ usingLists = False
45
+
46
+ # Handle upload
47
+ if args.upload:
48
+ logger.info("Upload case")
49
+ upload = True
50
+ else:
51
+ upload = False
52
+
53
+ if args.dir:
54
+ directories = [args.dir]
55
+ logger.debug("Using --dir → %s", directories)
56
+ elif config.get("directories"):
57
+ directories = config["directories"]
58
+ logger.debug(f"Using config.directories → %s", directories)
59
+
60
+ # board generation standar case
61
+ if not usingLists:
62
+ if upload:
63
+ boards.extend(uploadBoards(directories, outputDir, paginate, upload=True))
64
+ else:
65
+ boards.extend(
66
+ standardBoards(directories, outputDir, paginate, upload=False)
67
+ )
68
+
69
+ if args.random:
70
+ rancount = args.random
71
+
72
+ # for random case
73
+ if args.random:
74
+ boards.append(randomBoard(boards, rancount, outputDir, paginate, upload))
75
+
76
+ from pixBoards.nest_boards import assign_nested_boards
77
+
78
+ root_boards = assign_nested_boards(boards)
79
+ logger.debug(root_boards)
80
+
81
+ # Group boards by output directory and create output
82
+ logger.info(f"Total boards to generate HTML for: {len(boards)}")
83
+ from pixBoards.filemaking import create_output_files
84
+
85
+ create_output_files(root_boards, boards, conn)
86
+
87
+ # Print nested board tree
88
+ def print_board_tree(boards, depth=0):
89
+ for b in boards:
90
+ print(" " * depth + f"- {b.name}")
91
+ print_board_tree(b.nested_boards, depth + 1)
92
+
93
+ print("Boards structure - ")
94
+ print_board_tree(root_boards)
95
+
96
+ logger.debug(root_boards)
97
+ print(f"browse boards at - {outputDir}")
98
+
99
+ elapsed_time = time.time() - start_time
100
+ logger.info(f"Finished in {elapsed_time:.2f} seconds.")
101
+
102
+
103
+ if __name__ == "__main__":
104
+ main()
@@ -0,0 +1,32 @@
1
+ import os
2
+
3
+ import yaml
4
+
5
+ from pixBoards.arguments import args
6
+
7
+
8
+ def load_config(yml_path):
9
+ with open(yml_path, "r", encoding="utf-8") as f:
10
+ return yaml.safe_load(f)
11
+
12
+
13
+ if args.config:
14
+ configFile = args.config
15
+ else:
16
+ configFile = "config.yml"
17
+ config = load_config(configFile)
18
+ config["col_count"] = args.col if args.col else config.get("col_count", [])
19
+ config["margin"] = args.margin if args.margin else config.get("margin", [])
20
+
21
+ masterDir = config["masterDir"]
22
+ if args.config:
23
+ masterDir = os.path.join(os.path.dirname(masterDir), os.path.basename(configFile))
24
+
25
+ suffix = ""
26
+
27
+ if args.upload:
28
+ suffix = "_upload"
29
+ elif args.imageLists:
30
+ suffix = "_imglist"
31
+
32
+ outputDir = masterDir + suffix