DnD / app.py
Ceetar's picture
updates
284cb79
raw
history blame contribute delete
No virus
7.64 kB
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()