Spaces:
Sleeping
Sleeping
drakosfire
commited on
Merge damn you!
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +4 -0
- .gitignore +4 -0
- Dockerfile +40 -0
- LICENSE +21 -0
- MerchanBot CLI/LICENSE +21 -0
- MerchanBot CLI/README.md +2 -0
- MerchanBot CLI/card_generator.py +109 -0
- MerchanBot CLI/image_gen.py +50 -0
- MerchanBot CLI/img2img.py +77 -0
- MerchanBot CLI/inventory.py +52 -0
- MerchanBot CLI/item_dict_gen.py +329 -0
- MerchanBot CLI/main.py +25 -0
- MerchanBot CLI/render_card_text.py +102 -0
- MerchanBot CLI/user_input.py +85 -0
- MerchanBot CLI/utilities.py +40 -0
- README.md +5 -0
- __pycache__/card_generator.cpython-310.pyc +0 -0
- __pycache__/image_gen.cpython-310.pyc +0 -0
- __pycache__/img2img.cpython-310.pyc +0 -0
- __pycache__/inventory.cpython-310.pyc +0 -0
- __pycache__/item_dict_gen.cpython-310.pyc +0 -0
- __pycache__/main.cpython-310.pyc +0 -0
- __pycache__/render_card_text.cpython-310.pyc +0 -0
- __pycache__/template_builder.cpython-310.pyc +0 -0
- __pycache__/user_input.cpython-310.pyc +0 -0
- __pycache__/utilities.cpython-310.pyc +0 -0
- card_generator.py +124 -0
- card_parts/Common.png +3 -0
- card_parts/Legendary.png +3 -0
- card_parts/Rare.png +3 -0
- card_parts/Sizzek Sticker.png +3 -0
- card_parts/Uncommon.png +3 -0
- card_parts/Value_box_transparent.png +3 -0
- card_parts/Very Rare.png +3 -0
- card_parts/white-fill-title-detail-value-transparent.png +3 -0
- fonts/Balgruf.ttf +0 -0
- fonts/BalgrufItalic.ttf +0 -0
- fonts/Goudy Medieval Medieval.ttf +0 -0
- fonts/balgruf-font/Balgruf.ttf +0 -0
- fonts/balgruf-font/BalgrufItalic.ttf +0 -0
- fonts/balgruf-font/info.txt +2 -0
- fonts/balgruf-font/misc/Balgruf-31cd.woff2 +0 -0
- fonts/balgruf-font/misc/Balgruf-d256.woff +0 -0
- fonts/balgruf-font/misc/Balgruf_Italic-52d6.woff +0 -0
- fonts/balgruf-font/misc/Balgruf_Italic-e184.woff2 +0 -0
- img2img.py +77 -0
- inventory.py +52 -0
- item_dict_gen.py +371 -0
- main.py +330 -0
- render_card_text.py +97 -0
.gitattributes
CHANGED
@@ -1,3 +1,4 @@
|
|
|
|
1 |
*.7z filter=lfs diff=lfs merge=lfs -text
|
2 |
*.arrow filter=lfs diff=lfs merge=lfs -text
|
3 |
*.bin filter=lfs diff=lfs merge=lfs -text
|
@@ -33,3 +34,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
1 |
+
<<<<<<< HEAD
|
2 |
*.7z filter=lfs diff=lfs merge=lfs -text
|
3 |
*.arrow filter=lfs diff=lfs merge=lfs -text
|
4 |
*.bin filter=lfs diff=lfs merge=lfs -text
|
|
|
34 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
35 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
36 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
37 |
+
=======
|
38 |
+
*.png filter=lfs diff=lfs merge=lfs -text
|
39 |
+
>>>>>>> master
|
.gitignore
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
output/
|
2 |
+
image_temp/
|
3 |
+
MerchantBot CLI/
|
4 |
+
seed_images
|
Dockerfile
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Stage 1: Build Cuda toolkit
|
2 |
+
FROM drakosfire/cuda-base:latest as base-layer
|
3 |
+
|
4 |
+
# Llama.cpp requires the ENV variable be set to signal the CUDA build and be built with the CMAKE variables from pip for python use
|
5 |
+
ENV LLAMA_CUBLAS=1
|
6 |
+
RUN apt-get update && \
|
7 |
+
apt-get install -y python3 python3-pip python3-venv && \
|
8 |
+
pip install gradio && \
|
9 |
+
CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama-cpp-python && \
|
10 |
+
pip install pillow && \
|
11 |
+
pip install diffusers && \
|
12 |
+
pip install accelerate && \
|
13 |
+
pip install transformers && \
|
14 |
+
pip install peft
|
15 |
+
|
16 |
+
FROM base-layer as final-layer
|
17 |
+
|
18 |
+
RUN useradd -m -u 1000 user
|
19 |
+
|
20 |
+
# mkdir -p /home/user/.cache && \
|
21 |
+
# chmod 777 /home/user/.cache && \
|
22 |
+
# chown -R user:user /home/user/app/
|
23 |
+
# Set environment variables for copied builds of cuda and flash-attn in /venv
|
24 |
+
|
25 |
+
|
26 |
+
ENV PATH=/usr/local/cuda-12.4/bin:/venv/bin:${PATH}
|
27 |
+
ENV LD_LIBRARY_PATH=/usr/local/cuda-12.4/lib64:${LD_LIBRARY_PATH}
|
28 |
+
|
29 |
+
ENV VIRTUAL_ENV=/venv
|
30 |
+
RUN python3 -m venv $VIRTUAL_ENV
|
31 |
+
ENV PATH="$VIRTUAL_ENV/bin:$PATH"
|
32 |
+
# Set working directory and user
|
33 |
+
WORKDIR /home/user/app
|
34 |
+
|
35 |
+
USER user
|
36 |
+
|
37 |
+
# Set the entrypoint
|
38 |
+
EXPOSE 8000
|
39 |
+
|
40 |
+
ENTRYPOINT ["python", "main.py"]
|
LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2024 Drakosfire
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
MerchanBot CLI/LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2024 Drakosfire
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
MerchanBot CLI/README.md
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
# CardGenerator
|
2 |
+
Takes user input and generates a collectible card with custom or LLM generated text and image generation
|
MerchanBot CLI/card_generator.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import render_card_text as rend
|
2 |
+
import inventory as inv
|
3 |
+
from PIL import Image
|
4 |
+
import utilities as u
|
5 |
+
import os
|
6 |
+
from PIL import ImageFilter
|
7 |
+
|
8 |
+
|
9 |
+
def save_image(image,item_key):
|
10 |
+
image.save(f"{item_key['Name']}.png")
|
11 |
+
|
12 |
+
|
13 |
+
# Import Inventory
|
14 |
+
#shop_inventory = inv.inventory
|
15 |
+
#purchased_item_key = shop_inventory['Shortsword']
|
16 |
+
#border_path = './card_templates/Shining Sunset Border.png'
|
17 |
+
|
18 |
+
sticker_path_dictionary = {'Default': './card_parts/Sizzek Sticker.png','Common': './card_parts/Common.png', 'Uncommon': './card_parts/Uncommon.png','Rare': './card_parts/Rare.png','Very Rare':'./card_parts/Very Rare.png','Legendary':'./card_parts/Legendary.png'}
|
19 |
+
blank_overlay_path = "./card_parts/white-fill-title-detail-value-transparent.png"
|
20 |
+
value_overlay_path = "./card_parts/Value_box_transparent.png"
|
21 |
+
test_item = {'Name': 'Pustulent Raspberry', 'Type': 'Fruit', 'Value': '1 cp', 'Properties': ['Unusual Appearance', 'Rare Taste'], 'Weight': '0.2 lb', 'Description': 'This small fruit has a pustulent appearance, with bumps and irregular shapes covering its surface. Its vibrant colors and strange texture make it an oddity among other fruits.', 'Quote': 'A fruit that defies expectations, as sweet and sour as life itself.', 'SD Prompt': 'A small fruit with vibrant colors and irregular shapes, bumps covering its surface.'}
|
22 |
+
|
23 |
+
# Function that takes in an image path and a dictionary and uses the values to print onto a card.
|
24 |
+
def paste_image_and_resize(base_image,sticker_path, x_position, y_position,img_width, img_height, purchased_item_key = None):
|
25 |
+
# Load the image to paste
|
26 |
+
|
27 |
+
if purchased_item_key:
|
28 |
+
if sticker_path[purchased_item_key]:
|
29 |
+
sticker_path = sticker_path[purchased_item_key]
|
30 |
+
else: sticker_path = sticker_path['Default']
|
31 |
+
|
32 |
+
|
33 |
+
image_to_paste = Image.open(sticker_path)
|
34 |
+
|
35 |
+
# Define the new size (scale) for the image you're pasting
|
36 |
+
|
37 |
+
new_size = (img_width, img_height)
|
38 |
+
|
39 |
+
# Resize the image to the new size
|
40 |
+
image_to_paste_resized = image_to_paste.resize(new_size)
|
41 |
+
|
42 |
+
# Specify the top-left corner where the resized image will be pasted
|
43 |
+
paste_position = (x_position, y_position) # Replace x and y with the coordinates
|
44 |
+
|
45 |
+
# Paste the resized image onto the base image
|
46 |
+
base_image.paste(image_to_paste_resized, paste_position, image_to_paste_resized)
|
47 |
+
|
48 |
+
def render_text_on_card(image_path, purchased_item_key) :
|
49 |
+
# Card Properties
|
50 |
+
print(list(purchased_item_key.keys()))
|
51 |
+
output_image_path = f"./{purchased_item_key['Name']}.png"
|
52 |
+
print(f"Saving image to {output_image_path}")
|
53 |
+
font_path = "./fonts/Balgruf.ttf"
|
54 |
+
italics_font_path = './fonts/BalgrufItalic.ttf'
|
55 |
+
initial_font_size = 50
|
56 |
+
|
57 |
+
# Title Properties
|
58 |
+
title_center_position = (395, 55)
|
59 |
+
title_area_width = 600 # Maximum width of the text box
|
60 |
+
title_area_height = 60 # Maximum height of the text box
|
61 |
+
|
62 |
+
# Type box properties
|
63 |
+
type_center_position = (384, 540)
|
64 |
+
type_area_width = 600
|
65 |
+
type_area_height = 50
|
66 |
+
type_text = purchased_item_key['Type']
|
67 |
+
if 'Weight' in list(purchased_item_key.keys()) :
|
68 |
+
type_text = type_text + ' '+ purchased_item_key['Weight']
|
69 |
+
|
70 |
+
if 'Damage' in list(purchased_item_key.keys()) :
|
71 |
+
type_text = type_text + ' '+ purchased_item_key['Damage']
|
72 |
+
|
73 |
+
# Description box properties
|
74 |
+
description_position = (105, 630)
|
75 |
+
description_area_width = 590
|
76 |
+
description_area_height = 215
|
77 |
+
|
78 |
+
# Value box properties (This is good, do not change unless underlying textbox layout is changing)
|
79 |
+
value_position = (660,905)
|
80 |
+
value_area_width = 125
|
81 |
+
value_area_height = 50
|
82 |
+
|
83 |
+
# Quote test properties
|
84 |
+
quote_position = (110,885)
|
85 |
+
quote_area_width = 470
|
86 |
+
quote_area_height = 60
|
87 |
+
|
88 |
+
# open image and render text
|
89 |
+
image = Image.open(image_path)
|
90 |
+
#paste_image_and_resize(image, blank_overlay_path,x_position= 0,y_position=0, img_width= 768, img_height= 1024)
|
91 |
+
image = rend.render_text_with_dynamic_spacing(image, purchased_item_key['Name'], title_center_position, title_area_width, title_area_height,font_path,initial_font_size)
|
92 |
+
|
93 |
+
image = rend.render_text_with_dynamic_spacing(image,type_text , type_center_position, type_area_width, type_area_height,font_path,initial_font_size)
|
94 |
+
image = rend.render_text_with_dynamic_spacing(image, '', description_position, description_area_width, description_area_height,font_path,initial_font_size,purchased_item_key, description = True)
|
95 |
+
paste_image_and_resize(image, value_overlay_path,x_position= 0,y_position=0, img_width= 768, img_height= 1024)
|
96 |
+
image = rend.render_text_with_dynamic_spacing(image, purchased_item_key['Value'], value_position, value_area_width, value_area_height,font_path,initial_font_size)
|
97 |
+
image = rend.render_text_with_dynamic_spacing(image, purchased_item_key['Quote'], quote_position, quote_area_width, quote_area_height,italics_font_path,initial_font_size, quote = True)
|
98 |
+
#Paste Sizzek Sticker
|
99 |
+
paste_image_and_resize(image, sticker_path_dictionary,x_position= 0,y_position=909, img_width= 115, img_height= 115, purchased_item_key= purchased_item_key['Rarity'])
|
100 |
+
#save_image(image, purchased_item_key)
|
101 |
+
image = image.filter(ImageFilter.GaussianBlur(.5))
|
102 |
+
image = image.save(f"./output/{purchased_item_key['Name']}.png")
|
103 |
+
|
104 |
+
|
105 |
+
#render_text_on_card('./card_templates/Shining Sunset Border.png',test_item )
|
106 |
+
|
107 |
+
|
108 |
+
|
109 |
+
|
MerchanBot CLI/image_gen.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#This independent from streamlit runs full speed ~ 5it/s /w StableDiffusionXLPipeline
|
2 |
+
from diffusers import StableDiffusionXLPipeline, StableDiffusionPipeline
|
3 |
+
import torch
|
4 |
+
import time
|
5 |
+
import inventory as inv
|
6 |
+
import utilities as u
|
7 |
+
|
8 |
+
start_time = time.time()
|
9 |
+
card_pre_prompt = " blank magic card,high resolution, detailed high quality intricate border, decorated textbox, high quality magnum opus cgi drawing of"
|
10 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
11 |
+
image_list = []
|
12 |
+
item = inv.inventory['Shortsword']
|
13 |
+
def generate_image(num_img, prompt, item) :
|
14 |
+
prompt = card_pre_prompt + prompt
|
15 |
+
print(prompt)
|
16 |
+
model_path = ("../models/stable-diffusion/SDXLFaetastic_v20.safetensors")
|
17 |
+
lora_path = ("../models/stable-diffusion/Loras/blank-card-template.safetensors")
|
18 |
+
pipe = StableDiffusionXLPipeline.from_single_file(model_path,
|
19 |
+
custom_pipeline="low_stable_diffusion",
|
20 |
+
torch_dtype=torch.float16,
|
21 |
+
variant="fp16" ).to("cuda")
|
22 |
+
pipe.load_lora_weights(lora_path)
|
23 |
+
pipe.enable_vae_slicing()
|
24 |
+
|
25 |
+
|
26 |
+
for x in range(num_img):
|
27 |
+
img_start = time.time()
|
28 |
+
image = pipe(prompt=prompt,num_inference_steps=50, height = 1024, width = 768).images[0]
|
29 |
+
image = image.save(str(x) + f"{item}.png")
|
30 |
+
img_time = time.time() - img_start
|
31 |
+
img_its = 50/img_time
|
32 |
+
print(f"image gen time = {img_time} and {img_its} it/s")
|
33 |
+
print(f"Memory after image {x} = {torch.cuda.memory_allocated()}")
|
34 |
+
image_path = str(os.path.abspath(image))
|
35 |
+
# image_list.append(image_path)
|
36 |
+
del image
|
37 |
+
del pipe
|
38 |
+
u.reclaim_mem()
|
39 |
+
|
40 |
+
print(f"Memory after del {torch.cuda.memory_allocated()}")
|
41 |
+
print(image_list)
|
42 |
+
total_time = time.time() - start_time
|
43 |
+
|
44 |
+
print(f"Total Time to generate{x} images = {total_time} ")
|
45 |
+
return image_path
|
46 |
+
|
47 |
+
|
48 |
+
|
49 |
+
|
50 |
+
|
MerchanBot CLI/img2img.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from diffusers import StableDiffusionXLPipeline, StableDiffusionXLImg2ImgPipeline
|
2 |
+
from diffusers.utils import load_image
|
3 |
+
import torch
|
4 |
+
import time
|
5 |
+
import utilities as u
|
6 |
+
import card_generator as card
|
7 |
+
from PIL import Image
|
8 |
+
|
9 |
+
start_time = time.time()
|
10 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
11 |
+
model_path = ("../../models/stable-diffusion/SDXLFaetastic_v24.safetensors")
|
12 |
+
lora_path = "../../models/stable-diffusion/Loras/blank-card-template-5.safetensors"
|
13 |
+
detail_lora_path = "../../models/stable-diffusion/Loras/add-detail-xl.safetensors"
|
14 |
+
mimic_lora_path = "../../models/stable-diffusion/Loras/EnvyMimicXL01.safetensors"
|
15 |
+
|
16 |
+
card_pre_prompt = " blank magic card,high resolution, detailed intricate high quality border, textbox, high quality magnum opus drawing of a "
|
17 |
+
negative_prompts = "text, words, numbers, letters"
|
18 |
+
image_list = []
|
19 |
+
|
20 |
+
def generate_image(num_img, prompt, item, user_input_template, mimic = None) :
|
21 |
+
prompt = card_pre_prompt + item + ' ' + prompt
|
22 |
+
print(prompt)
|
23 |
+
image_path = f"card_templates/{user_input_template}"
|
24 |
+
init_image = load_image(image_path).convert("RGB")
|
25 |
+
|
26 |
+
pipe = StableDiffusionXLImg2ImgPipeline.from_single_file(model_path,
|
27 |
+
custom_pipeline="low_stable_diffusion",
|
28 |
+
torch_dtype=torch.float16,
|
29 |
+
variant="fp16",
|
30 |
+
local_files_only = True).to("cuda")
|
31 |
+
# Load LoRAs for controlling image
|
32 |
+
pipe.load_lora_weights(lora_path, weight_name = "blank-card-template-5.safetensors",adapter_name = 'blank-card-template')
|
33 |
+
pipe.load_lora_weights(detail_lora_path, weight_name = "add-detail-xl.safetensors", adapter_name = "add-detail-xl")
|
34 |
+
|
35 |
+
# If mimic keyword has been detected, load the mimic LoRA and set adapter values
|
36 |
+
if mimic:
|
37 |
+
pipe.load_lora_weights(mimic_lora_path, weight_name = "EnvyMimicXL01.safetensors", adapter_name = "EnvyMimicXL")
|
38 |
+
pipe.set_adapters(['blank-card-template', "add-detail-xl", "EnvyMimicXL"], adapter_weights = [0.9,0.9,1.0])
|
39 |
+
else :
|
40 |
+
pipe.set_adapters(['blank-card-template', "add-detail-xl"], adapter_weights = [0.9,0.9])
|
41 |
+
pipe.enable_vae_slicing()
|
42 |
+
|
43 |
+
for x in range(num_img):
|
44 |
+
img_start = time.time()
|
45 |
+
image = pipe(prompt=prompt,
|
46 |
+
strength = .9,
|
47 |
+
guidance_scale = 5,
|
48 |
+
image= init_image,
|
49 |
+
negative_promt = negative_prompts,
|
50 |
+
num_inference_steps=50,
|
51 |
+
height = 1024, width = 768).images[0]
|
52 |
+
image = image.save(str(x) + f"{item}.png")
|
53 |
+
output_image_path = str(x) + f"{item}.png"
|
54 |
+
img_time = time.time() - img_start
|
55 |
+
img_its = 50/img_time
|
56 |
+
print(f"image gen time = {img_time} and {img_its} it/s")
|
57 |
+
print(f"Memory after image {x} = {torch.cuda.memory_allocated()}")
|
58 |
+
|
59 |
+
image_list.append(output_image_path)
|
60 |
+
|
61 |
+
# Delete the image variable to keep VRAM open to load the LLM
|
62 |
+
del image
|
63 |
+
print(f"Memory after del {torch.cuda.memory_allocated()}")
|
64 |
+
print(image_list)
|
65 |
+
total_time = time.time() - start_time
|
66 |
+
|
67 |
+
print(f"Total Time to generate{x} images = {total_time} ")
|
68 |
+
del pipe
|
69 |
+
u.reclaim_mem()
|
70 |
+
return image_list
|
71 |
+
|
72 |
+
|
73 |
+
|
74 |
+
|
75 |
+
|
76 |
+
|
77 |
+
|
MerchanBot CLI/inventory.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
inventory = {
|
4 |
+
'Shortsword': {
|
5 |
+
'Name' : 'Shortsword',
|
6 |
+
'Type' : 'Melee Weapon (martial, sword)',
|
7 |
+
'Value': '10 gp',
|
8 |
+
'Properties': ['Finesse, Light '],
|
9 |
+
'Damage': '1d6 + proficiency + Dex or Str',
|
10 |
+
'Weight': '2 lb',
|
11 |
+
'Description': 'Gleaming with a modest radiance, the shortsword boasts a keen edge and a leather-wrapped hilt, promising both grace and reliability in the heat of combat.',
|
12 |
+
'Quote': 'In the heart of battle, the shortsword proves not just a weapon, but a steadfast companion, whispering paths of valor to those who wield it.',
|
13 |
+
'SD Description' : 'high resolution, blank magic card,detailed high quality intricate border, decorated textbox, high quality magnum opus cgi drawing of a steel shortsword'
|
14 |
+
},
|
15 |
+
|
16 |
+
'Health Potion': {
|
17 |
+
'Name' : 'Health Portion',
|
18 |
+
'Type' : 'Potion',
|
19 |
+
'Value': '50 gp',
|
20 |
+
'Properties': ['Quafable', 'Restores 1d4 + 2 HP upon consumption'],
|
21 |
+
'Weight': '0.5 lb',
|
22 |
+
'Description': 'Contained within this small vial is a crimson liquid that sparkles when shaken, a life-saving elixir for those who brave the unknown.',
|
23 |
+
'Quote': 'To the weary, a drop of hope; to the fallen, a chance to stand once more.'
|
24 |
+
},
|
25 |
+
|
26 |
+
|
27 |
+
'Wooden Shield': {
|
28 |
+
'Name' : 'Wooden Shield',
|
29 |
+
'Type' : 'Armor, Shield',
|
30 |
+
'Value': '15 gp',
|
31 |
+
'Properties': ['+2 AC'],
|
32 |
+
'Weight': '6 lb',
|
33 |
+
'Description': 'Sturdy and reliable, this wooden shield is a simple yet effective defense against the blows of adversaries.',
|
34 |
+
'Quote': 'In the rhythm of battle, it dances - a barrier between life and defeat.'
|
35 |
+
},
|
36 |
+
|
37 |
+
'Magical Helmet': {
|
38 |
+
'Name' : 'Magical Helmet of Perception',
|
39 |
+
'Type' : 'Magical Item (armor, helmet)',
|
40 |
+
'Value': '120 gp',
|
41 |
+
'Properties': ['+ 1 to AC', 'Grants the wearer enhanced perception'],
|
42 |
+
'Weight': '3 lb',
|
43 |
+
'Description': 'Forged from mystic metals and enchanted with ancient spells, this helmet offers protection beyond the physical realm.',
|
44 |
+
'Quote': 'A crown not of royalty, but of unyielding vigilance, warding off the unseen threats that lurk in the shadows.'
|
45 |
+
}
|
46 |
+
}
|
47 |
+
|
48 |
+
{'id': 'cmpl-5b0ed6c7-2326-473f-8f11-32d3f079edc2',
|
49 |
+
'object': 'text_completion',
|
50 |
+
'created': 1709094107,
|
51 |
+
'model': '../models/starling-lm-7b-alpha.Q8_0.gguf',
|
52 |
+
'choices': [{'text': ' Here\'s an example of a structured inventory entry for a Mimic Treasure Chest as per your request:\n\n```python\n{\n \'Mimic Treasure Chest\': {\n \'Name\': \'Mimic Treasure Chest\',\n \'Type\': \'Trap\',\n \'Rarity\': \'Rare\',\n \'Value\': \'1000 gp\', \n \'Properties\': [\n \'Deceptively inviting\', \n \'Springs to life when interacted with\', \n \'Capable of attacking unwary adventurers\'\n ],\n \'Weight\': \'50 lb\', \n \'Description\': \'At first glance, this chest appears to be laden with treasure, beckoning to all who gaze upon it. However, it harbors a deadly secret: it is a Mimic, a cunning and dangerous creature that preys on the greed of adventurers. With its dark magic, it can perfectly imitate a treasure chest, only to reveal its true, monstrous form when approached. Those who seek to plunder its contents might find themselves in a fight for their lives.\',\n \'Quote\': \'"Beneath the guise of gold and riches lies a predator, waiting with bated breath for its next victim."\',\n \'SD Prompt\': \'A seemingly ordinary treasure chest that glimmers with promise. Upon closer inspection, sinister, almost living edges move with malice, revealing its true nature as a Mimic, ready to unleash fury on the unwary.\'\n }\n}\n```\n\nKeep in mind that mimics are typically found in dungeons and are known to take on the form of doors and chests. This example follows that theme while also providing information on the mimic\'s rarity, value, properties, and weight.', 'index': 0, 'logprobs': None, 'finish_reason': 'stop'}], 'usage': {'prompt_tokens': 4287, 'completion_tokens': 405, 'total_tokens': 4692}}
|
MerchanBot CLI/item_dict_gen.py
ADDED
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from llama_cpp import Llama
|
2 |
+
import ast
|
3 |
+
import gc
|
4 |
+
import torch
|
5 |
+
|
6 |
+
model_path = "../models/starling-lm-7b-alpha.Q8_0.gguf"
|
7 |
+
# Set gpu_layers to the number of layers to offload to GPU. Set to 0 if no GPU acceleration is available on your system.
|
8 |
+
|
9 |
+
|
10 |
+
# Simple inference example
|
11 |
+
def load_llm(user_input):
|
12 |
+
llm = Llama(
|
13 |
+
model_path=model_path,
|
14 |
+
n_ctx=8192, # The max sequence length to use - note that longer sequence lengths require much more resources
|
15 |
+
n_threads=8, # The number of CPU threads to use, tailor to your system and the resulting performance
|
16 |
+
n_gpu_layers=-1 # The number of layers to offload to GPU, if you have GPU acceleration available
|
17 |
+
)
|
18 |
+
return llm(
|
19 |
+
f"GPT4 User: {prompt_instructions} the item is {user_input}: <|end_of_turn|>GPT4 Assistant:", # Prompt
|
20 |
+
max_tokens=512, # Generate up to 512 tokens
|
21 |
+
stop=["</s>"], # Example stop token - not necessarily correct for this specific model! Please check before using.
|
22 |
+
echo=False # Whether to echo the prompt
|
23 |
+
)
|
24 |
+
|
25 |
+
def call_llm_and_cleanup(user_input):
|
26 |
+
# Call the LLM and store its output
|
27 |
+
llm_output = load_llm(user_input)
|
28 |
+
print(llm_output['choices'][0]['text'])
|
29 |
+
gc.collect()
|
30 |
+
if torch.cuda.is_available():
|
31 |
+
torch.cuda.empty_cache() # Clear VRAM allocated by PyTorch
|
32 |
+
|
33 |
+
# llm_output is still available for use here
|
34 |
+
|
35 |
+
return llm_output
|
36 |
+
|
37 |
+
def convert_to_dict(string):
|
38 |
+
# Evaluate if string is dictionary literal
|
39 |
+
try:
|
40 |
+
result = ast.literal_eval(string)
|
41 |
+
if isinstance(result, dict):
|
42 |
+
print("Item dictionary is valid")
|
43 |
+
return result
|
44 |
+
# If not, modify by attempting to add brackets to where they tend to fail to generate.
|
45 |
+
else:
|
46 |
+
modified_string = '{' + string
|
47 |
+
if isinstance(modified_string, dict):
|
48 |
+
return modified_string
|
49 |
+
modified_string = string + '}'
|
50 |
+
if isinstance(modified_string, dict):
|
51 |
+
return modified_string
|
52 |
+
modified_string = '{' + string + '}'
|
53 |
+
if isinstance(modified_string, dict):
|
54 |
+
return modified_string
|
55 |
+
except (ValueError, SyntaxError) :
|
56 |
+
print("Dictionary not valid")
|
57 |
+
return None
|
58 |
+
|
59 |
+
|
60 |
+
# Instructions past 4 are not time tested and may need to be removed.
|
61 |
+
### Meta prompted :
|
62 |
+
prompt_instructions = """ **Purpose**: Generate a structured inventory entry for a specific item as a hashmap. Follow the format provided in the examples below.
|
63 |
+
|
64 |
+
**Instructions**:
|
65 |
+
1. Replace `{item}` with the name of your item, enclosed in single quotes (e.g., `'Magic Wand'`).
|
66 |
+
2. Ensure your request is formatted as a hashmap. Do not add quotation marks around the dictionary's `Quote` value.
|
67 |
+
3. The quote should be strange and interesting and from the perspective of someone commenting on the impact of the {item} on their life
|
68 |
+
4. Value should be assigned as an integer of copper pieces (cp), silver pieces (sp), electrum pieces (ep), gold pieces (gp), and platinum pieces (pp). .
|
69 |
+
5. Use this table for reference on value :
|
70 |
+
1 cp 1 lb. of wheat
|
71 |
+
2 cp 1 lb. of flour or one chicken
|
72 |
+
5 cp 1 lb. of salt
|
73 |
+
1 sp 1 lb. of iron or 1 sq. yd. of canvas
|
74 |
+
5 sp 1 lb. of copper or 1 sq. yd. of cotton cloth
|
75 |
+
1 gp 1 lb. of ginger or one goat
|
76 |
+
2 gp 1 lb. of cinnamon or pepper, or one sheep
|
77 |
+
3 gp 1 lb. of cloves or one pig
|
78 |
+
5 gp 1 lb. of silver or 1 sq. yd. of linen
|
79 |
+
10 gp 1 sq. yd. of silk or one cow
|
80 |
+
15 gp 1 lb. of saffron or one ox
|
81 |
+
50 gp 1 lb. of gold
|
82 |
+
500 gp 1 lb. of platinum
|
83 |
+
|
84 |
+
6. Examples of Magical Scroll Value:
|
85 |
+
Common: 50-100 gp
|
86 |
+
Uncommon: 101-500 gp
|
87 |
+
Rare: 501-5000 gp
|
88 |
+
Very rare: 5001-50000 gp
|
89 |
+
Legendary: 50001+ gp
|
90 |
+
A scroll's rarity depends on the spell's level:
|
91 |
+
Cantrip-1: Common
|
92 |
+
2-3: Uncommon
|
93 |
+
4-5: Rare
|
94 |
+
6-8: Very rare
|
95 |
+
9: Legendary
|
96 |
+
|
97 |
+
7. Explanation of Mimics:
|
98 |
+
Mimics are shapeshifting predators able to take on the form of inanimate objects to lure creatures to their doom. In dungeons, these cunning creatures most often take the form of doors and chests, having learned that such forms attract a steady stream of prey.
|
99 |
+
Imitative Predators. Mimics can alter their outward texture to resemble wood, stone, and other basic materials, and they have evolved to assume the appearance of objects that other creatures are likely to come into contact with. A mimic in its altered form is nearly unrecognizable until potential prey blunders into its reach, whereupon the monster sprouts pseudopods and attacks.
|
100 |
+
When it changes shape, a mimic excretes an adhesive that helps it seize prey and weapons that touch it. The adhesive is absorbed when the mimic assumes its amorphous form and on parts the mimic uses to move itself.
|
101 |
+
Cunning Hunters. Mimics live and hunt alone, though they occasionally share their feeding grounds with other creatures. Although most mimics have only predatory intelligence, a rare few evolve greater cunning and the ability to carry on simple conversations in Common or Undercommon. Such mimics might allow safe passage through their domains or provide useful information in exchange for food.
|
102 |
+
|
103 |
+
8.
|
104 |
+
**Format Example**:
|
105 |
+
- **Dictionary Structure**:
|
106 |
+
|
107 |
+
{'{item}': {
|
108 |
+
'Name': '{item name}',
|
109 |
+
'Type': '{item type}',
|
110 |
+
'Rarity': '{item rarity},
|
111 |
+
'Value': '{item value}',
|
112 |
+
'Properties': ['{property1}', '{property2}', ...],
|
113 |
+
'Damage': '{damage formula} , 'damage type}',
|
114 |
+
'Weight': '{weight}',
|
115 |
+
'Description': '{item description}',
|
116 |
+
'Quote': '{item quote}',
|
117 |
+
'SD Prompt': '{special description for the item}'
|
118 |
+
} }
|
119 |
+
|
120 |
+
- **Input Placeholder**:
|
121 |
+
- `{item}`: Replace with the item name, ensuring it's wrapped in single quotes.
|
122 |
+
|
123 |
+
**Output Examples**:
|
124 |
+
1. Cloak of Whispering Shadows Entry:
|
125 |
+
|
126 |
+
{'Cloak of Whispering Shadows': {
|
127 |
+
'Name': 'Cloak of Whispering Shadows',
|
128 |
+
'Type': 'Cloak',
|
129 |
+
'Rarity': 'Very Rare',
|
130 |
+
'Value': '10000 gp',
|
131 |
+
'Properties': ['Grants invisibility in dim light or darkness','Allows communication with shadows for gathering information'],
|
132 |
+
'Weight': '1 lb',
|
133 |
+
'Description': 'A cloak woven from the essence of twilight, blending its wearer into the shadows. Whispers of the past and present linger in its folds, offering secrets to those who listen.',
|
134 |
+
'Quote': 'In the embrace of night, secrets surface in the silent whispers of the dark.',
|
135 |
+
'SD Prompt': ' decorated with shimmering threads that catch the light to mimic stars.'
|
136 |
+
} }
|
137 |
+
|
138 |
+
2. Health Potion Entry:
|
139 |
+
|
140 |
+
{'Health Potion': {
|
141 |
+
'Name' : 'Health Portion',
|
142 |
+
'Type' : 'Potion',
|
143 |
+
'Rarity' : 'Common',
|
144 |
+
'Value': '50 gp',
|
145 |
+
'Properties': ['Quafable', 'Restores 1d4 + 2 HP upon consumption'],
|
146 |
+
'Weight': '0.5 lb',
|
147 |
+
'Description': 'Contained within this small vial is a crimson liquid that sparkles when shaken, a life-saving elixir for those who brave the unknown.',
|
148 |
+
'Quote': 'To the weary, a drop of hope; to the fallen, a chance to stand once more.',
|
149 |
+
'SD Prompt' : ' high quality magnum opus drawing of a vial of bubling red liquid'
|
150 |
+
} }
|
151 |
+
|
152 |
+
3. Wooden Shield Entry:
|
153 |
+
|
154 |
+
{'Wooden Shield': {
|
155 |
+
'Name' : 'Wooden Shield',
|
156 |
+
'Type' : 'Armor, Shield',
|
157 |
+
'Rarity': 'Common',
|
158 |
+
'Value': '10 gp',
|
159 |
+
'Properties': ['+2 AC'],
|
160 |
+
'Weight': '6 lb',
|
161 |
+
'Description': 'Sturdy and reliable, this wooden shield is a simple yet effective defense against the blows of adversaries.',
|
162 |
+
'Quote': 'In the rhythm of battle, it dances - a barrier between life and defeat.',
|
163 |
+
'SD Prompt': ' high quality magnum opus drawing of a wooden shield strapped with iron and spikes'
|
164 |
+
} }
|
165 |
+
|
166 |
+
4. Magical Helmet of Perception Entry:
|
167 |
+
|
168 |
+
{'Magical Helmet': {
|
169 |
+
'Name' : 'Magical Helmet of Perception',
|
170 |
+
'Type' : 'Magical Item (armor, helmet)',
|
171 |
+
'Rarity': 'Very Rare',
|
172 |
+
'Value': '3000 gp',
|
173 |
+
'Properties': ['+ 1 to AC', 'Grants the wearer advantage on perception checks', '+5 to passive perception'],
|
174 |
+
'Weight': '3 lb',
|
175 |
+
'Description': 'Forged from mystic metals and enchanted with ancient spells, this helmet offers protection beyond the physical realm.',
|
176 |
+
'Quote': 'A crown not of royalty, but of unyielding vigilance, warding off the unseen threats that lurk in the shadows.',
|
177 |
+
'SD Prompt': 'high quality magnum opus drawing of an ancient elegant helm with a shimmer of magic'
|
178 |
+
} }
|
179 |
+
|
180 |
+
5. Longbow Entry:
|
181 |
+
|
182 |
+
{'Longbow': {
|
183 |
+
'Name': 'Longbow',
|
184 |
+
'Type': 'Ranged Weapon (martial, longbow)',
|
185 |
+
'Rarity': 'Common',
|
186 |
+
'Value': '50 gp',
|
187 |
+
'Properties': ['2-handed', 'Range 150/600', 'Loading'],
|
188 |
+
'Damage': '1d8 + Dex, piercing',
|
189 |
+
'Weight': '6 lb',
|
190 |
+
'Description': 'With a sleek and elegant design, this longbow is crafted for speed and precision, capable of striking down foes from a distance.',
|
191 |
+
'Quote': 'From the shadows it emerges, a silent whisper of steel that pierces the veil of darkness, bringing justice to those who dare to trespass.',
|
192 |
+
'SD Prompt' : 'high quality magnum opus drawing of a longbow with a quiver attached'
|
193 |
+
} }
|
194 |
+
|
195 |
+
|
196 |
+
6. Mace Entry:
|
197 |
+
|
198 |
+
{'Mace': {
|
199 |
+
'Name': 'Mace',
|
200 |
+
'Type': 'Melee Weapon (martial, bludgeoning)',
|
201 |
+
'Rarity': 'Common',
|
202 |
+
'Value': '25 gp', 'Properties': ['Bludgeoning', 'One-handed'],
|
203 |
+
'Damage': '1d6 + str, bludgeoning',
|
204 |
+
'Weight': '6 lb',
|
205 |
+
'Description': 'This mace is a fearsome sight, its head a heavy and menacing ball of metal designed to crush bone and break spirits.',
|
206 |
+
'Quote': 'With each swing, it sings a melody of pain and retribution, an anthem of justice to those who wield it.',
|
207 |
+
'SD Prompt': 'high quality magnum opus drawing of a mace with intricate detailing and an ominous presence'
|
208 |
+
} }
|
209 |
+
|
210 |
+
7. Flying Carpet Entry:
|
211 |
+
|
212 |
+
{'Flying Carpet': {
|
213 |
+
'Name': 'Flying Carpet',
|
214 |
+
'Type': 'Magical Item (transportation)',
|
215 |
+
'Rarity': 'Very Rare'
|
216 |
+
'Value': '12000 gp',
|
217 |
+
'Properties': ['Flying', 'Personal Flight', 'Up to 2 passengers', Speed : 60 ft],
|
218 |
+
'Weight': '50 lb',
|
219 |
+
'Description': 'This enchanted carpet whisks its riders through the skies, providing a swift and comfortable mode of transport across great distances.', 'Quote': 'Soar above the mundane, and embrace the winds of adventure with this magical gift from the heavens.',
|
220 |
+
'SD Prompt': 'high quality magnum opus drawing of an elegant flying carpet with intricate patterns and colors'
|
221 |
+
} }
|
222 |
+
|
223 |
+
8. Tome of Endless Stories Entry:
|
224 |
+
|
225 |
+
{'Tome of Endless Stories': {
|
226 |
+
'Name': 'Tome of Endless Stories',
|
227 |
+
'Type': 'Book',
|
228 |
+
'Rarity': 'Uncommon'
|
229 |
+
'Value': '500 gp',
|
230 |
+
'Properties': [
|
231 |
+
'Generates a new story or piece of lore each day',
|
232 |
+
'Reading a story grants insight or a hint towards solving a problem or puzzle'
|
233 |
+
],
|
234 |
+
'Weight': '3 lbs',
|
235 |
+
'Description': 'An ancient tome bound in leather that shifts colors like the sunset. Its pages are never-ending, filled with tales from worlds both known and undiscovered.',
|
236 |
+
'Quote': 'Within its pages lie the keys to a thousand worlds, each story a doorway to infinite possibilities.',
|
237 |
+
'SD Prompt': 'leather-bound with gold and silver inlay, pages appear aged but are incredibly durable, magical glyphs shimmer softly on the cover.'
|
238 |
+
} }
|
239 |
+
|
240 |
+
9. Ring of Miniature Summoning Entry:
|
241 |
+
|
242 |
+
{'Ring of Miniature Summoning': {
|
243 |
+
'Name': 'Ring of Miniature Summoning',
|
244 |
+
'Type': 'Ring',
|
245 |
+
'Rarity': 'Rare',
|
246 |
+
'Value': '1500 gp',
|
247 |
+
'Properties': ['Summons a miniature beast ally once per day', 'Beast follows commands and lasts for 1 hour', 'Choice of beast changes with each dawn'],
|
248 |
+
'Weight': '0 lb',
|
249 |
+
'Description': 'A delicate ring with a gem that shifts colors. When activated, it brings forth a small, loyal beast companion from the ether.',
|
250 |
+
'Quote': 'Not all companions walk beside us. Some are summoned from the depths of magic, small in size but vast in heart.',
|
251 |
+
'SD Prompt': 'gemstone with changing colors, essence of companionship and versatility.'
|
252 |
+
} }
|
253 |
+
|
254 |
+
|
255 |
+
10. Spoon of Tasting Entry:
|
256 |
+
|
257 |
+
{'Spoon of Tasting': {
|
258 |
+
'Name': 'Spoon of Tasting',
|
259 |
+
'Type': 'Spoon',
|
260 |
+
'Rarity': 'Uncommon',
|
261 |
+
'Value': '200 gp',
|
262 |
+
'Properties': ['When used to taste any dish, it can instantly tell you all the ingredients', 'Provides exaggerated compliments or critiques about the dish'],
|
263 |
+
'Weight': '0.2 lb',
|
264 |
+
'Description': 'A culinary critic’s dream or nightmare. This spoon doesn’t hold back its opinions on any dish it tastes.',
|
265 |
+
'Quote': 'A spoonful of sugar helps the criticism go down.',
|
266 |
+
'SD Prompt': 'Looks like an ordinary spoon, but with a mouth that speaks more than you’d expect.'
|
267 |
+
} }
|
268 |
+
|
269 |
+
11. Infinite Scroll Entry:
|
270 |
+
|
271 |
+
{'Infinite Scroll': {
|
272 |
+
'Name': 'Infinite Scroll',
|
273 |
+
'Type': 'Magical Scroll',
|
274 |
+
'Rarity': 'Legendary',
|
275 |
+
'Value': '25000',
|
276 |
+
'Properties': [
|
277 |
+
'Endlessly Extends with New Knowledge',
|
278 |
+
'Reveals Content Based on Reader’s Need or Desire',
|
279 |
+
'Cannot be Fully Transcribed'
|
280 |
+
],
|
281 |
+
'Weight': '0.5 lb',
|
282 |
+
'Description': 'This scroll appears to be a standard parchment at first glance. However, as one begins to read, it unrolls to reveal an ever-expanding tapestry of knowledge, lore, and spells that seems to have no end. The content of the scroll adapts to the reader’s current quest for knowledge or need, always offering just a bit more beyond what has been revealed.',
|
283 |
+
'Quote': 'In the pursuit of knowledge, the horizon is ever receding. So too is the content of this scroll, an endless journey within a parchment’s bounds.',
|
284 |
+
'SD Prompt': 'A seemingly ordinary scroll that extends indefinitely, '
|
285 |
+
} }
|
286 |
+
|
287 |
+
12. Mimic Treasure Chest Entry:
|
288 |
+
|
289 |
+
{'Mimic Treasure Chest': {
|
290 |
+
'Name': 'Mimic Treasure Chest',
|
291 |
+
'Type': 'Trap',
|
292 |
+
'Rarity': 'Rare',
|
293 |
+
'Value': '1000 gp', # Increased value reflects its dangerous and rare nature
|
294 |
+
'Properties': [
|
295 |
+
'Deceptively inviting',
|
296 |
+
'Springs to life when interacted with',
|
297 |
+
'Capable of attacking unwary adventurers'
|
298 |
+
],
|
299 |
+
'Weight': '50 lb', # Mimics are heavy due to their monstrous nature
|
300 |
+
'Description': 'At first glance, this chest appears to be laden with treasure, beckoning to all who gaze upon it. However, it harbors a deadly secret: it is a Mimic, a cunning and dangerous creature that preys on the greed of adventurers. With its dark magic, it can perfectly imitate a treasure chest, only to reveal its true, monstrous form when approached. Those who seek to plunder its contents might find themselves in a fight for their lives.',
|
301 |
+
'Quote': '"Beneath the guise of gold and riches lies a predator, waiting with bated breath for its next victim."',
|
302 |
+
'SD Prompt': 'A seemingly ordinary treasure chest that glimmers with promise. Upon closer inspection, sinister, almost living edges move with malice, revealing its true nature as a Mimic, ready to unleash fury on the unwary.'
|
303 |
+
} }
|
304 |
+
|
305 |
+
13. Hammer of Thunderbolts Entry:
|
306 |
+
|
307 |
+
{'Hammer of Thunderbolts': {
|
308 |
+
'Name': 'Hammer of Thunderbolts',
|
309 |
+
'Type': 'Melee Weapon (maul, bludgeoning)',
|
310 |
+
'Rarity': 'Legendary',
|
311 |
+
'Value': '16000',
|
312 |
+
'Properties': [
|
313 |
+
'requires attunement',
|
314 |
+
'Giant's Bane',
|
315 |
+
'must be wearing a belt of giant strength and gauntlets of ogre power',
|
316 |
+
'Str +4',
|
317 |
+
'Can excees 20 but not 30',
|
318 |
+
'20 against giant, DC 17 save against death',
|
319 |
+
'5 charges, expend 1 to make a range attack 20/60',
|
320 |
+
'ranged attack releases thunderclap on hit, DC 17 save against stunned 30 ft',
|
321 |
+
'regain 1d4+1 charges at dawn'
|
322 |
+
],
|
323 |
+
'Weight': 15 lb',
|
324 |
+
'Description': 'Forged by the gods and bound by the storms themselves, the Hammer of Thunderbolts is a weapon of unparalleled might. Its head is etched with ancient runes that glow with a fierce light whenever its power is called upon. This maul is not just a tool of destruction but a symbol of the indomitable force of nature, capable of leveling mountains and commanding the elements with each swing.',
|
325 |
+
'Quote': 'When the skies rage and the earth trembles, know that the Hammer of Thunderbolts has found its mark. It is not merely a weapon, but the embodiment of the storm\'s wrath wielded by those deemed worthy.',
|
326 |
+
'SD Prompt': 'It radiates with electric energy, its rune-etched head and storm-weathered leather grip symbolizing its dominion over storms. In its grasp, it pulses with the potential to summon the heavens' fury, embodying the tempest's raw power.'
|
327 |
+
} }
|
328 |
+
|
329 |
+
"""
|
MerchanBot CLI/main.py
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import item_dict_gen as igen
|
2 |
+
import img2img
|
3 |
+
import card_generator as card
|
4 |
+
import utilities as u
|
5 |
+
import ctypes
|
6 |
+
import user_input as uinput
|
7 |
+
import os
|
8 |
+
|
9 |
+
# This is a fix for the way that python doesn't release system memory back to the OS and it was leading to locking up the system
|
10 |
+
libc = ctypes.cdll.LoadLibrary("libc.so.6")
|
11 |
+
M_MMAP_THRESHOLD = -3
|
12 |
+
|
13 |
+
# Set malloc mmap threshold.
|
14 |
+
libc.mallopt(M_MMAP_THRESHOLD, 2**20)
|
15 |
+
|
16 |
+
uinput.prompt_user_input()
|
17 |
+
|
18 |
+
|
19 |
+
|
20 |
+
|
21 |
+
|
22 |
+
|
23 |
+
|
24 |
+
|
25 |
+
|
MerchanBot CLI/render_card_text.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image, ImageDraw, ImageFont
|
2 |
+
|
3 |
+
# Function for managing longer bodies of text and breaking into a list of lines to be printed based on input arguments
|
4 |
+
def split_text_into_lines(text, font, max_width, draw):
|
5 |
+
blocks = text.split('\n')
|
6 |
+
lines = []
|
7 |
+
for block in blocks:
|
8 |
+
words = block.split()
|
9 |
+
current_line = ''
|
10 |
+
|
11 |
+
for word in words:
|
12 |
+
# Check width with new word added
|
13 |
+
test_line = f"{current_line} {word}".strip()
|
14 |
+
test_width = draw.textlength(text = test_line, font=font)
|
15 |
+
if test_width <= max_width:
|
16 |
+
current_line = test_line
|
17 |
+
else:
|
18 |
+
#If the line with the new word exceeds the max width, start a new line
|
19 |
+
lines.append(current_line)
|
20 |
+
current_line = word
|
21 |
+
# add the last line
|
22 |
+
lines.append(current_line)
|
23 |
+
return lines
|
24 |
+
# Function for calculating the height of the text at the current font setting
|
25 |
+
|
26 |
+
|
27 |
+
def adjust_font_size_lines_and_spacing(text, font_path, initial_font_size, max_width, area_height, image) :
|
28 |
+
font_size = initial_font_size
|
29 |
+
optimal_font_size = font_size
|
30 |
+
optimal_lines = []
|
31 |
+
line_spacing_factor = 1.2 # multiple of font size that will get added between each line
|
32 |
+
|
33 |
+
while font_size > 10: # Set minimum font size
|
34 |
+
font = ImageFont.truetype(font_path, font_size)
|
35 |
+
draw = ImageDraw.Draw(image)
|
36 |
+
# Fitting text into box dimensions
|
37 |
+
lines = split_text_into_lines(text, font, max_width, draw)
|
38 |
+
# Calculate total height with dynamic line spacing
|
39 |
+
single_line_height = draw.textbbox((0, 0), "Ay", font=font)[3] - draw.textbbox((0, 0), "Ay", font=font)[1] # Height of 'Ay'
|
40 |
+
line_spacing = int(single_line_height * line_spacing_factor) - single_line_height
|
41 |
+
total_text_height = len(lines) * single_line_height + (len(lines) - 1) * line_spacing # Estimate total height of all lines by multiplying number of lines by font height plus number of lines -1 times line spacing
|
42 |
+
|
43 |
+
if total_text_height <= area_height :
|
44 |
+
optimal_font_size = font_size
|
45 |
+
optimal_lines = lines
|
46 |
+
break # Exit loop font fits in contraints
|
47 |
+
|
48 |
+
else:
|
49 |
+
font_size -= 1 # Reduce font by 1 to check if it fits
|
50 |
+
|
51 |
+
return optimal_font_size, optimal_lines, line_spacing
|
52 |
+
# Function that takes in an image,text and properties for textfrom card_generator
|
53 |
+
def render_text_with_dynamic_spacing(image, text, center_position, max_width, area_height,font_path, initial_font_size, item_key = None, description = None, quote = None):
|
54 |
+
if item_key:
|
55 |
+
text = write_description(item_key)
|
56 |
+
|
57 |
+
optimal_font_size, optimal_lines, line_spacing = adjust_font_size_lines_and_spacing(
|
58 |
+
text, font_path, initial_font_size, max_width, area_height, image)
|
59 |
+
# create an object to draw on
|
60 |
+
|
61 |
+
font = ImageFont.truetype(font_path, optimal_font_size)
|
62 |
+
draw = ImageDraw.Draw(image)
|
63 |
+
|
64 |
+
# Shadow settings
|
65 |
+
shadow_offset = (1, 1) # X and Y offset for shadow
|
66 |
+
shadow_color = 'grey' # Shadow color
|
67 |
+
|
68 |
+
# Unsure about the following line, not sure if I want y_offset to be dynamic
|
69 |
+
y_offset = center_position[1]
|
70 |
+
|
71 |
+
if description or quote :
|
72 |
+
for line in optimal_lines:
|
73 |
+
line_width = draw.textlength(text = line, font=font)
|
74 |
+
x = center_position[0]
|
75 |
+
# Draw Shadow first
|
76 |
+
shadow_position = (x + shadow_offset[0], y_offset + shadow_offset[1])
|
77 |
+
draw.text(shadow_position, line, font=font, fill=shadow_color)
|
78 |
+
#Draw text
|
79 |
+
draw.text((x, y_offset), line, font=font, fill = 'black', align = "left" )
|
80 |
+
y_offset += optimal_font_size + line_spacing # Move to next line
|
81 |
+
return image
|
82 |
+
|
83 |
+
for line in optimal_lines:
|
84 |
+
line_width = draw.textlength(text = line, font=font)
|
85 |
+
x = center_position[0] - (line_width / 2)
|
86 |
+
# Draw Shadow first
|
87 |
+
shadow_position = (x + shadow_offset[0], y_offset + shadow_offset[1])
|
88 |
+
draw.text(shadow_position, line, font=font, fill=shadow_color)
|
89 |
+
#Draw text
|
90 |
+
draw.text((x, y_offset), line, font=font, fill = 'black', align = "left" )
|
91 |
+
y_offset += optimal_font_size + line_spacing # Move to next line
|
92 |
+
return image
|
93 |
+
|
94 |
+
# Function to put the description objects together, this will be the complicated bit, I think iterate through keys excluding title, type and cost
|
95 |
+
def write_description(item_key):
|
96 |
+
skip_list = ['Name', 'Type', 'Value', 'Weight', 'Damage', 'SD Prompt', 'Quote', 'Rarity']
|
97 |
+
description_list = ['\n'.join(value) for key, value in item_key.items() if key not in skip_list and type(value) == list]
|
98 |
+
description_list += [value if key not in skip_list else '' for key, value in item_key.items() if type(value) != list]
|
99 |
+
return '\n'.join(filter(None, description_list))
|
100 |
+
|
101 |
+
|
102 |
+
|
MerchanBot CLI/user_input.py
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import item_dict_gen as igen
|
2 |
+
import img2img
|
3 |
+
import card_generator as card
|
4 |
+
import utilities as u
|
5 |
+
import sys
|
6 |
+
|
7 |
+
image_path = str
|
8 |
+
end_phrase = """<|end_of_turn|>"""
|
9 |
+
card_template_path = "./card_templates"
|
10 |
+
list_of_card_templates = u.directory_contents(card_template_path)
|
11 |
+
|
12 |
+
user_pick_template_prompt = "Pick a template number from this list : "
|
13 |
+
user_pick_image_prompt = "Select an image : "
|
14 |
+
|
15 |
+
# Check if the user wants to exit the chatbot
|
16 |
+
|
17 |
+
def user_exit_question(user_input):
|
18 |
+
if user_input.lower() in ['exit', 'quit']:
|
19 |
+
print("Chatbot session ended.")
|
20 |
+
sys.exit()
|
21 |
+
# Process the list of files in the card_template directory and print with corresponding numbers to index
|
22 |
+
def process_list_for_user_response(list_of_items):
|
23 |
+
x = 0
|
24 |
+
for item in list_of_items:
|
25 |
+
print(f"{x} : {item}")
|
26 |
+
x += 1
|
27 |
+
|
28 |
+
def user_pick_item(user_prompt,list_of_items):
|
29 |
+
process_list_for_user_response(list_of_items)
|
30 |
+
user_input = input(user_prompt)
|
31 |
+
# Check if the user wants to exit the chatbot
|
32 |
+
user_exit_question(user_input)
|
33 |
+
return list_of_items[int(user_input)]
|
34 |
+
|
35 |
+
def call_llm(user_input):
|
36 |
+
# Process the query and get the response
|
37 |
+
llm_call = igen.call_llm_and_cleanup(user_input)
|
38 |
+
response = llm_call['choices'][0]['text']
|
39 |
+
|
40 |
+
# Find the index of the phrase
|
41 |
+
index = response.find(end_phrase)
|
42 |
+
print(f"index = {index}")
|
43 |
+
if index != -1:
|
44 |
+
# Slice the string from the end of the phrase onwards
|
45 |
+
response = response[index + len(end_phrase):]
|
46 |
+
else:
|
47 |
+
# Phrase not found, optional handling
|
48 |
+
response = response
|
49 |
+
|
50 |
+
response = response.replace("GPT4 Assistant: ", "")
|
51 |
+
response = igen.convert_to_dict(response)
|
52 |
+
if not response:
|
53 |
+
response = call_llm(user_input)
|
54 |
+
del llm_call
|
55 |
+
return response
|
56 |
+
|
57 |
+
def prompt_user_input():
|
58 |
+
mimic = None
|
59 |
+
while True:
|
60 |
+
user_input_item = input("Provide an item : ")
|
61 |
+
user_exit_question(user_input_item)
|
62 |
+
|
63 |
+
if 'mimic' in user_input_item.lower():
|
64 |
+
mimic = True
|
65 |
+
|
66 |
+
#user_input_template = input(f"Pick a template number from this list : {process_list_for_user_response(list_of_card_templates)}")
|
67 |
+
user_input_template = user_pick_item(user_pick_template_prompt,list_of_card_templates)
|
68 |
+
response = call_llm(user_input_item)
|
69 |
+
print(response[u.keys_list(response,0)])
|
70 |
+
output_dict = response[u.keys_list(response,0)]
|
71 |
+
u.reclaim_mem()
|
72 |
+
item_name = response[u.keys_list(response,0)]['Name']
|
73 |
+
sd_prompt = response[u.keys_list(response,0)]['SD Prompt']
|
74 |
+
image_path = img2img.generate_image(4,sd_prompt,item_name,user_input_template, mimic)
|
75 |
+
user_card_image = user_pick_item(user_pick_image_prompt, image_path)
|
76 |
+
|
77 |
+
print(image_path)
|
78 |
+
|
79 |
+
card.render_text_on_card(user_card_image, output_dict)
|
80 |
+
u.delete_files(img2img.image_list)
|
81 |
+
|
82 |
+
|
83 |
+
|
84 |
+
print(list_of_card_templates)
|
85 |
+
|
MerchanBot CLI/utilities.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Create a list of hashmap key values .
|
2 |
+
import torch
|
3 |
+
import time
|
4 |
+
import gc
|
5 |
+
import os
|
6 |
+
|
7 |
+
# Utility Functions to be called from all modules
|
8 |
+
|
9 |
+
# Function to return a list of keys of a nested dictionary using it's key value (item or creature)
|
10 |
+
def keys_list(dict, index):
|
11 |
+
keys_list=list(dict.keys())
|
12 |
+
return keys_list[index]
|
13 |
+
|
14 |
+
def reclaim_mem():
|
15 |
+
|
16 |
+
print(f"Memory before del {torch.cuda.memory_allocated()}")
|
17 |
+
torch.cuda.ipc_collect()
|
18 |
+
gc.collect()
|
19 |
+
torch.cuda.empty_cache()
|
20 |
+
time.sleep(0.01)
|
21 |
+
print(f"Memory after del {torch.cuda.memory_allocated()}")
|
22 |
+
|
23 |
+
def del_object(object):
|
24 |
+
del object
|
25 |
+
gc.collect()
|
26 |
+
|
27 |
+
def directory_contents(directory_path):
|
28 |
+
if os.path.isdir(directory_path) :
|
29 |
+
contents = os.listdir(directory_path)
|
30 |
+
return contents
|
31 |
+
else : pass
|
32 |
+
|
33 |
+
def delete_files(file_paths):
|
34 |
+
|
35 |
+
for file_path in file_paths:
|
36 |
+
try:
|
37 |
+
os.remove(file_path)
|
38 |
+
except OSError as e:
|
39 |
+
print(f"Error: {file_path} : {e.strerror}")
|
40 |
+
file_paths.clear()
|
README.md
CHANGED
@@ -1,3 +1,4 @@
|
|
|
|
1 |
---
|
2 |
title: CollectibleCardGenerator
|
3 |
emoji: 🐠
|
@@ -9,3 +10,7 @@ license: mit
|
|
9 |
---
|
10 |
|
11 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
|
|
|
|
|
|
1 |
+
<<<<<<< HEAD
|
2 |
---
|
3 |
title: CollectibleCardGenerator
|
4 |
emoji: 🐠
|
|
|
10 |
---
|
11 |
|
12 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
13 |
+
=======
|
14 |
+
# CardGenerator
|
15 |
+
Takes user input and generates a collectible card with custom or LLM generated text and image generation
|
16 |
+
>>>>>>> master
|
__pycache__/card_generator.cpython-310.pyc
ADDED
Binary file (3.33 kB). View file
|
|
__pycache__/image_gen.cpython-310.pyc
ADDED
Binary file (1.74 kB). View file
|
|
__pycache__/img2img.cpython-310.pyc
ADDED
Binary file (2.45 kB). View file
|
|
__pycache__/inventory.cpython-310.pyc
ADDED
Binary file (3.77 kB). View file
|
|
__pycache__/item_dict_gen.cpython-310.pyc
ADDED
Binary file (18.4 kB). View file
|
|
__pycache__/main.cpython-310.pyc
ADDED
Binary file (7.27 kB). View file
|
|
__pycache__/render_card_text.cpython-310.pyc
ADDED
Binary file (2.03 kB). View file
|
|
__pycache__/template_builder.cpython-310.pyc
ADDED
Binary file (1.16 kB). View file
|
|
__pycache__/user_input.cpython-310.pyc
ADDED
Binary file (2.64 kB). View file
|
|
__pycache__/utilities.cpython-310.pyc
ADDED
Binary file (1.74 kB). View file
|
|
card_generator.py
ADDED
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import render_card_text as rend
|
2 |
+
from PIL import Image, ImageFilter
|
3 |
+
import utilities as u
|
4 |
+
import ast
|
5 |
+
|
6 |
+
|
7 |
+
def save_image(image,item_key):
|
8 |
+
image.save(f"{item_key['Name']}.png")
|
9 |
+
|
10 |
+
|
11 |
+
# Import Inventory
|
12 |
+
#shop_inventory = inv.inventory
|
13 |
+
#purchased_item_key = shop_inventory['Shortsword']
|
14 |
+
#border_path = './card_templates/Shining Sunset Border.png'
|
15 |
+
|
16 |
+
sticker_path_dictionary = {'Default': './card_parts/Sizzek Sticker.png','Common': './card_parts/Common.png', 'Uncommon': './card_parts/Uncommon.png','Rare': './card_parts/Rare.png','Very Rare':'./card_parts/Very Rare.png','Legendary':'./card_parts/Legendary.png'}
|
17 |
+
blank_overlay_path = "./card_parts/white-fill-title-detail-value-transparent.png"
|
18 |
+
value_overlay_path = "./card_parts/Value_box_transparent.png"
|
19 |
+
test_item = {'Name': 'Pustulent Raspberry', 'Type': 'Fruit', 'Value': '1 cp', 'Properties': ['Unusual Appearance', 'Rare Taste'], 'Weight': '0.2 lb', 'Description': 'This small fruit has a pustulent appearance, with bumps and irregular shapes covering its surface. Its vibrant colors and strange texture make it an oddity among other fruits.', 'Quote': 'A fruit that defies expectations, as sweet and sour as life itself.', 'SD Prompt': 'A small fruit with vibrant colors and irregular shapes, bumps covering its surface.'}
|
20 |
+
|
21 |
+
|
22 |
+
|
23 |
+
# Function that takes in an image url and a dictionary and uses the values to print onto a card.
|
24 |
+
def paste_image_and_resize(base_image,sticker_path, x_position, y_position,img_width, img_height, purchased_item_key = None):
|
25 |
+
|
26 |
+
# Check for if item has a Rarity string that is a in the dictionary of sticket paths
|
27 |
+
if purchased_item_key:
|
28 |
+
if sticker_path[purchased_item_key]:
|
29 |
+
sticker_path = sticker_path[purchased_item_key]
|
30 |
+
else: sticker_path = sticker_path['Default']
|
31 |
+
|
32 |
+
# Load the image to paste
|
33 |
+
image_to_paste = Image.open(sticker_path)
|
34 |
+
|
35 |
+
# Define the new size (scale) for the image you're pasting
|
36 |
+
|
37 |
+
new_size = (img_width, img_height)
|
38 |
+
|
39 |
+
# Resize the image to the new size
|
40 |
+
image_to_paste_resized = image_to_paste.resize(new_size)
|
41 |
+
|
42 |
+
# Specify the top-left corner where the resized image will be pasted
|
43 |
+
paste_position = (x_position, y_position) # Replace x and y with the coordinates
|
44 |
+
|
45 |
+
# Paste the resized image onto the base image
|
46 |
+
base_image.paste(image_to_paste_resized, paste_position, image_to_paste_resized)
|
47 |
+
|
48 |
+
def render_text_on_card(image_path, item_name,
|
49 |
+
item_type,
|
50 |
+
item_rarity,
|
51 |
+
item_value,
|
52 |
+
item_properties,
|
53 |
+
item_damage,
|
54 |
+
item_weight,
|
55 |
+
item_description,
|
56 |
+
item_quote) :
|
57 |
+
# Card Properties
|
58 |
+
image_list = []
|
59 |
+
item_properties = ast.literal_eval(item_properties)
|
60 |
+
item_properties = '\n'.join(item_properties)
|
61 |
+
output_image_path = f"./{item_name}.png"
|
62 |
+
print(f"Saving image to {output_image_path}")
|
63 |
+
font_path = "./fonts/Balgruf.ttf"
|
64 |
+
italics_font_path = './fonts/BalgrufItalic.ttf'
|
65 |
+
initial_font_size = 50
|
66 |
+
|
67 |
+
# Title Properties
|
68 |
+
title_center_position = (395, 55)
|
69 |
+
title_area_width = 600 # Maximum width of the text box
|
70 |
+
title_area_height = 60 # Maximum height of the text box
|
71 |
+
|
72 |
+
# Type box properties
|
73 |
+
type_center_position = (384, 545)
|
74 |
+
type_area_width = 600
|
75 |
+
type_area_height = 45
|
76 |
+
type_text = item_type
|
77 |
+
if len(item_weight) >= 1:
|
78 |
+
type_text = type_text + ' '+ item_weight
|
79 |
+
|
80 |
+
if len(item_damage) >= 1 :
|
81 |
+
type_text = type_text + ' '+ item_damage
|
82 |
+
|
83 |
+
# Description box properties
|
84 |
+
description_position = (105, 630)
|
85 |
+
description_area_width = 590
|
86 |
+
description_area_height = 215
|
87 |
+
|
88 |
+
# Value box properties (This is good, do not change unless underlying textbox layout is changing)
|
89 |
+
value_position = (660,905)
|
90 |
+
value_area_width = 125
|
91 |
+
value_area_height = 50
|
92 |
+
|
93 |
+
# Quote test properties
|
94 |
+
quote_position = (110,885)
|
95 |
+
quote_area_width = 470
|
96 |
+
quote_area_height = 60
|
97 |
+
|
98 |
+
# open image and render text
|
99 |
+
image = u.open_image_from_url(image_path)
|
100 |
+
image = rend.render_text_with_dynamic_spacing(image, item_name, title_center_position, title_area_width, title_area_height,font_path,initial_font_size)
|
101 |
+
image = rend.render_text_with_dynamic_spacing(image,type_text , type_center_position, type_area_width, type_area_height,font_path,initial_font_size)
|
102 |
+
image = rend.render_text_with_dynamic_spacing(image, item_description + '\n\n' + item_properties, description_position, description_area_width, description_area_height,font_path,initial_font_size, description = True)
|
103 |
+
paste_image_and_resize(image, value_overlay_path,x_position= 0,y_position=0, img_width= 768, img_height= 1024)
|
104 |
+
image = rend.render_text_with_dynamic_spacing(image, item_value, value_position, value_area_width, value_area_height,font_path,initial_font_size)
|
105 |
+
image = rend.render_text_with_dynamic_spacing(image, item_quote, quote_position, quote_area_width, quote_area_height,italics_font_path,initial_font_size, quote = True)
|
106 |
+
#Paste Sizzek Sticker
|
107 |
+
paste_image_and_resize(image, sticker_path_dictionary,x_position= 0,y_position=909, img_width= 115, img_height= 115, purchased_item_key= item_rarity)
|
108 |
+
|
109 |
+
# Add blur, gives it a less artificial look, put into list and return the list since gallery requires lists
|
110 |
+
image = image.filter(ImageFilter.GaussianBlur(.5))
|
111 |
+
image_list.append(image)
|
112 |
+
|
113 |
+
image = image.save(f"./output/{item_name}.png")
|
114 |
+
|
115 |
+
|
116 |
+
|
117 |
+
return image_list
|
118 |
+
|
119 |
+
|
120 |
+
#render_text_on_card('./card_templates/Shining Sunset Border.png',test_item )
|
121 |
+
|
122 |
+
|
123 |
+
|
124 |
+
|
card_parts/Common.png
ADDED
Git LFS Details
|
card_parts/Legendary.png
ADDED
Git LFS Details
|
card_parts/Rare.png
ADDED
Git LFS Details
|
card_parts/Sizzek Sticker.png
ADDED
Git LFS Details
|
card_parts/Uncommon.png
ADDED
Git LFS Details
|
card_parts/Value_box_transparent.png
ADDED
Git LFS Details
|
card_parts/Very Rare.png
ADDED
Git LFS Details
|
card_parts/white-fill-title-detail-value-transparent.png
ADDED
Git LFS Details
|
fonts/Balgruf.ttf
ADDED
Binary file (85.4 kB). View file
|
|
fonts/BalgrufItalic.ttf
ADDED
Binary file (79.4 kB). View file
|
|
fonts/Goudy Medieval Medieval.ttf
ADDED
Binary file (53.6 kB). View file
|
|
fonts/balgruf-font/Balgruf.ttf
ADDED
Binary file (85.4 kB). View file
|
|
fonts/balgruf-font/BalgrufItalic.ttf
ADDED
Binary file (79.4 kB). View file
|
|
fonts/balgruf-font/info.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
license: SIL Open Font License (OFL)
|
2 |
+
link: https://www.fontspace.com/balgruf-font-f59539
|
fonts/balgruf-font/misc/Balgruf-31cd.woff2
ADDED
Binary file (31.7 kB). View file
|
|
fonts/balgruf-font/misc/Balgruf-d256.woff
ADDED
Binary file (39.8 kB). View file
|
|
fonts/balgruf-font/misc/Balgruf_Italic-52d6.woff
ADDED
Binary file (38.8 kB). View file
|
|
fonts/balgruf-font/misc/Balgruf_Italic-e184.woff2
ADDED
Binary file (31.1 kB). View file
|
|
img2img.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from diffusers import (StableDiffusionXLImg2ImgPipeline, AutoencoderKL)
|
2 |
+
from diffusers.utils import load_image
|
3 |
+
import torch
|
4 |
+
import time
|
5 |
+
import utilities as u
|
6 |
+
import card_generator as card
|
7 |
+
from PIL import Image
|
8 |
+
|
9 |
+
pipe = None
|
10 |
+
start_time = time.time()
|
11 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
12 |
+
model_path = ("./models/stable-diffusion/card-generator-v1.safetensors")
|
13 |
+
lora_path = "./models/stable-diffusion/Loras/blank-card-template-5.safetensors"
|
14 |
+
detail_lora_path = "./models/stable-diffusion/Loras/add-detail-xl.safetensors"
|
15 |
+
mimic_lora_path = "./models/stable-diffusion/Loras/EnvyMimicXL01.safetensors"
|
16 |
+
temp_image_path = "./image_temp/"
|
17 |
+
card_pre_prompt = " blank magic card,high resolution, detailed intricate high quality border, textbox, high quality detailed magnum opus drawing of a "
|
18 |
+
negative_prompts = "text, words, numbers, letters"
|
19 |
+
image_list = []
|
20 |
+
|
21 |
+
|
22 |
+
def load_img_gen(prompt, item, mimic = None):
|
23 |
+
prompt = card_pre_prompt + item + ' ' + prompt
|
24 |
+
print(prompt)
|
25 |
+
# image_path = f"{user_input_template}"
|
26 |
+
# init_image = load_image(image_path).convert("RGB")
|
27 |
+
|
28 |
+
pipe = StableDiffusionXLImg2ImgPipeline.from_single_file(model_path,
|
29 |
+
custom_pipeline="low_stable_diffusion",
|
30 |
+
torch_dtype=torch.float16,
|
31 |
+
variant="fp16").to("cuda")
|
32 |
+
# Load LoRAs for controlling image
|
33 |
+
#pipe.load_lora_weights(lora_path, weight_name = "blank-card-template-5.safetensors",adapter_name = 'blank-card-template')
|
34 |
+
pipe.load_lora_weights(detail_lora_path, weight_name = "add-detail-xl.safetensors", adapter_name = "add-detail-xl")
|
35 |
+
|
36 |
+
# If mimic keyword has been detected, load the mimic LoRA and set adapter values
|
37 |
+
if mimic:
|
38 |
+
pipe.load_lora_weights(mimic_lora_path, weight_name = "EnvyMimicXL01.safetensors", adapter_name = "EnvyMimicXL")
|
39 |
+
pipe.set_adapters(['blank-card-template', "add-detail-xl", "EnvyMimicXL"], adapter_weights = [0.9,0.9,1.0])
|
40 |
+
else :
|
41 |
+
pipe.set_adapters([ "add-detail-xl"], adapter_weights = [0.9])
|
42 |
+
pipe.enable_vae_slicing()
|
43 |
+
return pipe, prompt
|
44 |
+
|
45 |
+
def preview_and_generate_image(x,pipe, prompt, user_input_template, item):
|
46 |
+
img_start = time.time()
|
47 |
+
image = pipe(prompt=prompt,
|
48 |
+
strength = .9,
|
49 |
+
guidance_scale = 5,
|
50 |
+
image= user_input_template,
|
51 |
+
negative_promt = negative_prompts,
|
52 |
+
num_inference_steps=40,
|
53 |
+
height = 1024, width = 768).images[0]
|
54 |
+
|
55 |
+
image = image.save(temp_image_path+str(x) + f"{item}.png")
|
56 |
+
output_image_path = temp_image_path+str(x) + f"{item}.png"
|
57 |
+
img_time = time.time() - img_start
|
58 |
+
img_its = 50/img_time
|
59 |
+
print(f"image gen time = {img_time} and {img_its} it/s")
|
60 |
+
|
61 |
+
# Delete the image variable to keep VRAM open to load the LLM
|
62 |
+
del image
|
63 |
+
print(f"Memory after del {torch.cuda.memory_allocated()}")
|
64 |
+
print(image_list)
|
65 |
+
total_time = time.time() - start_time
|
66 |
+
print(total_time)
|
67 |
+
|
68 |
+
return output_image_path
|
69 |
+
|
70 |
+
|
71 |
+
|
72 |
+
|
73 |
+
|
74 |
+
|
75 |
+
|
76 |
+
|
77 |
+
|
inventory.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
inventory = {
|
4 |
+
'Shortsword': {
|
5 |
+
'Name' : 'Shortsword',
|
6 |
+
'Type' : 'Melee Weapon (martial, sword)',
|
7 |
+
'Value': '10 gp',
|
8 |
+
'Properties': ['Finesse, Light '],
|
9 |
+
'Damage': '1d6 + proficiency + Dex or Str',
|
10 |
+
'Weight': '2 lb',
|
11 |
+
'Description': 'Gleaming with a modest radiance, the shortsword boasts a keen edge and a leather-wrapped hilt, promising both grace and reliability in the heat of combat.',
|
12 |
+
'Quote': 'In the heart of battle, the shortsword proves not just a weapon, but a steadfast companion, whispering paths of valor to those who wield it.',
|
13 |
+
'SD Description' : 'high resolution, blank magic card,detailed high quality intricate border, decorated textbox, high quality magnum opus cgi drawing of a steel shortsword'
|
14 |
+
},
|
15 |
+
|
16 |
+
'Health Potion': {
|
17 |
+
'Name' : 'Health Portion',
|
18 |
+
'Type' : 'Potion',
|
19 |
+
'Value': '50 gp',
|
20 |
+
'Properties': ['Quafable', 'Restores 1d4 + 2 HP upon consumption'],
|
21 |
+
'Weight': '0.5 lb',
|
22 |
+
'Description': 'Contained within this small vial is a crimson liquid that sparkles when shaken, a life-saving elixir for those who brave the unknown.',
|
23 |
+
'Quote': 'To the weary, a drop of hope; to the fallen, a chance to stand once more.'
|
24 |
+
},
|
25 |
+
|
26 |
+
|
27 |
+
'Wooden Shield': {
|
28 |
+
'Name' : 'Wooden Shield',
|
29 |
+
'Type' : 'Armor, Shield',
|
30 |
+
'Value': '15 gp',
|
31 |
+
'Properties': ['+2 AC'],
|
32 |
+
'Weight': '6 lb',
|
33 |
+
'Description': 'Sturdy and reliable, this wooden shield is a simple yet effective defense against the blows of adversaries.',
|
34 |
+
'Quote': 'In the rhythm of battle, it dances - a barrier between life and defeat.'
|
35 |
+
},
|
36 |
+
|
37 |
+
'Magical Helmet': {
|
38 |
+
'Name' : 'Magical Helmet of Perception',
|
39 |
+
'Type' : 'Magical Item (armor, helmet)',
|
40 |
+
'Value': '120 gp',
|
41 |
+
'Properties': ['+ 1 to AC', 'Grants the wearer enhanced perception'],
|
42 |
+
'Weight': '3 lb',
|
43 |
+
'Description': 'Forged from mystic metals and enchanted with ancient spells, this helmet offers protection beyond the physical realm.',
|
44 |
+
'Quote': 'A crown not of royalty, but of unyielding vigilance, warding off the unseen threats that lurk in the shadows.'
|
45 |
+
}
|
46 |
+
}
|
47 |
+
|
48 |
+
{'id': 'cmpl-5b0ed6c7-2326-473f-8f11-32d3f079edc2',
|
49 |
+
'object': 'text_completion',
|
50 |
+
'created': 1709094107,
|
51 |
+
'model': '../models/starling-lm-7b-alpha.Q8_0.gguf',
|
52 |
+
'choices': [{'text': ' Here\'s an example of a structured inventory entry for a Mimic Treasure Chest as per your request:\n\n```python\n{\n \'Mimic Treasure Chest\': {\n \'Name\': \'Mimic Treasure Chest\',\n \'Type\': \'Trap\',\n \'Rarity\': \'Rare\',\n \'Value\': \'1000 gp\', \n \'Properties\': [\n \'Deceptively inviting\', \n \'Springs to life when interacted with\', \n \'Capable of attacking unwary adventurers\'\n ],\n \'Weight\': \'50 lb\', \n \'Description\': \'At first glance, this chest appears to be laden with treasure, beckoning to all who gaze upon it. However, it harbors a deadly secret: it is a Mimic, a cunning and dangerous creature that preys on the greed of adventurers. With its dark magic, it can perfectly imitate a treasure chest, only to reveal its true, monstrous form when approached. Those who seek to plunder its contents might find themselves in a fight for their lives.\',\n \'Quote\': \'"Beneath the guise of gold and riches lies a predator, waiting with bated breath for its next victim."\',\n \'SD Prompt\': \'A seemingly ordinary treasure chest that glimmers with promise. Upon closer inspection, sinister, almost living edges move with malice, revealing its true nature as a Mimic, ready to unleash fury on the unwary.\'\n }\n}\n```\n\nKeep in mind that mimics are typically found in dungeons and are known to take on the form of doors and chests. This example follows that theme while also providing information on the mimic\'s rarity, value, properties, and weight.', 'index': 0, 'logprobs': None, 'finish_reason': 'stop'}], 'usage': {'prompt_tokens': 4287, 'completion_tokens': 405, 'total_tokens': 4692}}
|
item_dict_gen.py
ADDED
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from llama_cpp import Llama
|
2 |
+
import ast
|
3 |
+
import gc
|
4 |
+
import torch
|
5 |
+
|
6 |
+
model_path = "./models/starling-lm-7b-alpha.Q8_0.gguf"
|
7 |
+
# Set gpu_layers to the number of layers to offload to GPU. Set to 0 if no GPU acceleration is available on your system.
|
8 |
+
|
9 |
+
|
10 |
+
# Simple inference example
|
11 |
+
def load_llm(user_input):
|
12 |
+
llm = Llama(
|
13 |
+
model_path=model_path,
|
14 |
+
n_ctx=8192, # The max sequence length to use - note that longer sequence lengths require much more resources
|
15 |
+
n_threads=8, # The number of CPU threads to use, tailor to your system and the resulting performance
|
16 |
+
n_gpu_layers=-1 # The number of layers to offload to GPU, if you have GPU acceleration available
|
17 |
+
)
|
18 |
+
return llm(
|
19 |
+
f"GPT4 User: {prompt_instructions} the item is {user_input}: <|end_of_turn|>GPT4 Assistant:", # Prompt
|
20 |
+
max_tokens=512, # Generate up to 512 tokens
|
21 |
+
stop=["</s>"], # Example stop token - not necessarily correct for this specific model! Please check before using.
|
22 |
+
echo=False # Whether to echo the prompt
|
23 |
+
)
|
24 |
+
|
25 |
+
def call_llm_and_cleanup(user_input):
|
26 |
+
# Call the LLM and store its output
|
27 |
+
llm_output = load_llm(user_input)
|
28 |
+
print(llm_output['choices'][0]['text'])
|
29 |
+
gc.collect()
|
30 |
+
if torch.cuda.is_available():
|
31 |
+
torch.cuda.empty_cache() # Clear VRAM allocated by PyTorch
|
32 |
+
|
33 |
+
# llm_output is still available for use here
|
34 |
+
|
35 |
+
return llm_output
|
36 |
+
|
37 |
+
def convert_to_dict(string):
|
38 |
+
# Evaluate if string is dictionary literal
|
39 |
+
try:
|
40 |
+
result = ast.literal_eval(string)
|
41 |
+
if isinstance(result, dict):
|
42 |
+
print("Item dictionary is valid")
|
43 |
+
return result
|
44 |
+
# If not, modify by attempting to add brackets to where they tend to fail to generate.
|
45 |
+
else:
|
46 |
+
modified_string = '{' + string
|
47 |
+
if isinstance(modified_string, dict):
|
48 |
+
return modified_string
|
49 |
+
modified_string = string + '}'
|
50 |
+
if isinstance(modified_string, dict):
|
51 |
+
return modified_string
|
52 |
+
modified_string = '{' + string + '}'
|
53 |
+
if isinstance(modified_string, dict):
|
54 |
+
return modified_string
|
55 |
+
except (ValueError, SyntaxError) :
|
56 |
+
print("Dictionary not valid")
|
57 |
+
return None
|
58 |
+
|
59 |
+
|
60 |
+
# Instructions past 4 are not time tested and may need to be removed.
|
61 |
+
### Meta prompted :
|
62 |
+
prompt_instructions = """ **Purpose**: Generate a structured inventory entry for a specific item as a hashmap. Follow the format provided in the examples below.
|
63 |
+
|
64 |
+
**Instructions**:
|
65 |
+
1. Replace `{item}` with the name of the user item, DO NOT CHANGE THE USER ITEM NAME enclosed in single quotes (e.g., `'Magic Wand'`).
|
66 |
+
2. Ensure your request is formatted as a hashmap.
|
67 |
+
3. Weapons MUST have a key 'Damage'
|
68 |
+
4. The description should be brief and puncy, or concise and thoughtful.
|
69 |
+
5. The quote and SD Prompt MUST be inside double quotations ie " ".
|
70 |
+
6. The quote is from the perspective of someone commenting on the impact of the {item} on their life
|
71 |
+
7. Value should be assigned as an integer of copper pieces (cp), silver pieces (sp), electrum pieces (ep), gold pieces (gp), and platinum pieces (pp).
|
72 |
+
8. Use this table for reference on value :
|
73 |
+
1 cp 1 lb. of wheat
|
74 |
+
2 cp 1 lb. of flour or one chicken
|
75 |
+
5 cp 1 lb. of salt
|
76 |
+
1 sp 1 lb. of iron or 1 sq. yd. of canvas
|
77 |
+
5 sp 1 lb. of copper or 1 sq. yd. of cotton cloth
|
78 |
+
1 gp 1 lb. of ginger or one goat
|
79 |
+
2 gp 1 lb. of cinnamon or pepper, or one sheep
|
80 |
+
3 gp 1 lb. of cloves or one pig
|
81 |
+
5 gp 1 lb. of silver or 1 sq. yd. of linen
|
82 |
+
10 gp 1 sq. yd. of silk or one cow
|
83 |
+
15 gp 1 lb. of saffron or one ox
|
84 |
+
50 gp 1 lb. of gold
|
85 |
+
500 gp 1 lb. of platinum
|
86 |
+
|
87 |
+
|
88 |
+
300 gp +1 Melee or Ranged Weapon
|
89 |
+
2000 gp +2 Melee or Ranged Weapon
|
90 |
+
10000 gp +3 Melee or Ranged Weapon
|
91 |
+
300 gp +1 Armor Uncommon
|
92 |
+
2000 gp +2 Armor Rare
|
93 |
+
10000 gp +3 Armor Very Rare
|
94 |
+
300 gp +1 Shield Uncommon
|
95 |
+
2000 gp +2 Shield Rare
|
96 |
+
10000 gp +3 Shield Very Rare
|
97 |
+
|
98 |
+
9. Examples of Magical Scroll Value:
|
99 |
+
Common: 50-100 gp
|
100 |
+
Uncommon: 101-500 gp
|
101 |
+
Rare: 501-5000 gp
|
102 |
+
Very rare: 5001-50000 gp
|
103 |
+
Legendary: 50001+ gp
|
104 |
+
|
105 |
+
A scroll's rarity depends on the spell's level:
|
106 |
+
Cantrip-1: Common
|
107 |
+
2-3: Uncommon
|
108 |
+
4-5: Rare
|
109 |
+
6-8: Very rare
|
110 |
+
9: Legendary
|
111 |
+
|
112 |
+
10. Explanation of Mimics:
|
113 |
+
Mimics are shapeshifting predators able to take on the form of inanimate objects to lure creatures to their doom. In dungeons, these cunning creatures most often take the form of doors and chests, having learned that such forms attract a steady stream of prey.
|
114 |
+
Imitative Predators. Mimics can alter their outward texture to resemble wood, stone, and other basic materials, and they have evolved to assume the appearance of objects that other creatures are likely to come into contact with. A mimic in its altered form is nearly unrecognizable until potential prey blunders into its reach, whereupon the monster sprouts pseudopods and attacks.
|
115 |
+
When it changes shape, a mimic excretes an adhesive that helps it seize prey and weapons that touch it. The adhesive is absorbed when the mimic assumes its amorphous form and on parts the mimic uses to move itself.
|
116 |
+
Cunning Hunters. Mimics live and hunt alone, though they occasionally share their feeding grounds with other creatures. Although most mimics have only predatory intelligence, a rare few evolve greater cunning and the ability to carry on simple conversations in Common or Undercommon. Such mimics might allow safe passage through their domains or provide useful information in exchange for food.
|
117 |
+
|
118 |
+
11.
|
119 |
+
**Format Example**:
|
120 |
+
- **Dictionary Structure**:
|
121 |
+
|
122 |
+
{"{item}": {
|
123 |
+
'Name': "{item name}",
|
124 |
+
'Type': '{item type}',
|
125 |
+
'Rarity': '{item rarity},
|
126 |
+
'Value': '{item value}',
|
127 |
+
'Properties': ["{property1}", "{property2}", ...],
|
128 |
+
'Damage': '{damage formula} , '{damage type}',
|
129 |
+
'Weight': '{weight}',
|
130 |
+
'Description': "{item description}",
|
131 |
+
'Quote': "{item quote}",
|
132 |
+
'SD Prompt': "{special description for the item}"
|
133 |
+
} }
|
134 |
+
|
135 |
+
- **Input Placeholder**:
|
136 |
+
- "{item}": Replace with the item name, ensuring it's wrapped in single quotes.
|
137 |
+
|
138 |
+
**Output Examples**:
|
139 |
+
1. Cloak of Whispering Shadows Entry:
|
140 |
+
|
141 |
+
{"Cloak of Whispering Shadows": {
|
142 |
+
'Name': 'Cloak of Whispering Shadows',
|
143 |
+
'Type': 'Cloak',
|
144 |
+
'Rarity': 'Very Rare',
|
145 |
+
'Value': '7500 gp',
|
146 |
+
'Properties': ["Grants invisibility in dim light or darkness","Allows communication with shadows for gathering information"],
|
147 |
+
'Weight': '1 lb',
|
148 |
+
'Description': "A cloak woven from the essence of twilight, blending its wearer into the shadows. Whispers of the past and present linger in its folds, offering secrets to those who listen.",
|
149 |
+
'Quote': "In the embrace of night, secrets surface in the silent whispers of the dark.",
|
150 |
+
'SD Prompt': " Cloak of deep indigo almost black, swirling patterns that shift and move with every step. As it drapes over one's shoulders, an eerie connection forms between the wearer and darkness itself."
|
151 |
+
} }
|
152 |
+
|
153 |
+
2. Health Potion Entry:
|
154 |
+
|
155 |
+
{"Health Potion": {
|
156 |
+
'Name' : "Health Portion",
|
157 |
+
'Type' : 'Potion',
|
158 |
+
'Rarity' : 'Common',
|
159 |
+
'Value': '50 gp',
|
160 |
+
'Properties': ["Quafable", "Restores 1d4 + 2 HP upon consumption"],
|
161 |
+
'Weight': '0.5 lb',
|
162 |
+
'Description': "Contained within this small vial is a crimson liquid that sparkles when shaken, a life-saving elixir for those who brave the unknown.",
|
163 |
+
'Quote': "To the weary, a drop of hope; to the fallen, a chance to stand once more.",
|
164 |
+
'SD Prompt' : " a small, delicate vial containing a sparkling crimson liquid. Emit a soft glow, suggesting its restorative properties. The vial is set against a dark, ambiguous background."
|
165 |
+
} }
|
166 |
+
|
167 |
+
3. Wooden Shield Entry:
|
168 |
+
|
169 |
+
{"Wooden Shield": {
|
170 |
+
'Name' : "Wooden Shield",
|
171 |
+
'Type' : 'Armor, Shield',
|
172 |
+
'Rarity': 'Common',
|
173 |
+
'Value': '10 gp',
|
174 |
+
'Properties': ["+2 AC"],
|
175 |
+
'Weight': '6 lb',
|
176 |
+
'Description': "Sturdy and reliable, this wooden shield is a simple yet effective defense against the blows of adversaries.",
|
177 |
+
'Quote': "In the rhythm of battle, it dances - a barrier between life and defeat.",
|
178 |
+
'SD Prompt': " a sturdy wooden shield, a symbol of defense, with a simple yet solid design. The shield, has visible grain patterns and a few battle scars. It stands as a steadfast protector, embodying the essence of a warrior's resilience in the face of adversity."
|
179 |
+
} }
|
180 |
+
|
181 |
+
4. Helmet of Perception Entry:
|
182 |
+
|
183 |
+
{"Helmet of Perception": {
|
184 |
+
'Name' : "Helmet of Perception",
|
185 |
+
'Type' : 'Magical Item (armor, helmet)',
|
186 |
+
'Rarity': 'Very Rare',
|
187 |
+
'Value': '3000 gp',
|
188 |
+
'Properties': ["+ 1 to AC", "Grants the wearer advantage on perception checks", "+5 to passive perception"],
|
189 |
+
'Weight': '3 lb',
|
190 |
+
'Description': "Forged from mystic metals and enchanted with ancient spells, this helmet offers protection beyond the physical realm.",
|
191 |
+
'Quote': "A crown not of royalty, but of unyielding vigilance, warding off the unseen threats that lurk in the shadows.",
|
192 |
+
'SD Prompt': " a mystical helmet crafted from enchanted metals, glowing with subtle runes. imbued with spells, radiates a mystical aura, symbolizing enhanced perception and vigilance,elegant,formidable"
|
193 |
+
} }
|
194 |
+
|
195 |
+
5. Longbow Entry:
|
196 |
+
|
197 |
+
{"Longbow": {
|
198 |
+
'Name': "Longbow",
|
199 |
+
'Type': 'Ranged Weapon (martial, longbow)',
|
200 |
+
'Rarity': 'Common',
|
201 |
+
'Value': '50 gp',
|
202 |
+
'Properties': ["2-handed", "Range 150/600", "Loading"],
|
203 |
+
'Damage': '1d8 + Dex, piercing',
|
204 |
+
'Weight': '6 lb',
|
205 |
+
'Description': "With a sleek and elegant design, this longbow is crafted for speed and precision, capable of striking down foes from a distance.",
|
206 |
+
'Quote': "From the shadows it emerges, a silent whisper of steel that pierces the veil of darkness, bringing justice to those who dare to trespass.",
|
207 |
+
'SD Prompt' : "a longbow with intricate carvings and stone inlay with a black string"
|
208 |
+
} }
|
209 |
+
|
210 |
+
|
211 |
+
6. Mace Entry:
|
212 |
+
|
213 |
+
{"Mace": {
|
214 |
+
'Name': "Mace",
|
215 |
+
'Type': 'Melee Weapon (martial, bludgeoning)',
|
216 |
+
'Rarity': 'Common',
|
217 |
+
'Value': '25 gp',
|
218 |
+
'Properties': ["Bludgeoning", "One-handed"],
|
219 |
+
'Damage': '1d6 + str, bludgeoning',
|
220 |
+
'Weight': '6 lb',
|
221 |
+
'Description': "This mace is a fearsome sight, its head a heavy and menacing ball of metal designed to crush bone and break spirits.",
|
222 |
+
'Quote': "With each swing, it sings a melody of pain and retribution, an anthem of justice to those who wield it.",
|
223 |
+
'SD Prompt': "a menacing metal spike ball mace, designed for bludgeoning, with a heavy, intimidating head, embodying a tool for bone-crushing and spirit-breaking."
|
224 |
+
} }
|
225 |
+
|
226 |
+
7. Flying Carpet Entry:
|
227 |
+
|
228 |
+
{"Flying Carpet": {
|
229 |
+
'Name': "Flying Carpet",
|
230 |
+
'Type': 'Magical Item (transportation)',
|
231 |
+
'Rarity': 'Very Rare',
|
232 |
+
'Value': '3000 gp',
|
233 |
+
'Properties': ["Flying", "Personal Flight", "Up to 2 passengers", Speed : 60 ft],
|
234 |
+
'Weight': '50 lb',
|
235 |
+
'Description': "This enchanted carpet whisks its riders through the skies, providing a swift and comfortable mode of transport across great distances.",
|
236 |
+
'Quote': "Soar above the mundane, and embrace the winds of adventure with this magical gift from the heavens.",
|
237 |
+
'SD Prompt': "a vibrant, intricately patterned flying carpet soaring high in the sky, with clouds and a clear blue backdrop, emphasizing its magical essence and freedom of flight"
|
238 |
+
} }
|
239 |
+
|
240 |
+
8. Tome of Endless Stories Entry:
|
241 |
+
|
242 |
+
{"Tome of Endless Stories": {
|
243 |
+
'Name': "Tome of Endless Stories",
|
244 |
+
'Type': 'Book',
|
245 |
+
'Rarity': 'Uncommon'
|
246 |
+
'Value': '500 gp',
|
247 |
+
'Properties': [
|
248 |
+
"Generates a new story or piece of lore each day",
|
249 |
+
"Reading a story grants insight or a hint towards solving a problem or puzzle"
|
250 |
+
],
|
251 |
+
'Weight': '3 lbs',
|
252 |
+
'Description': "An ancient tome bound in leather that shifts colors like the sunset. Its pages are never-ending, filled with tales from worlds both known and undiscovered.",
|
253 |
+
'Quote': "Within its pages lie the keys to a thousand worlds, each story a doorway to infinite possibilities.",
|
254 |
+
'SD Prompt': "leather-bound with gold and silver inlay, pages appear aged but are incredibly durable, magical glyphs shimmer softly on the cover."
|
255 |
+
} }
|
256 |
+
|
257 |
+
9. Ring of Miniature Summoning Entry:
|
258 |
+
|
259 |
+
{"Ring of Miniature Summoning": {
|
260 |
+
'Name': "Ring of Miniature Summoning",
|
261 |
+
'Type': 'Ring',
|
262 |
+
'Rarity': 'Rare',
|
263 |
+
'Value': '1500 gp',
|
264 |
+
'Properties': ["Summons a miniature beast ally once per day", "Beast follows commands and lasts for 1 hour", "Choice of beast changes with each dawn"],
|
265 |
+
'Weight': '0 lb',
|
266 |
+
'Description': "A delicate ring with a gem that shifts colors. When activated, it brings forth a small, loyal beast companion from the ether.",
|
267 |
+
'Quote': "Not all companions walk beside us. Some are summoned from the depths of magic, small in size but vast in heart.",
|
268 |
+
'SD Prompt': "gemstone with changing colors, essence of companionship and versatility."
|
269 |
+
} }
|
270 |
+
|
271 |
+
|
272 |
+
10. Spoon of Tasting Entry:
|
273 |
+
|
274 |
+
{"Spoon of Tasting": {
|
275 |
+
'Name': "Spoon of Tasting",
|
276 |
+
'Type': 'Spoon',
|
277 |
+
'Rarity': 'Uncommon',
|
278 |
+
'Value': '200 gp',
|
279 |
+
'Properties': ["When used to taste any dish, it can instantly tell you all the ingredients", "Provides exaggerated compliments or critiques about the dish"],
|
280 |
+
'Weight': '0.2 lb',
|
281 |
+
'Description': "A culinary critic’s dream or nightmare. This spoon doesn’t hold back its opinions on any dish it tastes.",
|
282 |
+
'Quote': "A spoonful of sugar helps the criticism go down.",
|
283 |
+
'SD Prompt': "Looks like an ordinary spoon, but with a mouth that speaks more than you’d expect."
|
284 |
+
} }
|
285 |
+
|
286 |
+
11. Infinite Scroll Entry:
|
287 |
+
|
288 |
+
{"Infinite Scroll": {
|
289 |
+
'Name': "Infinite Scroll",
|
290 |
+
'Type': 'Magical Scroll',
|
291 |
+
'Rarity': 'Legendary',
|
292 |
+
'Value': '25000',
|
293 |
+
'Properties': [
|
294 |
+
"Endlessly Extends with New Knowledge","Reveals Content Based on Reader’s Need or Desire","Cannot be Fully Transcribed"],
|
295 |
+
'Weight': '0.5 lb',
|
296 |
+
'Description': "This scroll appears to be a standard parchment at first glance. However, as one begins to read, it unrolls to reveal an ever-expanding tapestry of knowledge, lore, and spells that seems to have no end.",
|
297 |
+
'Quote': "In the pursuit of knowledge, the horizon is ever receding. So too is the content of this scroll, an endless journey within a parchment’s bounds.",
|
298 |
+
'SD Prompt': "A seemingly ordinary scroll that extends indefinitely"
|
299 |
+
} }
|
300 |
+
|
301 |
+
12. Mimic Treasure Chest Entry:
|
302 |
+
|
303 |
+
{"Mimic Treasure Chest": {
|
304 |
+
'Name': "Mimic Treasure Chest",
|
305 |
+
'Type': 'Trap',
|
306 |
+
'Rarity': 'Rare',
|
307 |
+
'Value': '1000 gp', # Increased value reflects its dangerous and rare nature
|
308 |
+
'Properties': ["Deceptively inviting","Springs to life when interacted with","Capable of attacking unwary adventurers"],
|
309 |
+
'Weight': '50 lb', # Mimics are heavy due to their monstrous nature
|
310 |
+
'Description': "This enticing treasure chest is a deadly Mimic, luring adventurers with the promise of riches only to unleash its monstrous true form upon those who dare to approach, turning their greed into a fight for survival.",
|
311 |
+
'SD Prompt': "A seemingly ordinary treasure chest that glimmers with promise. Upon closer inspection, sinister, almost living edges move with malice, revealing its true nature as a Mimic, ready to unleash fury on the unwary."
|
312 |
+
} }
|
313 |
+
|
314 |
+
13. Hammer of Thunderbolts Entry:
|
315 |
+
|
316 |
+
{'Hammer of Thunderbolts': {
|
317 |
+
'Name': 'Hammer of Thunderbolts',
|
318 |
+
'Type': 'Melee Weapon (maul, bludgeoning)',
|
319 |
+
'Rarity': 'Legendary',
|
320 |
+
'Value': '16000',
|
321 |
+
'Damage': '2d6 + 1 (martial, bludgeoning)',
|
322 |
+
'Properties': ["requires attunement","Giant's Bane","must be wearing a belt of giant strength and gauntlets of ogre power","Str +4","Can excees 20 but not 30","20 against giant, DC 17 save against death","5 charges, expend 1 to make a range attack 20/60","ranged attack releases thunderclap on hit, DC 17 save against stunned 30 ft","regain 1d4+1 charges at dawn"],
|
323 |
+
'Weight': 15 lb',
|
324 |
+
'Description': "God-forged and storm-bound, a supreme force, its rune-etched head blazing with power. More than a weapon, it's a symbol of nature's fury, capable of reshaping landscapes and commanding elements with every strike.",
|
325 |
+
'Quote': "When the skies rage and the earth trembles, know that the Hammer of Thunderbolts has found its mark. It is not merely a weapon, but the embodiment of the storm\'s wrath wielded by those deemed worthy.",
|
326 |
+
'SD Prompt': "It radiates with electric energy, its rune-etched head and storm-weathered leather grip symbolizing its dominion over storms. In its grasp, it pulses with the potential to summon the heavens' fury, embodying the tempest's raw power."
|
327 |
+
} }
|
328 |
+
|
329 |
+
14. Shadow Lamp Entry:
|
330 |
+
|
331 |
+
{'Shadow Lamp': {
|
332 |
+
'Name': 'Shadow Lamp',
|
333 |
+
'Type': 'Magical Item',
|
334 |
+
'Rarity': 'Uncommon',
|
335 |
+
'Value': '500 gp',
|
336 |
+
'Properties': ["Provides dim light in a 20-foot radius", "Invisibility to darkness-based senses", "Can cast Darkness spell once per day"],
|
337 |
+
'Weight': '1 lb',
|
338 |
+
'Description': "A small lamp carved from obsidian and powered by a mysterious force, it casts an eerie glow that illuminates its surroundings while making the wielder invisible to those relying on darkness-based senses.",
|
339 |
+
'Quote': "In the heart of shadow lies an unseen light, casting away darkness and revealing what was once unseen.",
|
340 |
+
'SD Prompt': "Glass lantern filled with inky swirling shadows, black gaseous clouds flow out, blackness flows from it, spooky, sneaky"
|
341 |
+
} }
|
342 |
+
|
343 |
+
15. Dark Mirror:
|
344 |
+
|
345 |
+
{'Dark Mirror': {
|
346 |
+
'Name': 'Dark Mirror',
|
347 |
+
'Type': 'Magical Item',
|
348 |
+
'Rarity': 'Rare',
|
349 |
+
'Value': '600 gp',
|
350 |
+
'Properties': ["Reflects only darkness when viewed from one side", "Grants invisibility to its reflection", "Can be used to cast Disguise Self spell once per day"],
|
351 |
+
'Weight': '2 lb',
|
352 |
+
'Description': "An ordinary-looking mirror with a dark, almost sinister tint. It reflects only darkness and distorted images when viewed from one side, making it an ideal tool for spies and those seeking to hide their true identity.",
|
353 |
+
'Quote': "A glass that hides what lies within, a surface that reflects only darkness and deceit.",
|
354 |
+
'SD Prompt': "Dark and mysterious black surfaced mirror with an obsidian flowing center with a tint of malice, its surface reflecting nothing but black and distorted images, swirling with tendrils, spooky, ethereal"
|
355 |
+
} }
|
356 |
+
|
357 |
+
16. Moon-Touched Greatsword Entry:
|
358 |
+
|
359 |
+
{'Moon-Touched Greatsword':{
|
360 |
+
'Name': 'Moontouched Greatsword',
|
361 |
+
'Type': 'Melee Weapon (greatsword, slashing)',
|
362 |
+
'Rarity': 'Very Rare',
|
363 |
+
'Value': '8000 gp',
|
364 |
+
'Damage': '2d6 + Str slashing',
|
365 |
+
'Properties': ["Adds +2 to attack and damage rolls while wielder is under the effects of Moonbeam or Daylight spells", "Requires attunement"],
|
366 |
+
'Weight': '6 lb',
|
367 |
+
'Description': "Forged from lunar metal and imbued with celestial magic, this greatsword gleams like a silver crescent moon, its edge sharp enough to cut through the darkest shadows.",
|
368 |
+
'Quote': "With each swing, it sings a melody of light that pierces the veil of darkness, a beacon of hope and justice.",
|
369 |
+
'SD Prompt': "A silver greatsword with a crescent moon-shaped blade that reflects a soft glow, reminiscent of the moon's radiance. The hilt is wrapped in silvery leather, and the metal seems to shimmer and change with the light, reflecting the lunar cycles."
|
370 |
+
} }
|
371 |
+
"""
|
main.py
ADDED
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import img2img
|
3 |
+
import card_generator as card
|
4 |
+
import utilities as u
|
5 |
+
import ctypes
|
6 |
+
import user_input as useri
|
7 |
+
import gradio as gr
|
8 |
+
import template_builder as tb
|
9 |
+
import threading
|
10 |
+
import time
|
11 |
+
|
12 |
+
|
13 |
+
|
14 |
+
# This is a fix for the way that python doesn't release system memory back to the OS and it was leading to locking up the system
|
15 |
+
libc = ctypes.cdll.LoadLibrary("libc.so.6")
|
16 |
+
M_MMAP_THRESHOLD = -3
|
17 |
+
|
18 |
+
# Set malloc mmap threshold.
|
19 |
+
libc.mallopt(M_MMAP_THRESHOLD, 2**20)
|
20 |
+
initial_name = "A Crowbar"
|
21 |
+
|
22 |
+
|
23 |
+
|
24 |
+
|
25 |
+
|
26 |
+
with gr.Blocks() as demo:
|
27 |
+
|
28 |
+
# Functions and State Variables
|
29 |
+
# Build functions W/in the Gradio format, because it only allows modification within it's context
|
30 |
+
# Define inputs to match what is called on click, and output of the function as a list that matches the list of outputs
|
31 |
+
textbox_default_dict = {'Name':'', \
|
32 |
+
'Type': '',
|
33 |
+
'Rarity':'',
|
34 |
+
'Value':'',
|
35 |
+
'Properties':'',
|
36 |
+
'Damage':'',
|
37 |
+
'Weight':'',
|
38 |
+
'Description':'',
|
39 |
+
'Quote':'',
|
40 |
+
'SD Prompt':''
|
41 |
+
}
|
42 |
+
|
43 |
+
item_name_var = gr.State()
|
44 |
+
item_type_var = gr.State()
|
45 |
+
item_rarity_var = gr.State()
|
46 |
+
item_value_var = gr.State()
|
47 |
+
item_properties_var = gr.State()
|
48 |
+
item_damage_var = gr.State()
|
49 |
+
item_weight_var = gr.State()
|
50 |
+
item_description_var = gr.State()
|
51 |
+
item_quote_var = gr.State()
|
52 |
+
item_sd_prompt_var = gr.State('')
|
53 |
+
|
54 |
+
selected_border_image = gr.State('./card_templates/Moonstone Border.png')
|
55 |
+
num_image_to_generate = gr.State(4)
|
56 |
+
generated_image_list = gr.State([])
|
57 |
+
selected_generated_image = gr.State()
|
58 |
+
selected_seed_image = gr.State()
|
59 |
+
built_template = gr.State()
|
60 |
+
mimic = None
|
61 |
+
|
62 |
+
def set_textbox_defaults(textbox_default_dict, key):
|
63 |
+
item_name = textbox_default_dict[key]
|
64 |
+
return item_name
|
65 |
+
|
66 |
+
|
67 |
+
|
68 |
+
# Function called when user generates item info, then assign values of dictionary to variables, output once to State, twice to textbox
|
69 |
+
def generate_text_update_textboxes(user_input, progress = gr.Progress()):
|
70 |
+
u.reclaim_mem()
|
71 |
+
|
72 |
+
# Define a function to update progress
|
73 |
+
def update_progress(duration, progress):
|
74 |
+
for i in range(10):
|
75 |
+
time.sleep(duration / 10) # Wait for a fraction of the total duration
|
76 |
+
progress((i + 1) / 10, desc="Thinking...") # Update progress
|
77 |
+
# Start the progress update in a separate thread, passing `progress` explicitly
|
78 |
+
threading.Thread(target=update_progress, args=(10, progress)).start()
|
79 |
+
|
80 |
+
llm_output=useri.call_llm(user_input)
|
81 |
+
item_key = list(llm_output.keys())
|
82 |
+
|
83 |
+
item_key_values = list(llm_output[item_key[0]].keys())
|
84 |
+
item_name = llm_output[item_key[0]]['Name']
|
85 |
+
item_type = llm_output[item_key[0]]['Type']
|
86 |
+
item_rarity = llm_output[item_key[0]]['Rarity']
|
87 |
+
item_value = llm_output[item_key[0]]['Value']
|
88 |
+
item_properties = llm_output[item_key[0]]['Properties']
|
89 |
+
|
90 |
+
if 'Damage' in item_key_values:
|
91 |
+
item_damage = llm_output[item_key[0]]['Damage']
|
92 |
+
else: item_damage = ''
|
93 |
+
item_weight = llm_output[item_key[0]]['Weight']
|
94 |
+
item_description = llm_output[item_key[0]]['Description']
|
95 |
+
item_quote = llm_output[item_key[0]]['Quote']
|
96 |
+
|
97 |
+
sd_prompt = llm_output[item_key[0]]['SD Prompt']
|
98 |
+
return [item_name, item_name,
|
99 |
+
item_type, item_type,
|
100 |
+
item_rarity, item_rarity,
|
101 |
+
item_value, item_value,
|
102 |
+
item_properties, item_properties,
|
103 |
+
item_damage, item_damage,
|
104 |
+
item_weight, item_weight,
|
105 |
+
item_description, item_description,
|
106 |
+
item_quote, item_quote,
|
107 |
+
sd_prompt, sd_prompt]
|
108 |
+
|
109 |
+
# Called on user selecting an image from the gallery, outputs the path of the image
|
110 |
+
def assign_img_path(evt: gr.SelectData):
|
111 |
+
img_dict = evt.value
|
112 |
+
print(img_dict)
|
113 |
+
selected_image_path = img_dict['image']['url']
|
114 |
+
print(selected_image_path)
|
115 |
+
return selected_image_path
|
116 |
+
|
117 |
+
# Make a list of files in image_temp and delete them
|
118 |
+
def delete_temp_images():
|
119 |
+
image_list = u.directory_contents('./image_temp')
|
120 |
+
u.delete_files(image_list)
|
121 |
+
img2img.image_list.clear()
|
122 |
+
|
123 |
+
# Called when pressing button to generate image, updates gallery by returning the list of image URLs
|
124 |
+
def generate_image_update_gallery(num_img, sd_prompt,item_name, built_template):
|
125 |
+
delete_temp_images()
|
126 |
+
print(type(built_template))
|
127 |
+
image_list = []
|
128 |
+
img_gen, prompt = img2img.load_img_gen(sd_prompt, item_name)
|
129 |
+
for x in range(num_img):
|
130 |
+
preview = img2img.preview_and_generate_image(x,img_gen, prompt, built_template, item_name)
|
131 |
+
image_list.append(preview)
|
132 |
+
yield image_list
|
133 |
+
#generate_gallery.change(image_list)
|
134 |
+
del preview
|
135 |
+
u.reclaim_mem()
|
136 |
+
|
137 |
+
#generated_image_list = img2img.generate_image(num_img,sd_prompt,item_name,selected_border)
|
138 |
+
return image_list
|
139 |
+
|
140 |
+
def build_template(selected_border, selected_seed_image):
|
141 |
+
image_list = tb.build_card_template(selected_border, selected_seed_image)
|
142 |
+
return image_list, image_list
|
143 |
+
|
144 |
+
|
145 |
+
# Beginning of page format
|
146 |
+
# Title
|
147 |
+
gr.HTML(""" <div id="inner"> <header>
|
148 |
+
<h1>Item Card Generator</h1>
|
149 |
+
<p>
|
150 |
+
With this AI driven tool you will build a collectible style card of a fantasy flavored item with details.
|
151 |
+
</p>
|
152 |
+
</div>""")
|
153 |
+
gr.HTML(""" <div id="inner"> <header>
|
154 |
+
<h2><b>First:</b> Build a Card Template</h2>
|
155 |
+
</div>""")
|
156 |
+
with gr.Row():
|
157 |
+
|
158 |
+
# Template Gallery instructions
|
159 |
+
gr.HTML(""" <div id="inner"> <header>
|
160 |
+
<h3>1. Click a border from the 'Card Template Gallery'</h3>
|
161 |
+
</div>""")
|
162 |
+
|
163 |
+
border_gallery = gr.Gallery(label = "Card Template Gallery",
|
164 |
+
scale = 2,
|
165 |
+
value = useri.index_image_paths("./seed_images/card_templates/", "card_templates/"),
|
166 |
+
show_label = True,
|
167 |
+
columns = [3], rows = [3],
|
168 |
+
object_fit = "contain",
|
169 |
+
height = "auto",
|
170 |
+
elem_id = "Template Gallery")
|
171 |
+
gr.HTML(""" <div id="inner"> <header>
|
172 |
+
<h3>2. Click a image from the Seed Image Gallery</h3><br>
|
173 |
+
</div>""")
|
174 |
+
border_gallery.select(assign_img_path, outputs = selected_border_image)
|
175 |
+
|
176 |
+
seed_image_gallery = gr.Gallery(label= " Image Seed Gallery",
|
177 |
+
scale = 2,
|
178 |
+
value = useri.index_image_paths("./seed_images/item_seeds/","item_seeds/"),
|
179 |
+
show_label = True,
|
180 |
+
columns = [3], rows = [3],
|
181 |
+
object_fit = "contain",
|
182 |
+
height = "auto",
|
183 |
+
elem_id = "Template Gallery",
|
184 |
+
interactive=True)
|
185 |
+
|
186 |
+
|
187 |
+
gr.HTML(""" <div id="inner"> <header><h4> -Or- Upload your own seed image, by dropping it into the 'Generated Template Gallery' </h4><br>
|
188 |
+
<h3>3. Click 'Generate Card Template'</h3><br>
|
189 |
+
</div>""")
|
190 |
+
|
191 |
+
|
192 |
+
built_template_gallery = gr.Gallery(label= "Generated Template Gallery",
|
193 |
+
scale = 1,
|
194 |
+
value = None,
|
195 |
+
show_label = True,
|
196 |
+
columns = [4], rows = [4],
|
197 |
+
object_fit = "contain",
|
198 |
+
height = "auto",
|
199 |
+
elem_id = "Template Gallery",
|
200 |
+
interactive=True)
|
201 |
+
|
202 |
+
seed_image_gallery.select(assign_img_path, outputs = selected_seed_image)
|
203 |
+
built_template_gallery.upload(u.receive_upload, inputs=built_template_gallery, outputs= selected_seed_image)
|
204 |
+
|
205 |
+
build_card_template_button = gr.Button(value = "Generate Card Template")
|
206 |
+
build_card_template_button.click(build_template, inputs = [selected_border_image, selected_seed_image], outputs = [built_template_gallery, built_template])
|
207 |
+
|
208 |
+
gr.HTML(""" <div id="inner"> <header>
|
209 |
+
<h2><b>Second:</b> Generate Item Text </h2>
|
210 |
+
</div>""")
|
211 |
+
gr.HTML(""" <div id="inner"> <header>
|
212 |
+
<h3>1. Use a few words to describe the item then click 'Generate Text' </h3>
|
213 |
+
</div>""")
|
214 |
+
with gr.Row():
|
215 |
+
|
216 |
+
|
217 |
+
user_input = gr.Textbox(label = 'Item', lines =1, placeholder= "Flaming Magical Sword", elem_id= "Item", scale =4)
|
218 |
+
item_text_generate = gr.Button(value = "Generate item text", scale=1)
|
219 |
+
|
220 |
+
gr.HTML(""" <div id="inner"> <header>
|
221 |
+
<h3> 2. Review and Edit the text</h3>
|
222 |
+
</div>""")
|
223 |
+
with gr.Row():
|
224 |
+
# Build text boxes for the broken up item dictionary values
|
225 |
+
|
226 |
+
with gr.Column(scale = 1):
|
227 |
+
|
228 |
+
|
229 |
+
|
230 |
+
item_name_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Name'),label = 'Name', lines = 1, interactive=True, elem_id='Item Name')
|
231 |
+
item_type_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Type'),label = 'Type', lines = 1, interactive=True, elem_id='Item Type')
|
232 |
+
item_rarity_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Rarity'),label = 'Rarity : [Common, Uncommon, Rare, Very Rare, Legendary]', lines = 1, interactive=True, elem_id='Item Rarity')
|
233 |
+
item_value_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Value'),label = 'Value', lines = 1, interactive=True, elem_id='Item Value')
|
234 |
+
|
235 |
+
# Pass the user input and border template to the generator
|
236 |
+
with gr.Column(scale = 1):
|
237 |
+
item_damage_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Damage'),label = 'Damage', lines = 1, interactive=True, elem_id='Item Damage')
|
238 |
+
item_weight_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Weight'),label = 'Weight', lines = 1, interactive=True, elem_id='Item Weight')
|
239 |
+
item_description_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Description'),label = 'Description', lines = 1, interactive=True, elem_id='Item Description')
|
240 |
+
item_quote_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Quote'),label = 'Quote', lines = 1, interactive=True, elem_id='Item quote')
|
241 |
+
item_properties_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Properties'),label = 'Properties : [List of comma seperated values]', lines = 1, interactive=True, elem_id='Item Properties')
|
242 |
+
gr.HTML(""" <div id="inner"> <header>
|
243 |
+
<h3> 3. This text will be used to generate the card's image.</h3>
|
244 |
+
</div>""")
|
245 |
+
item_sd_prompt_output = gr.Textbox(label = 'Putting words or phrases in parenthesis adds weight. Example: (Flaming Magical :1.0) Sword.', value = set_textbox_defaults(textbox_default_dict, 'SD Prompt'), lines = 1, interactive=True, elem_id='SD Prompt')
|
246 |
+
|
247 |
+
gr.HTML(""" <div id="inner"> <header>
|
248 |
+
<h2> <b>Third:</b> Click 'Generate Cards' to generate 4 cards to choose from. </h2>
|
249 |
+
</div>""")
|
250 |
+
card_gen_button = gr.Button(value = "Generate Cards", elem_id="Generate Card Button")
|
251 |
+
|
252 |
+
# No longer Row Context, in context of entire Block
|
253 |
+
gr.HTML(""" <div id="inner"> <header>
|
254 |
+
<h2> <b>Fourth:</b> Click your favorite card then add text, or click 'Generate Four Card Options' again.<br>
|
255 |
+
</h2>
|
256 |
+
</div>""")
|
257 |
+
|
258 |
+
with gr.Row():
|
259 |
+
generate_gallery = gr.Gallery(label = "Generated Cards",
|
260 |
+
value = [],
|
261 |
+
show_label= True,
|
262 |
+
scale= 5,
|
263 |
+
columns =[2], rows = [2],
|
264 |
+
object_fit= "fill",
|
265 |
+
height = "768",
|
266 |
+
elem_id = "Generated Cards Gallery"
|
267 |
+
)
|
268 |
+
generate_final_item_card = gr.Button(value = "Add Text", elem_id = "Generate user card")
|
269 |
+
|
270 |
+
|
271 |
+
card_gen_button.click(fn = generate_image_update_gallery, inputs =[num_image_to_generate,item_sd_prompt_output,item_name_output,built_template], outputs= generate_gallery)
|
272 |
+
generate_gallery.select(assign_img_path, outputs = selected_generated_image)
|
273 |
+
|
274 |
+
# Button logice calls function when button object is pressed, passing inputs and passing output to components
|
275 |
+
llm_output = item_text_generate.click(generate_text_update_textboxes,
|
276 |
+
inputs = [user_input],
|
277 |
+
outputs= [item_name_var,
|
278 |
+
item_name_output,
|
279 |
+
item_type_var,
|
280 |
+
item_type_output,
|
281 |
+
item_rarity_var,
|
282 |
+
item_rarity_output,
|
283 |
+
item_value_var,
|
284 |
+
item_value_output,
|
285 |
+
item_properties_var,
|
286 |
+
item_properties_output,
|
287 |
+
item_damage_var,
|
288 |
+
item_damage_output,
|
289 |
+
item_weight_var,
|
290 |
+
item_weight_output,
|
291 |
+
item_description_var,
|
292 |
+
item_description_output,
|
293 |
+
item_quote_var,
|
294 |
+
item_quote_output,
|
295 |
+
item_sd_prompt_var,
|
296 |
+
item_sd_prompt_output])
|
297 |
+
|
298 |
+
|
299 |
+
|
300 |
+
generate_final_item_card.click(card.render_text_on_card, inputs = [selected_generated_image,
|
301 |
+
item_name_output,
|
302 |
+
item_type_output,
|
303 |
+
item_rarity_output,
|
304 |
+
item_value_output,
|
305 |
+
item_properties_output,
|
306 |
+
item_damage_output,
|
307 |
+
item_weight_output,
|
308 |
+
item_description_output,
|
309 |
+
item_quote_output
|
310 |
+
],
|
311 |
+
outputs = generate_gallery )
|
312 |
+
|
313 |
+
|
314 |
+
|
315 |
+
if __name__ == '__main__':
|
316 |
+
demo.launch(server_name = "0.0.0.0", server_port = 8000, share = False, allowed_paths = ["/media/drakosfire/Shared/","/media/drakosfire/Shared/MerchantBot/card_templates"])
|
317 |
+
|
318 |
+
|
319 |
+
|
320 |
+
|
321 |
+
|
322 |
+
|
323 |
+
|
324 |
+
|
325 |
+
|
326 |
+
|
327 |
+
|
328 |
+
|
329 |
+
|
330 |
+
|
render_card_text.py
ADDED
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image, ImageDraw, ImageFont
|
2 |
+
|
3 |
+
# Function for managing longer bodies of text and breaking into a list of lines to be printed based on input arguments
|
4 |
+
def split_text_into_lines(text, font, max_width, draw):
|
5 |
+
blocks = text.split('\n')
|
6 |
+
lines = []
|
7 |
+
for block in blocks:
|
8 |
+
words = block.split()
|
9 |
+
current_line = ''
|
10 |
+
|
11 |
+
for word in words:
|
12 |
+
# Check width with new word added
|
13 |
+
test_line = f"{current_line} {word}".strip()
|
14 |
+
test_width = draw.textlength(text = test_line, font=font)
|
15 |
+
if test_width <= max_width:
|
16 |
+
current_line = test_line
|
17 |
+
else:
|
18 |
+
#If the line with the new word exceeds the max width, start a new line
|
19 |
+
lines.append(current_line)
|
20 |
+
current_line = word
|
21 |
+
# add the last line
|
22 |
+
lines.append(current_line)
|
23 |
+
return lines
|
24 |
+
# Function for calculating the height of the text at the current font setting
|
25 |
+
|
26 |
+
|
27 |
+
def adjust_font_size_lines_and_spacing(text, font_path, initial_font_size, max_width, area_height, image) :
|
28 |
+
font_size = initial_font_size
|
29 |
+
optimal_font_size = font_size
|
30 |
+
optimal_lines = []
|
31 |
+
line_spacing_factor = 1.2 # multiple of font size that will get added between each line
|
32 |
+
|
33 |
+
while font_size > 10: # Set minimum font size
|
34 |
+
font = ImageFont.truetype(font_path, font_size)
|
35 |
+
draw = ImageDraw.Draw(image)
|
36 |
+
# Fitting text into box dimensions
|
37 |
+
lines = split_text_into_lines(text, font, max_width, draw)
|
38 |
+
# Calculate total height with dynamic line spacing
|
39 |
+
single_line_height = draw.textbbox((0, 0), "Ay", font=font)[3] - draw.textbbox((0, 0), "Ay", font=font)[1] # Height of 'Ay'
|
40 |
+
line_spacing = int(single_line_height * line_spacing_factor) - single_line_height
|
41 |
+
total_text_height = len(lines) * single_line_height + (len(lines) - 1) * line_spacing # Estimate total height of all lines by multiplying number of lines by font height plus number of lines -1 times line spacing
|
42 |
+
|
43 |
+
if total_text_height <= area_height :
|
44 |
+
optimal_font_size = font_size
|
45 |
+
optimal_lines = lines
|
46 |
+
break # Exit loop font fits in contraints
|
47 |
+
|
48 |
+
else:
|
49 |
+
font_size -= 1 # Reduce font by 1 to check if it fits
|
50 |
+
|
51 |
+
return optimal_font_size, optimal_lines, line_spacing
|
52 |
+
# Function that takes in an image,text and properties for textfrom card_generator
|
53 |
+
def render_text_with_dynamic_spacing(image, text, center_position, max_width, area_height,font_path, initial_font_size,description = None, quote = None):
|
54 |
+
|
55 |
+
|
56 |
+
optimal_font_size, optimal_lines, line_spacing = adjust_font_size_lines_and_spacing(
|
57 |
+
text, font_path, initial_font_size, max_width, area_height, image)
|
58 |
+
# create an object to draw on
|
59 |
+
|
60 |
+
font = ImageFont.truetype(font_path, optimal_font_size)
|
61 |
+
draw = ImageDraw.Draw(image)
|
62 |
+
|
63 |
+
# Shadow settings
|
64 |
+
shadow_offset = (1, 1) # X and Y offset for shadow
|
65 |
+
shadow_color = 'grey' # Shadow color
|
66 |
+
|
67 |
+
# Unsure about the following line, not sure if I want y_offset to be dynamic
|
68 |
+
y_offset = center_position[1]
|
69 |
+
|
70 |
+
if description or quote :
|
71 |
+
for line in optimal_lines:
|
72 |
+
line_width = draw.textlength(text = line, font=font)
|
73 |
+
x = center_position[0]
|
74 |
+
# Draw Shadow first
|
75 |
+
shadow_position = (x + shadow_offset[0], y_offset + shadow_offset[1])
|
76 |
+
draw.text(shadow_position, line, font=font, fill=shadow_color)
|
77 |
+
#Draw text
|
78 |
+
draw.text((x, y_offset), line, font=font, fill = 'black', align = "left" )
|
79 |
+
y_offset += optimal_font_size + line_spacing # Move to next line
|
80 |
+
return image
|
81 |
+
|
82 |
+
for line in optimal_lines:
|
83 |
+
line_width = draw.textlength(text = line, font=font)
|
84 |
+
x = center_position[0] - (line_width / 2)
|
85 |
+
# Draw Shadow first
|
86 |
+
shadow_position = (x + shadow_offset[0], y_offset + shadow_offset[1])
|
87 |
+
draw.text(shadow_position, line, font=font, fill=shadow_color)
|
88 |
+
#Draw text
|
89 |
+
draw.text((x, y_offset), line, font=font, fill = 'black', align = "left" )
|
90 |
+
y_offset += optimal_font_size + line_spacing # Move to next line
|
91 |
+
return image
|
92 |
+
|
93 |
+
# Function to put the description objects together, this will be the complicated bit, I think iterate through keys excluding title, type and cost
|
94 |
+
|
95 |
+
|
96 |
+
|
97 |
+
|