drakosfire commited on
Commit
0cb2113
1 Parent(s): 2aa7608

Polished and launch to Hugging Face

Browse files
.gitattributes CHANGED
@@ -1,35 +1 @@
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
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz 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
+ *.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()
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}}