File size: 7,641 Bytes
68e9609 857d94b c5d56ba 03963fa 99ac7e3 03963fa e338f7b 03963fa e338f7b 03963fa 99ac7e3 03963fa e338f7b 03963fa e338f7b d3811c5 9f3ddf9 8061c4b 90a7e3d 8061c4b e338f7b 8061c4b e338f7b 857d94b 32a351c 857d94b 8061c4b e338f7b 8061c4b e338f7b 03963fa 857d94b 03963fa 90a7e3d 03963fa 90a7e3d 03963fa 90a7e3d 857d94b 90a7e3d 03963fa 90a7e3d 0daefef 284cb79 0daefef 68e9609 0daefef 90a7e3d 0daefef 90a7e3d 0daefef 90a7e3d 03963fa 0daefef 03963fa 90a7e3d 0daefef 90a7e3d 03963fa 0daefef 99ac7e3 d305a6e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 |
import gradio as gr
import openai
import os
import IPython
import random
import requests
import json
import time
import math
import io
from stability_sdk import client as sclient
from io import BytesIO
from dotenv import load_dotenv
from openai import OpenAI
from PIL import Image
import stability_sdk.interfaces.gooseai.generation.generation_pb2 as generation
load_dotenv()
sdurl = "https://stablediffusionapi.com/api/v3/text2img"
openai.api_key = os.getenv('OPENAI_API_KEY')
#print(openai.api_key)
#print (os.environ.get("OPENAI_API_KEY"))
client = openai.OpenAI(organization='org-eiNl8e4nk93VLQFDb4EBz9JG')
#openai.api_key = os.environ['openai'] #for huggingface i think
os.environ['STABILITY_HOST'] = 'grpc.stability.ai:443'
stability_api = sclient.StabilityInference(
key=os.getenv('STABILITY_KEY'),
verbose=True,
engine="stable-diffusion-xl-1024-v1-0"
)
#generates an AI picture of your char
def draw(thechar):
thechar=thechar.split("$$$")[0].strip()
moretime=50
cfg=8.0
noinit=0
r2="1"
r3="1"
filename="drunkgrogu"+str(r2)+".png"
filenamefilter="calvin"+str(r3)+".png"
#await ctx.channel.send(file=discord.File(filename))
#stable-diffusion-xl-1024-v0-9
notoldguy="bad anatomy, fuzzy, out of focus, cut off, low res"
try :
if noinit :
print("initimg")
answers = stability_api.generate(
prompt=[generation.Prompt(text=thechar,parameters=generation.PromptParameters(weight=1)),
generation.Prompt(text=notoldguy,parameters=generation.PromptParameters(weight=-1))],
steps=moretime, # defaults to 50 if not specified
)
else :
print("noinitimg:"+thechar+"\nneg:"+notoldguy)
answers = stability_api.generate(
prompt=[generation.Prompt(text=thechar,parameters=generation.PromptParameters(weight=1)),
generation.Prompt(text=notoldguy,parameters=generation.PromptParameters(weight=-1))],
cfg_scale=cfg,
steps=moretime, # defaults to 50 if not specified
width=1024,
height=1024
)
except Exception as eeeee :
print(eeeee)
try :
# iterating over the generator produces the api response
for resp in answers:
#print(resp)
for artifact in resp.artifacts:
#print("fin rease:"+str(artifact.finish_reason))
if artifact.finish_reason == generation.FILTER:
if random.randrange(0,2)==1 :
print("await ctx.channel.send(file=discord.File(filenamefilter))")
else :
print(" await ctx.channel.send(file=discord.File(filename))")
#warnings.warn("Your request activated the API's safety filters and could not be processed. Please modify the prompt and try again.")
if artifact.type == generation.ARTIFACT_IMAGE:
#print("we got an image")
img = Image.open(io.BytesIO(artifact.binary))
#oldoldguy=oldoldguy.replace("|","--")
# oldoldguy = oldoldguy.replace("*","")
#metadata = PngInfo()
#metadata.add_text("prompt", oldguy)
thechar=thechar.replace("Character Description","")
filename="dndChar"+str(math.trunc(time.time()))+thechar[:80].replace("\n","").replace(",","")
filename=filename[:245]+".png"
img.save(filename)
##filename="image5r"+str(math.trunc(time.time()))+".png"
#print(str(img))
##filename=filename[:245]+".png"
#print(filename)
##img.save(filename)
#filename="image5r"+str(math.trunc(time.time()))+".png"
#img.save(filename)
#display(img)
except Exception as eeee :
print(eeee.details)
print("Error. Have a random image instead:");
#print(response.text)
#print(response.output)
print(filename)
imageBox = gr.Image(value=Image.open(filename))
imageBox2 = img
return img
#generates an AI description of your character
def describe(names,wis,char,str,int,dex,con):
print(f"hi{names}")
if (wis==0) :
print(f"set some stats or roll random")
exit
prom=f"We're generating Dungeons and Dragons characters for a new campaign, and we need a brief character description, including race"
prom+=f" and class. The character's name is {names} with the following stats: Wisdom: {wis},Charisma:{char},Strength:{str},"
prom+=f"Intelligence:{int},Dexterity:{dex},Constitution:{con}. Describe the character, and then, separated by $$$ give us the "
prom+=f"character's interesting backstory."
completion = client.completions.create(
model='gpt-3.5-turbo-instruct',
prompt=prom,
max_tokens=510,
temperature=0.77,
frequency_penalty=0.2,
presence_penalty= 0.25)
result =completion.choices[0].text
#print(dict(completion).get('usage'))
#print(completion.model_dump_json(indent=2))
if not result :
result = "Could you be any more boring?"
#draw(result.split("$$$")[0],outputs=imageBox2)
return result#result.replace("$$$","")
#generates an AI nam,
def makeName():
prom=f"We're generating Dungeons and Dragons characters for a new campaign, and we need a good, original name."
prom+=f" Please imagine and give me just a character name for the player to use. Be creative and fun. No duds."
completion = client.completions.create(
model='gpt-3.5-turbo-instruct',
prompt=prom,
max_tokens=50,
temperature=0.97)
result =completion.choices[0].text
#print(dict(completion).get('usage'))
#print(completion.model_dump_json(indent=2))
if not result :
result = "The Doctor"
return result.strip()
def stat( ndice, dicerank):
# return ndice + dicerank
answer=[]
for x in range(6) :
results = [ # Generate ndice numbers between [1,dice_rank]
random.randint(1, dicerank)
for n
in range(ndice)
]
lowest = min(results) # Find the lowest roll among the results
results.remove(lowest) # Remove the first instance of that lowest roll
answer.append(sum(results)) # Return the sum of the remaining results.
return answer
with gr.Blocks() as statBlock:
gr.Markdown("Your characters stats")
nameBox = gr.Textbox(label="Your DND character",show_label=True)
nameButt = gr.Button(value="Random Name")
wisBox = gr.Number(label="Wisdom",show_label=True,precision=0,minimum=1,maximum=18)
charBox = gr.Number(label="Charisma",show_label=True,precision=0)
strBox =gr.Number(label="Strength",show_label=True,precision=0)
intBox =gr.Number(label="Intelligence",show_label=True,precision=0)
dexBox =gr.Number(label="Dexterity",show_label=True,precision=0)
conBox =gr.Number(label="Constitution",show_label=True,precision=0)
dice = gr.Number(value=4,precision=0,visible=False)
dice.visible = False
rollButt = gr.Button(value="Roll Stats")
describeButt = gr.Button(value="Generate Description")
imgButt = gr.Button(value="Generate Image")
outputBox=gr.Textbox(label="The character",show_label=True)
imageBox = gr.Image()
imageBox2 = gr.Image()
nameButt.click(makeName,inputs=[],outputs=[nameBox])
rollButt.click(stat, inputs=[dice,gr.Number(value=6, visible=False,precision=0)],outputs=[wisBox,charBox,strBox,intBox,dexBox,conBox])
describeButt.click(describe, outputs=[outputBox],inputs=[nameBox,wisBox,charBox,strBox,intBox,dexBox,conBox])
imgButt.click(draw,inputs=[outputBox],outputs=[imageBox2])
statBlock.launch()
|