drakosfire commited on
Commit
6ce51a7
1 Parent(s): 207b6ad
.gitattributes CHANGED
@@ -1,4 +1,5 @@
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
@@ -37,3 +38,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
37
  =======
38
  *.png filter=lfs diff=lfs merge=lfs -text
39
 
 
 
 
 
1
  <<<<<<< HEAD
2
+ <<<<<<< HEAD
3
  *.7z filter=lfs diff=lfs merge=lfs -text
4
  *.arrow filter=lfs diff=lfs merge=lfs -text
5
  *.bin filter=lfs diff=lfs merge=lfs -text
 
38
  =======
39
  *.png filter=lfs diff=lfs merge=lfs -text
40
 
41
+ =======
42
+ *.png filter=lfs diff=lfs merge=lfs -text
43
+
.gitignore CHANGED
@@ -1,6 +1,6 @@
1
  output/
2
  image_temp/
3
- MerchantBotCLI/
4
  models
5
  seed_images/
6
  cuda_12.4.0_550.54.14_linux.run
 
 
1
  output/
2
  image_temp/
 
3
  models
4
  seed_images/
5
  cuda_12.4.0_550.54.14_linux.run
6
+
Dockerfile CHANGED
@@ -1,4 +1,5 @@
1
  # Stage 1: Build Cuda toolkit
 
2
  FROM ubuntu:22.04 as cuda-setup
3
 
4
 
@@ -81,10 +82,21 @@ RUN pip install --no-cache-dir torch packaging wheel && \
81
  pip install gradio && \
82
  CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama_cpp_python==0.2.55 && \
83
  CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama_cpp_python==0.2.55 && \
 
 
 
 
 
 
 
 
 
 
84
  pip install pillow && \
85
  pip install diffusers && \
86
  pip install accelerate && \
87
  pip install transformers && \
 
88
  pip install peft && \
89
  pip install pip install PyGithub
90
 
@@ -118,6 +130,28 @@ RUN chown -R user:user /home/user/app/ && \
118
  mkdir -p /home/user/app/output && \
119
  chown -R user:user /home/user/app/image_temp && \
120
  chown -R user:user /home/user/app/output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
  USER user
123
 
 
1
  # Stage 1: Build Cuda toolkit
2
+ <<<<<<< HEAD
3
  FROM ubuntu:22.04 as cuda-setup
4
 
5
 
 
82
  pip install gradio && \
83
  CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama_cpp_python==0.2.55 && \
84
  CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama_cpp_python==0.2.55 && \
85
+ =======
86
+ FROM drakosfire/cuda-base:latest as base-layer
87
+
88
+ # 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
89
+ ENV LLAMA_CUBLAS=1
90
+ RUN apt-get update && \
91
+ apt-get install -y python3 python3-pip python3-venv && \
92
+ pip install gradio && \
93
+ CMAKE_ARGS="-DLLAMA_CUBLAS=on" pip install llama-cpp-python && \
94
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
95
  pip install pillow && \
96
  pip install diffusers && \
97
  pip install accelerate && \
98
  pip install transformers && \
99
+ <<<<<<< HEAD
100
  pip install peft && \
101
  pip install pip install PyGithub
102
 
 
130
  mkdir -p /home/user/app/output && \
131
  chown -R user:user /home/user/app/image_temp && \
132
  chown -R user:user /home/user/app/output
133
+ =======
134
+ pip install peft
135
+
136
+ FROM base-layer as final-layer
137
+
138
+ RUN useradd -m -u 1000 user
139
+
140
+ # mkdir -p /home/user/.cache && \
141
+ # chmod 777 /home/user/.cache && \
142
+ # chown -R user:user /home/user/app/
143
+ # Set environment variables for copied builds of cuda and flash-attn in /venv
144
+
145
+
146
+ ENV PATH=/usr/local/cuda-12.4/bin:/venv/bin:${PATH}
147
+ ENV LD_LIBRARY_PATH=/usr/local/cuda-12.4/lib64:${LD_LIBRARY_PATH}
148
+
149
+ ENV VIRTUAL_ENV=/venv
150
+ RUN python3 -m venv $VIRTUAL_ENV
151
+ ENV PATH="$VIRTUAL_ENV/bin:$PATH"
152
+ # Set working directory and user
153
+ WORKDIR /home/user/app
154
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
155
 
156
  USER user
157
 
MerchanBotCLI/LICENSE DELETED
@@ -1,21 +0,0 @@
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.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
MerchanBotCLI/README.md DELETED
@@ -1,2 +0,0 @@
1
- # CardGenerator
2
- Takes user input and generates a collectible card with custom or LLM generated text and image generation
 
 
 
MerchanBotCLI/card_generator.py DELETED
@@ -1,109 +0,0 @@
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
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
MerchanBotCLI/image_gen.py DELETED
@@ -1,50 +0,0 @@
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
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
MerchanBotCLI/img2img.py DELETED
@@ -1,77 +0,0 @@
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
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
MerchanBotCLI/inventory.py DELETED
@@ -1,52 +0,0 @@
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}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
MerchanBotCLI/item_dict_gen.py DELETED
@@ -1,329 +0,0 @@
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
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
MerchanBotCLI/main.py DELETED
@@ -1,25 +0,0 @@
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
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
MerchanBotCLI/render_card_text.py DELETED
@@ -1,102 +0,0 @@
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
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
MerchanBotCLI/user_input.py DELETED
@@ -1,85 +0,0 @@
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
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
MerchanBotCLI/utilities.py DELETED
@@ -1,40 +0,0 @@
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
  <<<<<<< HEAD
3
  license: mit
@@ -31,3 +32,7 @@ license: mit
31
  ---
32
 
33
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
1
+ <<<<<<< HEAD
2
  ---
3
  <<<<<<< HEAD
4
  license: mit
 
32
  ---
33
 
34
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
35
+ =======
36
+ # CardGenerator
37
+ Takes user input and generates a collectible card with custom or LLM generated text and image generation
38
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
card_generator.py CHANGED
@@ -23,7 +23,11 @@ test_item = {'Name': 'Pustulent Raspberry', 'Type': 'Fruit', 'Value': '1 cp', 'P
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 in the dictionary of sticker paths
 
 
 
27
  if purchased_item_key:
28
  if sticker_path[purchased_item_key]:
29
  sticker_path = sticker_path[purchased_item_key]
 
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
+ <<<<<<< HEAD
27
  # Check for if item has a Rarity string that is in the dictionary of sticker paths
28
+ =======
29
+ # Check for if item has a Rarity string that is a in the dictionary of sticket paths
30
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
31
  if purchased_item_key:
32
  if sticker_path[purchased_item_key]:
33
  sticker_path = sticker_path[purchased_item_key]
item_dict_gen.py CHANGED
@@ -4,17 +4,32 @@ import gc
4
  import torch
5
 
6
  model_path = "./models/starling-lm-7b-alpha.Q8_0.gguf"
 
7
 
 
 
 
 
 
 
8
  def load_llm(user_input):
9
  llm = Llama(
10
  model_path=model_path,
11
  n_ctx=8192, # The max sequence length to use - note that longer sequence lengths require much more resources
12
  n_threads=8, # The number of CPU threads to use, tailor to your system and the resulting performance
 
13
  n_gpu_layers=32 # The number of layers to offload to GPU, if you have GPU acceleration available
14
  )
15
  return llm(
16
  f"GPT4 User: {prompt_instructions} the item is {user_input}: <|end_of_turn|>GPT4 Assistant:", # Prompt
17
  max_tokens=768, # Generate up to 512 tokens
 
 
 
 
 
 
 
18
  stop=["</s>"], # Example stop token - not necessarily correct for this specific model! Please check before using.
19
  echo=False # Whether to echo the prompt
20
  )
 
4
  import torch
5
 
6
  model_path = "./models/starling-lm-7b-alpha.Q8_0.gguf"
7
+ <<<<<<< HEAD
8
 
9
+ =======
10
+ # Set gpu_layers to the number of layers to offload to GPU. Set to 0 if no GPU acceleration is available on your system.
11
+
12
+
13
+ # Simple inference example
14
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
15
  def load_llm(user_input):
16
  llm = Llama(
17
  model_path=model_path,
18
  n_ctx=8192, # The max sequence length to use - note that longer sequence lengths require much more resources
19
  n_threads=8, # The number of CPU threads to use, tailor to your system and the resulting performance
20
+ <<<<<<< HEAD
21
  n_gpu_layers=32 # The number of layers to offload to GPU, if you have GPU acceleration available
22
  )
23
  return llm(
24
  f"GPT4 User: {prompt_instructions} the item is {user_input}: <|end_of_turn|>GPT4 Assistant:", # Prompt
25
  max_tokens=768, # Generate up to 512 tokens
26
+ =======
27
+ n_gpu_layers=-1 # The number of layers to offload to GPU, if you have GPU acceleration available
28
+ )
29
+ return llm(
30
+ f"GPT4 User: {prompt_instructions} the item is {user_input}: <|end_of_turn|>GPT4 Assistant:", # Prompt
31
+ max_tokens=512, # Generate up to 512 tokens
32
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
33
  stop=["</s>"], # Example stop token - not necessarily correct for this specific model! Please check before using.
34
  echo=False # Whether to echo the prompt
35
  )
main.py CHANGED
@@ -6,6 +6,13 @@ import ctypes
6
  import user_input as useri
7
  import gradio as gr
8
  import template_builder as tb
 
 
 
 
 
 
 
9
 
10
  # 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
11
  libc = ctypes.cdll.LoadLibrary("libc.so.6")
@@ -15,6 +22,13 @@ M_MMAP_THRESHOLD = -3
15
  libc.mallopt(M_MMAP_THRESHOLD, 2**20)
16
  initial_name = "A Crowbar"
17
 
 
 
 
 
 
 
 
18
  with gr.Blocks() as demo:
19
 
20
  # Functions and State Variables
@@ -54,6 +68,7 @@ with gr.Blocks() as demo:
54
  def set_textbox_defaults(textbox_default_dict, key):
55
  item_name = textbox_default_dict[key]
56
  return item_name
 
57
 
58
 
59
  # Function called when user generates item info, then assign values of dictionary to variables, output once to State, twice to textbox
@@ -62,6 +77,23 @@ with gr.Blocks() as demo:
62
  u.reclaim_mem()
63
 
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  llm_output=useri.call_llm(user_input)
66
  item_key = list(llm_output.keys())
67
 
@@ -75,6 +107,7 @@ with gr.Blocks() as demo:
75
  if 'Damage' in item_key_values:
76
  item_damage = llm_output[item_key[0]]['Damage']
77
  else: item_damage = ''
 
78
 
79
 
80
  item_weight = llm_output[item_key[0]]['Weight']
@@ -84,6 +117,13 @@ with gr.Blocks() as demo:
84
  sd_prompt = llm_output[item_key[0]]['SD Prompt']
85
 
86
 
 
 
 
 
 
 
 
87
  return [item_name, item_name,
88
  item_type, item_type,
89
  item_rarity, item_rarity,
@@ -131,21 +171,32 @@ with gr.Blocks() as demo:
131
  return image_list, image_list
132
 
133
 
 
134
  # Beginning of UI Page
135
  # Beginning of UI Page
 
 
 
 
136
  gr.HTML(""" <div id="inner"> <header>
137
  <h1>Item Card Generator</h1>
138
  <p>
139
  With this AI driven tool you will build a collectible style card of a fantasy flavored item with details.
140
  </p>
141
  </div>""")
 
142
 
143
 
 
 
144
  gr.HTML(""" <div id="inner"> <header>
145
  <h2><b>First:</b> Build a Card Template</h2>
146
  </div>""")
147
  with gr.Row():
 
148
  with gr.Column():
 
 
149
 
150
  # Template Gallery instructions
151
  gr.HTML(""" <div id="inner"> <header>
@@ -154,12 +205,17 @@ with gr.Blocks() as demo:
154
 
155
  border_gallery = gr.Gallery(label = "Card Template Gallery",
156
  scale = 2,
 
157
  value = useri.index_image_paths("Drakosfire/CardGenerator", "seed_images/card_templates"),
 
 
 
158
  show_label = True,
159
  columns = [3], rows = [3],
160
  object_fit = "contain",
161
  height = "auto",
162
  elem_id = "Template Gallery")
 
163
 
164
  gr.HTML(""" <div id="inner"> <header>
165
  <h3>2. Click a image from the Seed Image Gallery</h3><br>
@@ -169,16 +225,35 @@ with gr.Blocks() as demo:
169
  seed_image_gallery = gr.Gallery(label= " Image Seed Gallery",
170
  scale = 2,
171
  value = useri.index_image_paths("Drakosfire/CardGenerator", "seed_images/item_seeds"),
 
 
 
 
 
 
 
 
 
 
172
  show_label = True,
173
  columns = [3], rows = [3],
174
  object_fit = "contain",
175
  height = "auto",
176
  elem_id = "Template Gallery",
 
177
  interactive=True)
 
 
 
 
178
 
179
  gr.HTML(""" <div id="inner"> <header><h4> -Or- Upload your own seed image, by dropping it into the 'Generated Template Gallery' </h4><br>
180
  <h3>3. Click 'Generate Card Template'</h3><br>
181
  </div>""")
 
 
 
 
182
 
183
  built_template_gallery = gr.Gallery(label= "Generated Template Gallery",
184
  scale = 1,
@@ -192,6 +267,10 @@ with gr.Blocks() as demo:
192
 
193
  seed_image_gallery.select(assign_img_path, outputs = selected_seed_image)
194
  built_template_gallery.upload(u.receive_upload, inputs=built_template_gallery, outputs= selected_seed_image)
 
 
 
 
195
  build_card_template_button = gr.Button(value = "Generate Card Template")
196
  build_card_template_button.click(build_template, inputs = [selected_border_image, selected_seed_image], outputs = [built_template_gallery, built_template])
197
 
@@ -202,6 +281,11 @@ with gr.Blocks() as demo:
202
  <h3>1. Use a few words to describe the item then click 'Generate Text' </h3>
203
  </div>""")
204
  with gr.Row():
 
 
 
 
 
205
  user_input = gr.Textbox(label = 'Item', lines =1, placeholder= "Flaming Magical Sword", elem_id= "Item", scale =4)
206
  item_text_generate = gr.Button(value = "Generate item text", scale=1)
207
 
@@ -209,11 +293,20 @@ with gr.Blocks() as demo:
209
  <h3> 2. Review and Edit the text</h3>
210
  </div>""")
211
  with gr.Row():
 
212
 
213
  # Build text boxes for the broken up item dictionary values
214
 
215
  # Build text boxes for the broken up item dictionary values
216
  with gr.Column(scale = 1):
 
 
 
 
 
 
 
 
217
  item_name_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Name'),label = 'Name', lines = 1, interactive=True, elem_id='Item Name')
218
  item_type_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Type'),label = 'Type', lines = 1, interactive=True, elem_id='Item Type')
219
  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')
@@ -226,8 +319,11 @@ with gr.Blocks() as demo:
226
  item_description_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Description'),label = 'Description', lines = 1, interactive=True, elem_id='Item Description')
227
  item_quote_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Quote'),label = 'Quote', lines = 1, interactive=True, elem_id='Item quote')
228
  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')
 
229
 
230
 
 
 
231
  gr.HTML(""" <div id="inner"> <header>
232
  <h3> 3. This text will be used to generate the card's image.</h3>
233
  </div>""")
@@ -256,7 +352,11 @@ with gr.Blocks() as demo:
256
  )
257
  generate_final_item_card = gr.Button(value = "Add Text", elem_id = "Generate user card")
258
 
 
259
 
 
 
 
260
  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)
261
  generate_gallery.select(assign_img_path, outputs = selected_generated_image)
262
 
@@ -284,7 +384,12 @@ with gr.Blocks() as demo:
284
  item_sd_prompt_var,
285
  item_sd_prompt_output])
286
 
 
287
 
 
 
 
 
288
  generate_final_item_card.click(card.render_text_on_card, inputs = [selected_generated_image,
289
  item_name_output,
290
  item_type_output,
@@ -298,7 +403,12 @@ with gr.Blocks() as demo:
298
  ],
299
  outputs = generate_gallery )
300
 
 
301
 
 
 
 
 
302
  if __name__ == '__main__':
303
  demo.launch(server_name = "0.0.0.0", server_port = 8000, share = False, allowed_paths = ["/media/drakosfire/Shared/","/media/drakosfire/Shared/MerchantBot/card_templates"])
304
 
 
6
  import user_input as useri
7
  import gradio as gr
8
  import template_builder as tb
9
+ <<<<<<< HEAD
10
+ =======
11
+ import threading
12
+ import time
13
+
14
+
15
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
16
 
17
  # 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
18
  libc = ctypes.cdll.LoadLibrary("libc.so.6")
 
22
  libc.mallopt(M_MMAP_THRESHOLD, 2**20)
23
  initial_name = "A Crowbar"
24
 
25
+ <<<<<<< HEAD
26
+ =======
27
+
28
+
29
+
30
+
31
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
32
  with gr.Blocks() as demo:
33
 
34
  # Functions and State Variables
 
68
  def set_textbox_defaults(textbox_default_dict, key):
69
  item_name = textbox_default_dict[key]
70
  return item_name
71
+ <<<<<<< HEAD
72
 
73
 
74
  # Function called when user generates item info, then assign values of dictionary to variables, output once to State, twice to textbox
 
77
  u.reclaim_mem()
78
 
79
 
80
+ =======
81
+
82
+
83
+
84
+ # Function called when user generates item info, then assign values of dictionary to variables, output once to State, twice to textbox
85
+ def generate_text_update_textboxes(user_input, progress = gr.Progress()):
86
+ u.reclaim_mem()
87
+
88
+ # Define a function to update progress
89
+ def update_progress(duration, progress):
90
+ for i in range(10):
91
+ time.sleep(duration / 10) # Wait for a fraction of the total duration
92
+ progress((i + 1) / 10, desc="Thinking...") # Update progress
93
+ # Start the progress update in a separate thread, passing `progress` explicitly
94
+ threading.Thread(target=update_progress, args=(10, progress)).start()
95
+
96
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
97
  llm_output=useri.call_llm(user_input)
98
  item_key = list(llm_output.keys())
99
 
 
107
  if 'Damage' in item_key_values:
108
  item_damage = llm_output[item_key[0]]['Damage']
109
  else: item_damage = ''
110
+ <<<<<<< HEAD
111
 
112
 
113
  item_weight = llm_output[item_key[0]]['Weight']
 
117
  sd_prompt = llm_output[item_key[0]]['SD Prompt']
118
 
119
 
120
+ =======
121
+ item_weight = llm_output[item_key[0]]['Weight']
122
+ item_description = llm_output[item_key[0]]['Description']
123
+ item_quote = llm_output[item_key[0]]['Quote']
124
+
125
+ sd_prompt = llm_output[item_key[0]]['SD Prompt']
126
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
127
  return [item_name, item_name,
128
  item_type, item_type,
129
  item_rarity, item_rarity,
 
171
  return image_list, image_list
172
 
173
 
174
+ <<<<<<< HEAD
175
  # Beginning of UI Page
176
  # Beginning of UI Page
177
+ =======
178
+ # Beginning of page format
179
+ # Title
180
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
181
  gr.HTML(""" <div id="inner"> <header>
182
  <h1>Item Card Generator</h1>
183
  <p>
184
  With this AI driven tool you will build a collectible style card of a fantasy flavored item with details.
185
  </p>
186
  </div>""")
187
+ <<<<<<< HEAD
188
 
189
 
190
+ =======
191
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
192
  gr.HTML(""" <div id="inner"> <header>
193
  <h2><b>First:</b> Build a Card Template</h2>
194
  </div>""")
195
  with gr.Row():
196
+ <<<<<<< HEAD
197
  with gr.Column():
198
+ =======
199
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
200
 
201
  # Template Gallery instructions
202
  gr.HTML(""" <div id="inner"> <header>
 
205
 
206
  border_gallery = gr.Gallery(label = "Card Template Gallery",
207
  scale = 2,
208
+ <<<<<<< HEAD
209
  value = useri.index_image_paths("Drakosfire/CardGenerator", "seed_images/card_templates"),
210
+ =======
211
+ value = useri.index_image_paths("./seed_images/card_templates/", "card_templates/"),
212
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
213
  show_label = True,
214
  columns = [3], rows = [3],
215
  object_fit = "contain",
216
  height = "auto",
217
  elem_id = "Template Gallery")
218
+ <<<<<<< HEAD
219
 
220
  gr.HTML(""" <div id="inner"> <header>
221
  <h3>2. Click a image from the Seed Image Gallery</h3><br>
 
225
  seed_image_gallery = gr.Gallery(label= " Image Seed Gallery",
226
  scale = 2,
227
  value = useri.index_image_paths("Drakosfire/CardGenerator", "seed_images/item_seeds"),
228
+ =======
229
+ gr.HTML(""" <div id="inner"> <header>
230
+ <h3>2. Click a image from the Seed Image Gallery</h3><br>
231
+ </div>""")
232
+ border_gallery.select(assign_img_path, outputs = selected_border_image)
233
+
234
+ seed_image_gallery = gr.Gallery(label= " Image Seed Gallery",
235
+ scale = 2,
236
+ value = useri.index_image_paths("./seed_images/item_seeds/","item_seeds/"),
237
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
238
  show_label = True,
239
  columns = [3], rows = [3],
240
  object_fit = "contain",
241
  height = "auto",
242
  elem_id = "Template Gallery",
243
+ <<<<<<< HEAD
244
  interactive=True)
245
+ =======
246
+ interactive=True)
247
+
248
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
249
 
250
  gr.HTML(""" <div id="inner"> <header><h4> -Or- Upload your own seed image, by dropping it into the 'Generated Template Gallery' </h4><br>
251
  <h3>3. Click 'Generate Card Template'</h3><br>
252
  </div>""")
253
+ <<<<<<< HEAD
254
+ =======
255
+
256
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
257
 
258
  built_template_gallery = gr.Gallery(label= "Generated Template Gallery",
259
  scale = 1,
 
267
 
268
  seed_image_gallery.select(assign_img_path, outputs = selected_seed_image)
269
  built_template_gallery.upload(u.receive_upload, inputs=built_template_gallery, outputs= selected_seed_image)
270
+ <<<<<<< HEAD
271
+ =======
272
+
273
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
274
  build_card_template_button = gr.Button(value = "Generate Card Template")
275
  build_card_template_button.click(build_template, inputs = [selected_border_image, selected_seed_image], outputs = [built_template_gallery, built_template])
276
 
 
281
  <h3>1. Use a few words to describe the item then click 'Generate Text' </h3>
282
  </div>""")
283
  with gr.Row():
284
+ <<<<<<< HEAD
285
+ =======
286
+
287
+
288
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
289
  user_input = gr.Textbox(label = 'Item', lines =1, placeholder= "Flaming Magical Sword", elem_id= "Item", scale =4)
290
  item_text_generate = gr.Button(value = "Generate item text", scale=1)
291
 
 
293
  <h3> 2. Review and Edit the text</h3>
294
  </div>""")
295
  with gr.Row():
296
+ <<<<<<< HEAD
297
 
298
  # Build text boxes for the broken up item dictionary values
299
 
300
  # Build text boxes for the broken up item dictionary values
301
  with gr.Column(scale = 1):
302
+ =======
303
+ # Build text boxes for the broken up item dictionary values
304
+
305
+ with gr.Column(scale = 1):
306
+
307
+
308
+
309
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
310
  item_name_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Name'),label = 'Name', lines = 1, interactive=True, elem_id='Item Name')
311
  item_type_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Type'),label = 'Type', lines = 1, interactive=True, elem_id='Item Type')
312
  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')
 
319
  item_description_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Description'),label = 'Description', lines = 1, interactive=True, elem_id='Item Description')
320
  item_quote_output = gr.Textbox(value = set_textbox_defaults(textbox_default_dict, 'Quote'),label = 'Quote', lines = 1, interactive=True, elem_id='Item quote')
321
  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')
322
+ <<<<<<< HEAD
323
 
324
 
325
+ =======
326
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
327
  gr.HTML(""" <div id="inner"> <header>
328
  <h3> 3. This text will be used to generate the card's image.</h3>
329
  </div>""")
 
352
  )
353
  generate_final_item_card = gr.Button(value = "Add Text", elem_id = "Generate user card")
354
 
355
+ <<<<<<< HEAD
356
 
357
+ =======
358
+
359
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
360
  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)
361
  generate_gallery.select(assign_img_path, outputs = selected_generated_image)
362
 
 
384
  item_sd_prompt_var,
385
  item_sd_prompt_output])
386
 
387
+ <<<<<<< HEAD
388
 
389
+ =======
390
+
391
+
392
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
393
  generate_final_item_card.click(card.render_text_on_card, inputs = [selected_generated_image,
394
  item_name_output,
395
  item_type_output,
 
403
  ],
404
  outputs = generate_gallery )
405
 
406
+ <<<<<<< HEAD
407
 
408
+ =======
409
+
410
+
411
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
412
  if __name__ == '__main__':
413
  demo.launch(server_name = "0.0.0.0", server_port = 8000, share = False, allowed_paths = ["/media/drakosfire/Shared/","/media/drakosfire/Shared/MerchantBot/card_templates"])
414
 
models ADDED
@@ -0,0 +1 @@
 
 
1
+ /media/drakosfire/Shared/models
user_input.py CHANGED
@@ -5,13 +5,17 @@ import utilities as u
5
  import sys
6
  import tempfile
7
  from PIL import Image
 
8
  from github import Github
 
 
9
 
10
  image_path = str
11
  end_phrase = """<|end_of_turn|>"""
12
  # Indexing the contents of Card templates and temp images
13
  card_template_path = "./card_templates/"
14
  temp_image_path = "./image_temp"
 
15
 
16
  def index_image_paths(repo_name,directory_path):
17
  g = Github() # No token needed for public repos
@@ -24,6 +28,17 @@ def index_image_paths(repo_name,directory_path):
24
  files.append(content_file.download_url) # Or content_file.path for just the path
25
 
26
  return files
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  user_pick_template_prompt = "Pick a template number from this list : "
29
  user_pick_image_prompt = "Select an image : "
@@ -64,7 +79,10 @@ def call_llm(user_input):
64
  response = response
65
 
66
  response = response.replace("GPT4 Assistant: ", "")
 
67
  print(response)
 
 
68
  response = igen.convert_to_dict(response)
69
  if not response:
70
  response = call_llm(user_input)
@@ -81,7 +99,10 @@ def prompt_user_input():
81
  mimic = True
82
 
83
  #user_input_template = input(f"Pick a template number from this list : {process_list_for_user_response(list_of_card_templates)}")
 
84
 
 
 
85
  user_input_template = user_pick_item(user_pick_template_prompt,list_of_card_templates)
86
  response = call_llm(user_input_item)
87
  print(response[u.keys_list(response,0)])
 
5
  import sys
6
  import tempfile
7
  from PIL import Image
8
+ <<<<<<< HEAD
9
  from github import Github
10
+ =======
11
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
12
 
13
  image_path = str
14
  end_phrase = """<|end_of_turn|>"""
15
  # Indexing the contents of Card templates and temp images
16
  card_template_path = "./card_templates/"
17
  temp_image_path = "./image_temp"
18
+ <<<<<<< HEAD
19
 
20
  def index_image_paths(repo_name,directory_path):
21
  g = Github() # No token needed for public repos
 
28
  files.append(content_file.download_url) # Or content_file.path for just the path
29
 
30
  return files
31
+ =======
32
+ def index_image_paths(directory_path, github_path):
33
+ list_temp_files = []
34
+ list_of_image_paths = u.directory_contents(directory_path)
35
+ for image_path in list_of_image_paths:
36
+ image_path = f"https://raw.githubusercontent.com/Drakosfire/CardGenerator/alpha-templates/seed_images/{github_path}{image_path}"
37
+ print(image_path)
38
+ list_temp_files.append(image_path)
39
+ return list_temp_files
40
+
41
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
42
 
43
  user_pick_template_prompt = "Pick a template number from this list : "
44
  user_pick_image_prompt = "Select an image : "
 
79
  response = response
80
 
81
  response = response.replace("GPT4 Assistant: ", "")
82
+ <<<<<<< HEAD
83
  print(response)
84
+ =======
85
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
86
  response = igen.convert_to_dict(response)
87
  if not response:
88
  response = call_llm(user_input)
 
99
  mimic = True
100
 
101
  #user_input_template = input(f"Pick a template number from this list : {process_list_for_user_response(list_of_card_templates)}")
102
+ <<<<<<< HEAD
103
 
104
+ =======
105
+ >>>>>>> 9a956dd (Polished and launch to Hugging Face)
106
  user_input_template = user_pick_item(user_pick_template_prompt,list_of_card_templates)
107
  response = call_llm(user_input_item)
108
  print(response[u.keys_list(response,0)])