pixBoards 0.2.6__tar.gz

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.
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.1
2
+ Name: pixBoards
3
+ Version: 0.2.6
4
+ Description-Content-Type: text/markdown
5
+
6
+ # pixBoards
7
+
8
+ not changing the repo name due to dependency issues. this repo will be archived soon.
9
+
10
+ Gui has not been set up yet. Don't try to run the gui.py
11
+
12
+ first, rename the config_example.yml to config.yml. or start afresh, your choice.
13
+
14
+ if you wish to upload to imgchest and use those links instead, use `--upload`
15
+
16
+ If it is the first time you are uploading, you will have to install postgresql first if not already installed.
17
+
18
+ ### install
19
+
20
+ you can install the pixBoards package from PyPi
21
+
22
+ `pip install pixBoards`
23
+
24
+ or clone the repo.
25
+
26
+ `git clone https://github.com/flynnsharwood/boards_v2.git`
27
+
28
+ ### First time upload
29
+ If it is the first time you are uploading, you will have to install postgresql first if not already installed.
30
+
31
+ Also, if you have a LOT of files to upload for the first time, go to the uploader folder. [repo link](https://github.com/flynnsharwood/imgUploader)
32
+
33
+ 1. set up the directories list in config.yml
34
+ 1. run listFiles.py. it will create a file named "MediaFiles.py"
35
+ 2. now run calc_hex.py
36
+ 3. run fileListUpload.py
37
+
38
+ fileListUpload basically uploads in batches of 20, unlike the original script where it uploads each image individually. This will upload and cache the links and hashes to postgress db
39
+
40
+ ### Usage
41
+ simply use the binary file provided `boards.exe`
42
+
43
+ Or do `python3 cli.py` or `python3 __main__.py`
44
+
45
+ flags you might use
46
+
47
+ `--upload` ensure all files are being uploaded. If you have pictures with the same filenames in different folders, you might need to fix this.
48
+
49
+ `--gitPush` this will push your created html files to a github repo. set up your repo to trigger a gh_pages deployment every push.
50
+
51
+ `--config` change the config file being used
52
+
53
+
54
+ here is a link to an example board - [https://flynnsharwood.github.io/exampleBoard/index.html](https://flynnsharwood.github.io/exampleBoard/index.html)
55
+
56
+ ---
57
+
58
+ ## screenshots
59
+
60
+ example of index file
61
+ ![img1](meta/image.png)
62
+
63
+
64
+ example of image board
65
+ ![img2](meta/image-1.png)
@@ -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()
@@ -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()
@@ -0,0 +1,249 @@
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,
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
+
98
+ rel = Path(root).relative_to(os.path.dirname(src_dir))
99
+
100
+ board_name = str(rel).replace(os.sep, "_~")
101
+ output_path = outputDir # everything writes into this one folder
102
+ # collect local files
103
+ local_files = [
104
+ Path(root) / f
105
+ for f in sorted(files)
106
+ if f.lower().endswith(media_extensions)
107
+ ]
108
+ if not local_files:
109
+ logger.debug(f"No media in {root}, creating empty board.")
110
+ b = board(
111
+ name=board_name,
112
+ output_file_loc=str(outputDir),
113
+ image_paths=[],
114
+ paginate=paginate,
115
+ images_per_page=(config["page_size"] if paginate else 10000),
116
+ upload=upload,
117
+ dummy_status=True,
118
+ # outputDir=outputDir
119
+ )
120
+ else:
121
+ # create a Board object and paginate it
122
+ b = board(
123
+ name=board_name,
124
+ output_file_loc=str(output_path),
125
+ image_paths=image_paths,
126
+ paginate=paginate,
127
+ images_per_page=(config["page_size"] if paginate else 10000),
128
+ upload=upload,
129
+ dummy_status=False,
130
+ )
131
+
132
+ b.paginate_board()
133
+ boards.append(b)
134
+
135
+ logger.debug(f"Board created: {board_name} ({len(image_paths)} images)")
136
+
137
+ return boards
138
+
139
+
140
+ def uploadBoards(directories, outputDir, paginate, upload=True):
141
+ def connect_db():
142
+ return psycopg2.connect(
143
+ dbname="boards",
144
+ user="postgres",
145
+ password="password",
146
+ host="localhost",
147
+ )
148
+
149
+ conn = connect_db()
150
+ boards = []
151
+ outputDir = Path(outputDir)
152
+ outputDir.mkdir(parents=True, exist_ok=True)
153
+
154
+ media_extensions = (
155
+ ".jpg",
156
+ ".jpeg",
157
+ ".png",
158
+ ".gif",
159
+ ".bmp",
160
+ ".webp",
161
+ ".mp4",
162
+ ".avi",
163
+ ".webm",
164
+ )
165
+
166
+ for d in directories:
167
+ src_dir = Path(d)
168
+ if not src_dir.exists():
169
+ logger.warning(f"Skipping non-existent directory: {src_dir}")
170
+ continue
171
+
172
+ for root, _, files in os.walk(src_dir):
173
+ rel = Path(root).relative_to(os.path.dirname(src_dir))
174
+ board_name = (
175
+ src_dir.name if rel == Path(".") else str(rel).replace(os.sep, "_~")
176
+ )
177
+
178
+ local_files = [
179
+ Path(root) / f
180
+ for f in sorted(files)
181
+ if f.lower().endswith(media_extensions)
182
+ ]
183
+
184
+ if not local_files:
185
+ logger.debug(f"No media in {root}, creating empty board.")
186
+ boards.append(
187
+ board(
188
+ name=board_name,
189
+ output_file_loc=str(outputDir),
190
+ image_paths=[],
191
+ paginate=paginate,
192
+ images_per_page=(config["page_size"] if paginate else 10000),
193
+ upload=upload,
194
+ # outputDir=outputDir,
195
+ dummy_status=True,
196
+ )
197
+ )
198
+ continue
199
+
200
+ logger.debug(f"Uploading {len(local_files)} images from {root}…")
201
+ try:
202
+ http_links, hash_map = process_images(local_files, conn)
203
+ except Exception as e:
204
+ logger.error(f"Failed to upload images in {root}: {e}")
205
+ continue
206
+
207
+ b = board(
208
+ name=board_name,
209
+ output_file_loc=str(outputDir),
210
+ image_paths=http_links,
211
+ paginate=paginate,
212
+ images_per_page=(config["page_size"] if paginate else 10000),
213
+ upload=upload,
214
+ # outputDir=outputDir
215
+ )
216
+ b.link_hash_map = hash_map
217
+ b.paginate_board()
218
+ boards.append(b)
219
+ logger.debug(
220
+ f"Uploaded board created: {board_name} ({len(http_links)} images)"
221
+ )
222
+
223
+ conn.close()
224
+ return boards
225
+
226
+
227
+ def randomBoard(boards, count, outputDir, paginate, upload):
228
+ images = []
229
+ for b in boards:
230
+ images.extend(b.image_paths)
231
+
232
+ try:
233
+ ran_images = random.sample(images, count)
234
+ except:
235
+ random.shuffle(images)
236
+ ran_images = images
237
+
238
+ ranBoard = board(
239
+ name="randomised_set",
240
+ output_file_loc=outputDir,
241
+ image_paths=ran_images,
242
+ paginate=paginate,
243
+ upload=upload,
244
+ dummy_status=False,
245
+ )
246
+
247
+ ranBoard.paginate_board()
248
+
249
+ return ranBoard
@@ -0,0 +1,103 @@
1
+ import os
2
+ from datetime import date
3
+
4
+ from pixBoards.log_utils import setup_logger
5
+
6
+
7
+ import yaml
8
+
9
+ from pixBoards.arguments import args
10
+
11
+ # set up logger
12
+ today = date.today()
13
+ logger = setup_logger(__name__)
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
+ )
@@ -0,0 +1,105 @@
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
+ else: directories = []
60
+
61
+ # board generation standar case
62
+ if directories and not usingLists:
63
+ if upload:
64
+ boards.extend(uploadBoards(directories, outputDir, paginate, upload=True))
65
+ else:
66
+ boards.extend(
67
+ standardBoards(directories, outputDir, paginate, upload=False)
68
+ )
69
+
70
+ if args.random:
71
+ rancount = args.random
72
+
73
+ # for random case
74
+ if args.random:
75
+ boards.append(randomBoard(boards, rancount, outputDir, paginate, upload))
76
+
77
+ from pixBoards.nest_boards import assign_nested_boards
78
+
79
+ root_boards = assign_nested_boards(boards)
80
+ logger.debug(root_boards)
81
+
82
+ # Group boards by output directory and create output
83
+ logger.info(f"Total boards to generate HTML for: {len(boards)}")
84
+ from pixBoards.filemaking import create_output_files
85
+
86
+ create_output_files(root_boards, boards, conn)
87
+
88
+ # Print nested board tree
89
+ def print_board_tree(boards, depth=0):
90
+ for b in boards:
91
+ print(" " * depth + f"- {b.name}")
92
+ print_board_tree(b.nested_boards, depth + 1)
93
+
94
+ print("Boards structure - ")
95
+ print_board_tree(root_boards)
96
+
97
+ logger.debug(root_boards)
98
+ print(f"browse boards at - {outputDir}")
99
+
100
+ elapsed_time = time.time() - start_time
101
+ logger.info(f"Finished in {elapsed_time:.2f} seconds.")
102
+
103
+
104
+ if __name__ == "__main__":
105
+ 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.splitext(os.path.basename(configFile))[0])
24
+
25
+ suffix = ""
26
+
27
+ if args.upload:
28
+ suffix = "_upload"
29
+ elif args.imageLists or args.useLists:
30
+ suffix = "_imglist"
31
+
32
+ outputDir = masterDir + suffix