GameConfigIdea / app.py
kwabs22
More considerations
32e1b31
raw
history blame
119 kB
import gradio as gr
import random
import json
import re
import os
import shutil
from PIL import Image
import spaces
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
from threading import Thread
import time
import psutil
from sentence_transformers import SentenceTransformer
import textwrap
from gradio_client import Client
import gc
import sys
#Imported Long Variables - comment for each move to search
from relatively_constant_variables import *
# # # Initialize the zero tensor on CUDA
# zero = torch.Tensor([0]).cuda()
# print(zero.device) # This will print 'cpu' outside the @spaces.GPU decorated function
# # Load the embedding model
# embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
# # Load the Qwen model and tokenizer
# llmguide_model = AutoModelForCausalLM.from_pretrained(
# "Qwen/Qwen2-0.5B-Instruct",
# torch_dtype="auto",
# device_map="auto"
# )
# llmguide_tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
# #import knowledge_base from relatively_constant_variables
# # Create embeddings for the knowledge base
# knowledge_base_embeddings = embedding_model.encode([doc["content"] for doc in knowledge_base])
# def retrieve(query, k=2):
# query_embedding = embedding_model.encode([query])
# similarities = torch.nn.functional.cosine_similarity(torch.tensor(query_embedding), torch.tensor(knowledge_base_embeddings))
# top_k_indices = similarities.argsort(descending=True)[:k]
# return [(knowledge_base[i]["content"], knowledge_base[i]["id"]) for i in top_k_indices]
# def get_ram_usage():
# ram = psutil.virtual_memory()
# return f"RAM Usage: {ram.percent:.2f}%, Available: {ram.available / (1024 ** 3):.2f}GB, Total: {ram.total / (1024 ** 3):.2f}GB"
# @spaces.GPU
# def llmguide_generate_response(prompt, doc_ids=None, stream=False):
# print(zero.device) # This will print 'cuda:0' inside the @spaces.GPU decorated function
# messages = [
# {"role": "system", "content": "You are a helpful assistant."},
# {"role": "user", "content": prompt}
# ]
# text = llmguide_tokenizer.apply_chat_template(
# messages,
# tokenize=False,
# add_generation_prompt=True
# )
# model_inputs = llmguide_tokenizer([text], return_tensors="pt").to(llmguide_model.device)
# start_time = time.time()
# total_tokens = 0
# if stream:
# streamer = TextIteratorStreamer(llmguide_tokenizer, skip_special_tokens=True)
# generation_kwargs = dict(
# model_inputs,
# streamer=streamer,
# max_new_tokens=512,
# temperature=0.7,
# )
# thread = Thread(target=llmguide_model.generate, kwargs=generation_kwargs)
# thread.start()
# generated_text = ""
# for new_text in streamer:
# generated_text += new_text
# total_tokens += 1
# current_time = time.time()
# tokens_per_second = total_tokens / (current_time - start_time)
# yield generated_text, f"{tokens_per_second:.2f}", "", ", ".join(doc_ids) if doc_ids else "N/A"
# ram_usage = get_ram_usage()
# yield generated_text, f"{tokens_per_second:.2f}", ram_usage, ", ".join(doc_ids) if doc_ids else "N/A"
# else:
# generated_ids = llmguide_model.generate(
# model_inputs.input_ids,
# max_new_tokens=512
# )
# generated_ids = [
# output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
# ]
# response = llmguide_tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
# total_tokens = len(generated_ids[0])
# end_time = time.time()
# tokens_per_second = total_tokens / (end_time - start_time)
# ram_usage = get_ram_usage()
# yield response, f"{tokens_per_second:.2f}", ram_usage, ", ".join(doc_ids) if doc_ids else "N/A"
# def process_query(query, use_rag, stream=False):
# if use_rag:
# retrieved_docs = retrieve(query)
# context = " ".join([doc for doc, _ in retrieved_docs])
# doc_ids = [doc_id for _, doc_id in retrieved_docs]
# prompt = f"Context: {context}\nQuestion: {query}\nAnswer:"
# else:
# prompt = query
# doc_ids = None
# generator = llmguide_generate_response(prompt, doc_ids, stream)
# if stream:
# def stream_output():
# for generated_text, tokens_per_second, ram_usage, doc_references in generator:
# yield generated_text, tokens_per_second, ram_usage, doc_references
# return stream_output()
# else:
# # For non-streaming, we just need to get the final output
# for generated_text, tokens_per_second, ram_usage, doc_references in generator:
# pass # This will iterate to the last yield
# return generated_text, tokens_per_second, ram_usage, doc_references
#importing FAQAllprompts from relatively_constant_variables
#----Refactor-----
# Initialize the zero tensor on CUDA
zero = torch.Tensor([0]).cuda()
print(zero.device) # This will print 'cpu' outside the @spaces.GPU decorated function
modelnames = ["Qwen/Qwen2-0.5B-Instruct", "Qwen/Qwen2-1.5B-Instruct", "Qwen/Qwen2-7B-Instruct", "Qwen/Qwen1.5-MoE-A2.7B-Chat", "HuggingFaceTB/SmolLM-135M-Instruct", "microsoft/Phi-3-mini-4k-instruct",
"unsloth/Mistral-Nemo-Instruct-2407-bnb-4bit", "Groq/Llama-3-Groq-8B-Tool-Use", "hugging-quants/Meta-Llama-3.1-8B-Instruct-BNB-NF4", "SpectraSuite/TriLM_3.9B_Unpacked", "h2oai/h2o-danube3-500m-chat"
"OuteAI/Lite-Mistral-150M-v2-Instruct"]
current_model_index = 5
modelname = modelnames[current_model_index]
lastmodelnameinloadfunction = None
# Load the embedding model
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
# Initialize model and tokenizer as global variables
model = None
tokenizer = None
def get_size_str(bytes):
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if bytes < 1024:
return f"{bytes:.2f} {unit}"
bytes /= 1024
def load_model(model_name):
global model, tokenizer, lastmodelnameinloadfunction
print(f"Loading model and tokenizer: {model_name}")
# Record initial GPU memory usage
initial_memory = torch.cuda.memory_allocated()
# Clear old model and tokenizer if they exist
if 'model' in globals() and model is not None:
model = None
if 'tokenizer' in globals() and tokenizer is not None:
tokenizer = None
torch.cuda.empty_cache()
gc.collect()
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype="auto",
device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(model_name)
# Calculate memory usage
final_memory = torch.cuda.memory_allocated()
memory_used = final_memory - initial_memory
model_size = sum(p.numel() * p.element_size() for p in model.parameters())
tokenizer_size = sum(sys.getsizeof(v) for v in tokenizer.__dict__.values())
lastmodelnameinloadfunction = (model_name, model_size, tokenizer_size)
print(f"Model and tokenizer {model_name} loaded successfully")
print(f"Model size: {get_size_str(model_size)}")
print(f"Tokenizer size: {get_size_str(tokenizer_size)}")
print(f"GPU memory used: {get_size_str(memory_used)}")
return (f"Model and tokenizer {model_name} loaded successfully. "
f"Model size: {get_size_str(model_size)}, "
f"Tokenizer size: {get_size_str(tokenizer_size)}, "
f"GPU memory used: {get_size_str(memory_used)}")
# Initial model load
load_model(modelname)
# For this example, let's use a knowledge base with close queries
# knowledge_base = [
# {"id": "1", "content": "The capital of France is Paris. It's known for the Eiffel Tower."},
# {"id": "2", "content": "The capital of Italy is Rome. It's famous for the Colosseum."},
# {"id": "3", "content": "Python is a popular programming language, known for its simplicity."},
# {"id": "4", "content": "Java is a widely-used programming language, valued for its portability."},
# {"id": "5", "content": "Machine learning is a subset of artificial intelligence focused on data-driven learning."},
# {"id": "6", "content": "Deep learning is a part of machine learning based on artificial neural networks."},
# {"id": "7", "content": "Law is a Tekken character"},
# {"id": "8", "content": "The law is very complicated"},
# ]
# Create embeddings for the knowledge base
knowledge_base_embeddings = embedding_model.encode([doc["content"] for doc in knowledge_base])
def retrieve(query, k=2):
query_embedding = embedding_model.encode([query])
similarities = torch.nn.functional.cosine_similarity(torch.tensor(query_embedding), torch.tensor(knowledge_base_embeddings))
top_k_indices = similarities.argsort(descending=True)[:k]
return [(knowledge_base[i]["content"], knowledge_base[i]["id"]) for i in top_k_indices]
def get_ram_usage():
ram = psutil.virtual_memory()
return f"RAM Usage: {ram.percent:.2f}%, Available: {ram.available / (1024 ** 3):.2f}GB, Total: {ram.total / (1024 ** 3):.2f}GB"
# Global dictionary to store outputs
output_dict = {}
def empty_output_dict():
global output_dict
output_dict = {}
print("Output dictionary has been emptied.")
def get_model_details(model):
return {
"name": model.config.name_or_path,
"architecture": model.config.architectures[0] if model.config.architectures else "Unknown",
"num_parameters": sum(p.numel() for p in model.parameters()),
}
def get_tokenizer_details(tokenizer):
return {
"name": tokenizer.__class__.__name__,
"vocab_size": tokenizer.vocab_size,
"model_max_length": tokenizer.model_max_length,
}
@spaces.GPU
def generate_response(prompt, use_rag, stream=False):
global output_dict
print(zero.device) # This will print 'cuda:0' inside the @spaces.GPU decorated function
if use_rag:
retrieved_docs = retrieve(prompt)
context = " ".join([doc for doc, _ in retrieved_docs])
doc_ids = [doc_id for _, doc_id in retrieved_docs]
full_prompt = f"Context: {context}\nQuestion: {prompt}\nAnswer:"
else:
full_prompt = prompt
doc_ids = None
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": full_prompt}
]
text = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
model_inputs = tokenizer([text], return_tensors="pt").to(zero.device)
start_time = time.time()
total_tokens = 0
print(output_dict)
output_key = f"output_{len(output_dict) + 1}"
print(output_key)
output_dict[output_key] = {
"input_prompt": prompt,
"full_prompt": full_prompt,
"use_rag": use_rag,
"generated_text": "",
"tokens_per_second": 0,
"ram_usage": "",
"doc_ids": doc_ids if doc_ids else "N/A",
"model_details": get_model_details(model),
"tokenizer_details": get_tokenizer_details(tokenizer),
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(start_time))
}
print(output_dict)
if stream:
streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True)
generation_kwargs = dict(
model_inputs,
streamer=streamer,
max_new_tokens=512,
temperature=0.7,
)
thread = Thread(target=model.generate, kwargs=generation_kwargs)
thread.start()
for new_text in streamer:
output_dict[output_key]["generated_text"] += new_text
total_tokens += 1
current_time = time.time()
tokens_per_second = total_tokens / (current_time - start_time)
ram_usage = get_ram_usage()
output_dict[output_key]["tokens_per_second"] = f"{tokens_per_second:.2f}"
output_dict[output_key]["ram_usage"] = ram_usage
yield (output_dict[output_key]["generated_text"],
output_dict[output_key]["tokens_per_second"],
output_dict[output_key]["ram_usage"],
output_dict[output_key]["doc_ids"])
else:
generated_ids = model.generate(
model_inputs.input_ids,
max_new_tokens=512
)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
total_tokens = len(generated_ids[0])
end_time = time.time()
tokens_per_second = total_tokens / (end_time - start_time)
ram_usage = get_ram_usage()
output_dict[output_key]["generated_text"] = response
output_dict[output_key]["tokens_per_second"] = f"{tokens_per_second:.2f}"
output_dict[output_key]["ram_usage"] = ram_usage
print(output_dict)
yield (output_dict[output_key]["generated_text"],
output_dict[output_key]["tokens_per_second"],
output_dict[output_key]["ram_usage"],
output_dict[output_key]["doc_ids"])
def get_output_details(output_key):
if output_key in output_dict:
return output_dict[output_key]
else:
return f"No output found for key: {output_key}"
# Update the switch_model function to return the load_model message
def switch_model(choice):
global modelname
modelname = choice
load_message = load_model(modelname)
return load_message, f"Current model: {modelname}"
# Update the model_change_handler function
def model_change_handler(choice):
message, current_model = switch_model(choice)
return message, current_model, message # Use the same message for both outputs
def format_output_dict():
global output_dict
formatted_output = ""
for key, value in output_dict.items():
formatted_output += f"Key: {key}\n"
formatted_output += json.dumps(value, indent=2)
formatted_output += "\n\n"
print(formatted_output)
return formatted_output
#--------------------------------------------------------------------------------------------------------------------------------
#importing default_config from relatively_constant_variables
# Helper functions to dynamically add items
def add_inventory_item(inventory_items, type, name, description):
new_item = {"type": type, "name": name, "description": description}
inventory_items.append(new_item)
return inventory_items
def add_skill(skills_items, branch, name, learned):
new_skill = {"branch": branch, "name": name, "learned": learned == 'True'}
skills_items.append(new_skill)
return skills_items
def add_objective(objectives_items, id, name, complete):
new_objective = {"id": id, "name": name, "complete": complete == 'True'}
objectives_items.append(new_objective)
return objectives_items
def add_target(targets_items, name, x, y, collisionType, collisiontext):
new_target = {"name": name, "x": int(x), "y": int(y), "collisionType": collisionType, "collisiontext": collisiontext}
targets_items.append(new_target)
return targets_items
#-----------------------------------------------------------------------------------------------------------------------------------
#importing player_engagement_items and story_events from relatively_constant_variables
def pick_random_items(items, n):
return random.sample(items, n)
def generate_timeline(events, label):
timeline = []
for event in events:
timeline.append((random.randint(1, 100), label, event))
return timeline
def create_story(timeline):
story = []
for entry in timeline:
if entry[1] == "Story":
story.append(f"The hero {entry[2].replace('engageBattle', 'engaged in a fierce battle').replace('solveRiddle', 'solved a complex riddle').replace('exploreLocation', 'explored a mysterious location')}.")
else:
story.append(f"The player interacted with {entry[2]}.")
return " ".join(story)
def generate_story_and_timeline(no_story_timeline_points=10, no_ui_timeline_points=10, num_lists=1, items_per_list=1, include_existing_games=False, include_multiplayer=False): # , no_media_timeline_points=5, include_media=True):
# Pick 10 random UI items
random_ui_items = pick_random_items(player_engagement_items, no_ui_timeline_points)
random_story_items = pick_random_items(story_events, no_story_timeline_points)
# Generate UI and story timelines
ui_timeline = generate_timeline(random_ui_items, "UI")
story_timeline = generate_timeline(random_story_items, "Story")
# Initialize merged timeline with UI and story timelines
merged_timeline = ui_timeline + story_timeline
#no_media_merged_timeline = ui_timeline + story_timeline
#print(merged_timeline)
#print(no_media_merged_timeline)
# Include media-related items if specified
# if include_media:
# media_files = generate_media_file_list(no_media_timeline_points)
# #rendered_media = render_media_with_dropdowns(media_files)
# media_timeline = generate_timeline(media_files, "Media")
# merged_timeline += media_timeline
# print(merged_timeline)
# Sort the merged timeline based on the random numbers
merged_timeline.sort(key=lambda x: x[0])
# no_media_merged_timeline.sort(key=lambda x: x[0])
# Create the story
story = create_story(merged_timeline)
# Format the timeline for display
formatted_timeline = "\n".join([f"{entry[0]}: {entry[1]} - {entry[2]}" for entry in merged_timeline])
# no_media_formatted_timeline = "\n".join([f"{entry[0]}: {entry[1]} - {entry[2]}" for entry in no_media_merged_timeline])
# game_structure_with_media = generate_game_structures(formatted_timeline) #, game_structure_without_media = generate_game_structures(formatted_timeline, no_media_formatted_timeline)
game_structure_with_media = convert_timeline_to_game_structure(formatted_timeline)
print("simulplay debug - good to here 4")
suggestions, selected_list_names = timeline_get_random_suggestions(num_lists, items_per_list, include_existing_games, include_multiplayer)
print("simulplay debug - good to here 4")
return formatted_timeline, story, json.dumps(game_structure_with_media, indent=2), suggestions, selected_list_names #no_media_formatted_timeline, json.dumps(game_structure_without_media, indent=2) #, game_structure_with_media
media_file_types = ["image", "video", "audio"]
def generate_media_file_list(n):
return [random.choice(media_file_types) for _ in range(n)]
def show_elements(text):
# Parse the input text
pattern = r'(\d+): (UI|Story|Media) - (.+)'
blocks = re.findall(pattern, text)
# Sort blocks by their timestamp
blocks.sort(key=lambda x: int(x[0]))
outputs = []
for timestamp, block_type, content in blocks:
if block_type == 'UI':
# Create HTML for UI elements
ui_html = f'<div class="ui-element">{content}</div>'
outputs.append(gr.HTML(ui_html))
elif block_type == 'Story':
# Display story elements as Markdown
outputs.append(gr.Markdown(f"**{content}**"))
elif block_type == 'Media':
if content.lower() == 'audio':
# Placeholder for audio element
outputs.append(gr.Audio(label=f"Audio at {timestamp} in the order"))
elif content.lower() == 'video':
# Placeholder for video element
outputs.append(gr.Video(label=f"Video at {timestamp} in the order"))
elif content.lower() == 'image':
# Placeholder for image element
outputs.append(gr.Image(label=f"Image at {timestamp} in the order"))
return outputs
def show_elements_json_input(json_input):
data = json.loads(json_input)
masterlocation1 = data['masterlocation1']
outputs = []
for location, details in masterlocation1.items():
if location == 'end':
continue
with gr.Accordion(f"Location: {location} - Previous description {details['description']}", open=False):
description = gr.Textbox(label="Description", value=details['description'], interactive=True)
outputs.append(description)
events = gr.Textbox(label="Events", value=json.dumps(details['events']), interactive=True)
outputs.append(events)
choices = gr.Textbox(label="Choices", value=json.dumps(details['choices']), interactive=True)
outputs.append(choices)
transitions = gr.Textbox(label="Transitions", value=json.dumps(details['transitions']), interactive=True)
outputs.append(transitions)
# New media field
media = gr.Textbox(label="Media", value=json.dumps(details['media']), interactive=True)
outputs.append(media)
# New developernotes field
developernotes = gr.Textbox(label="developernotes", value=json.dumps(details['developernotes']), interactive=True)
outputs.append(developernotes)
#adding/removing a field means incrementing/decreasing the i+n to match the fields
num_current_unique_fields = 6
def update_json(*current_values):
updated_data = {"masterlocation1": {}}
locations = [loc for loc in masterlocation1.keys() if loc != 'end']
for i, location in enumerate(locations):
updated_data["masterlocation1"][location] = {
"description": current_values[i*num_current_unique_fields],
"events": json.loads(current_values[i*num_current_unique_fields + 1]),
"choices": json.loads(current_values[i*num_current_unique_fields + 2]),
"transitions": json.loads(current_values[i*num_current_unique_fields + 3]),
"media": json.loads(current_values[i*num_current_unique_fields + 4]), # New media field
"developernotes": json.loads(current_values[i*num_current_unique_fields + 5])
}
updated_data["masterlocation1"]["end"] = masterlocation1["end"]
return json.dumps(updated_data, indent=2) #json.dumps(updated_data, default=lambda o: o.__dict__, indent=2)
update_button = gr.Button("Update JSON - Still need to copy to correct textbox to load")
json_output = gr.Textbox(label="Updated JSON - Still need to copy to correct textbox to load", lines=10)
#json_output = gr.Code(label="Updated JSON", lines=10) #Locks whole UI so use textbox
update_button.click(update_json, inputs=outputs, outputs=json_output)
return outputs + [update_button, json_output] #, json_output_code]
def create_media_component(file_path):
print(file_path)
_, extension = os.path.splitext(file_path)
extension = extension.lower()[1:] # Remove the dot and convert to lowercase
if extension in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
return gr.Image(value=file_path, label="Image Input")
elif extension in ['mp4', 'avi', 'mov']:
return gr.Video(value=file_path, label="Video Input")
elif extension in ['mp3', 'wav', 'ogg']:
return gr.Audio(value=file_path, label="Audio Input")
else:
return gr.Textbox(value=file_path, label=f"File: {os.path.basename(file_path)}")
def convert_timeline_to_game_structure(timeline):
lines = timeline.split('\n')
game_structure = {}
current_location = 0
sub_location = 0
for i, line in enumerate(lines):
if line.strip() == "":
continue
if line[0].isdigit(): # New location starts
current_location += 1
sub_location = 0
location_key = f"location{current_location}"
game_structure[location_key] = {
"description": "",
"events": [],
"choices": ["continue"],
"transitions": {},
"media": [],
"developernotes": []
}
else: # Continue with sub-locations or media entries
sub_location += 1
location_key = f"location{current_location}_{sub_location}"
# Extract the event description
parts = line.split(': ', 1)
if len(parts) == 2:
prefix, rest = parts
event_parts = rest.split(' - ', 1)
if len(event_parts) == 2:
event_type, event_description = event_parts
else:
event_type, event_description = "Unknown", rest
else:
event_type, event_description = "Unknown", line
description = rest.strip() if event_type in ["Media", "UI"] else f"{event_type}: {event_description}"
if sub_location == 0:
game_structure[f"location{current_location}"]["description"] = description
else:
game_structure[f"location{current_location}"]["events"].append({
"description": description,
"type": event_type
})
# Set the transition to the next location or to the end
if i < len(lines) - 1:
next_line = lines[i + 1].strip()
if next_line and next_line[0].isdigit(): # New location starts
game_structure[f"location{current_location}"]["transitions"]["continue"] = f"masterlocation1_location{current_location + 1}"
else:
#game_structure[f"location{current_location}"]["transitions"]["continue"] = f"location_{current_location}_{sub_location + 1}"
game_structure[f"location{current_location}"]["transitions"]["continue"] = "end"
else:
game_structure[f"location{current_location}"]["transitions"]["continue"] = "end"
# Add an end location
game_structure["end"] = {
"description": "The adventure ends here.",
# "choices": [],
# "transitions": {}
"choices": ["restart"],
"transitions": {"restart": "location1"} # Assuming location_1 is the start
}
# Wrap the game structure in master_location1
wrapped_structure = {"masterlocation1": game_structure}
return wrapped_structure
# def generate_game_structures(timeline_with_media): #, timeline_without_media):
# game_structure_with_media = convert_timeline_to_game_structure(timeline_with_media)
# #game_structure_without_media = convert_timeline_to_game_structure(timeline_without_media)
# return game_structure_with_media #, game_structure_without_media
# def timeline_get_random_suggestions(num_lists, items_per_list):
# """
# Generate random suggestions from a specified number of lists.
# :param num_lists: Number of lists to consider
# :param items_per_list: Number of items to select from each list
# :return: A list of randomly selected suggestions
# """
# selected_lists = random.sample(all_idea_lists, min(num_lists, len(all_idea_lists)))
# suggestions = []
# for lst in selected_lists:
# suggestions.extend(random.sample(lst, min(items_per_list, len(lst))))
# return suggestions
def timeline_get_random_suggestions(num_lists, items_per_list, include_existing_games, include_multiplayer):
"""
Generate random suggestions from a specified number of lists.
:param num_lists: Number of lists to consider
:param items_per_list: Number of items to select from each list
:param include_existing_games: Whether to include existing game inspiration lists
:param include_multiplayer: Whether to include multiplayer features list
:return: A tuple containing the list of randomly selected suggestions and the names of selected lists
"""
available_lists = all_idea_lists.copy()
if not include_existing_games:
available_lists = [lst for lst in available_lists if lst not in existing_game_inspirations]
if not include_multiplayer:
available_lists = [lst for lst in available_lists if lst != multiplayer_features]
selected_lists = random.sample(available_lists, min(num_lists, len(available_lists)))
suggestions = []
selected_list_names = []
for lst in selected_lists:
suggestions.extend(random.sample(lst, min(items_per_list, len(lst))))
selected_list_names.append(list_names[all_idea_lists.index(lst)])
return suggestions, selected_list_names
#-----------------------------------------------------------------------------------------------------------------------------------
class Player:
def __init__(self):
self.inventory = []
self.money = 20
self.knowledge = {}
def add_item(self, item):
self.inventory.append(item)
def has_item(self, item):
return item in self.inventory
def update_knowledge(self, topic):
self.knowledge[topic] = True
#importing all_states from relatively_constant_variables
def validate_transitions(all_states):
errors = []
for location, states in all_states.items():
for state_key, state in states.items():
for transition_key, transition_state in state['transitions'].items():
# Check if the transition is to another location
if transition_state in all_states:
trans_location, trans_state = transition_state, 'start' # Assuming 'start' state for new locations
elif '_' in transition_state:
trans_location, trans_state = transition_state.split('_')
else:
trans_location, trans_state = location, transition_state
# Validate the transition state
if trans_location not in all_states or trans_state not in all_states[trans_location]:
errors.append(f"Invalid transition from {location}.{state_key} to {trans_location}.{trans_state}")
return errors
path_errors = validate_transitions(all_states)
if path_errors:
for error in path_errors:
print(error)
else:
print("All transitions are valid.")
class GameSession:
def __init__(self, starting_location='village', starting_state='start'):
self.player = Player()
self.current_location = starting_location
self.current_state = starting_state
self.game_log = []
def make_choice(self, choice_index):
state = all_states[self.current_location][self.current_state]
if 0 <= choice_index < len(state['choices']):
choice = state['choices'][choice_index]
next_state = state['transitions'][choice]
self.game_log.append(f"You chose: {choice}")
self.game_log.append(state['description'])
if 'consequences' in state and choice in state['consequences']:
if state['consequences'][choice]:
state['consequences'][choice](self.player)
else:
# Handle empty consequence, e.g., log a message or provide a default action
print(f"No consequence for choice: {choice}")
# You can add any default action here if needed
if '_' in next_state:
self.current_location, self.current_state = next_state.split('_')
else:
self.current_state = next_state
return self.get_current_state_info()
else:
return "Invalid choice. Please try again."
def get_current_state_info(self):
state = all_states[self.current_location][self.current_state]
choices = [f"{idx + 1}. {choice}" for idx, choice in enumerate(state['choices'])]
return state['description'], choices, "\n".join(self.game_log)
def get_current_state_media(self):
media = all_states[self.current_location][self.current_state]['media']
return media
def start_game(starting_location='village', starting_state='start'):
game_session = GameSession(starting_location, starting_state)
description, choices, game_log = game_session.get_current_state_info()
return description, choices, game_log, game_session
def make_choice(choice, game_session, with_media=False): #Calls the nested make choice function in the game session class
if not choice:
description, choices, game_log = game_session.get_current_state_info()
return description, choices, "Please select a choice before proceeding.", game_session
choice_index = int(choice.split('.')[0]) - 1
result = game_session.make_choice(choice_index)
if with_media:
media = game_session.get_current_state_media()
return result[0], gr.update(choices=result[1]), result[2], game_session, media
else:
return result[0], gr.update(choices=result[1]), result[2], game_session
def load_game(custom_config=None, with_media=False):
global all_states
if not custom_config:
return gr.update(value="No custom configuration provided."), None, None, None, None, None, None
try:
new_config = json.loads(custom_config)
all_states = new_config
# Determine the starting location and state
starting_location = next(iter(all_states.keys()))
starting_state = next(iter(all_states[starting_location].keys()))
print(f"Starting location: {starting_location}, Starting state: {starting_state}")
game_session = GameSession(starting_location, starting_state)
description, choices, game_log = game_session.get_current_state_info()
new_path_errors = validate_transitions(all_states)
output_media = []
if with_media:
media_list = all_states[starting_location][starting_state].get('media', [])
print(f"Media list: {media_list}")
if media_list:
for media_path in media_list:
#media_component = create_media_component(media_path)
output_media.append(media_path)
print(f"Created {len(output_media)} media components")
success_message = f"Custom configuration loaded successfully!\n{new_path_errors}"
return (
gr.update(value=success_message),
game_log,
description,
gr.update(choices=choices),
gr.update(value=custom_config),
game_session,
output_media if with_media else None
)
except json.JSONDecodeError as e:
error_message = format_json_error(custom_config, e)
return gr.update(value=error_message), None, None, None, None, gr.update(value=custom_config), None
except Exception as e:
error_message = f"Error loading custom configuration: {str(e)}"
return gr.update(value=error_message), None, None, None, None, gr.update(value=custom_config), None
def format_json_error(config, error):
lineno, colno = error.lineno, error.colno
lines = config.split('\n')
error_line = lines[lineno - 1] if lineno <= len(lines) else ""
pointer = ' ' * (colno - 1) + '^'
return f"""Invalid JSON format in custom configuration:
Error at line {lineno}, column {colno}:
{error_line}
{pointer}
Error details: {str(error)}"""
def display_website(link):
html = f"<iframe src='{link}' width='100%' height='1000px'></iframe>"
gr.Info("If 404 then the space/page has probably been disabled - normally due to a better alternative")
return html
initgameinfo = start_game()
#-----------------------------------------------------------------------------------------------------------------------------------
# Set the directory where files will be saved
SAVE_DIR = os.path.abspath("saved_media")
# Ensure the save directory exists
os.makedirs(SAVE_DIR, exist_ok=True)
# Define supported file extensions
SUPPORTED_EXTENSIONS = {
"image": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"],
"audio": [".mp3", ".wav", ".ogg"],
"video": [".mp4", ".avi", ".mov", ".webm"]
}
def save_file(file):
if file is None:
return "No file uploaded.", gr.update()
try:
# Get the original filename and extension
original_filename = os.path.basename(file.name)
_, extension = os.path.splitext(original_filename)
# Check if the file extension is supported
if not any(extension.lower() in exts for exts in SUPPORTED_EXTENSIONS.values()):
return f"Unsupported file type: {extension}", gr.update()
# Create a unique filename to avoid overwriting
base_name = os.path.splitext(original_filename)[0]
counter = 1
new_filename = f"{base_name}{extension}"
while os.path.exists(os.path.join(SAVE_DIR, new_filename)):
new_filename = f"{base_name}_{counter}{extension}"
counter += 1
# Copy the file from the temporary location to our save directory
dest_path = os.path.join(SAVE_DIR, new_filename)
shutil.copy2(file.name, dest_path)
# Return success message and updated FileExplorer
return f"File saved as {SAVE_DIR}/{new_filename}", gr.update(value=SAVE_DIR), gr.update(value=None)
except Exception as e:
return f"Error saving file: {str(e)}", gr.update(value=SAVE_DIR), gr.update()
def view_file(file_path):
if not file_path:
return None, None, None, "No file selected."
try:
full_path = os.path.join(SAVE_DIR, file_path)
_, extension = os.path.splitext(full_path)
extension = extension.lower()
if extension in SUPPORTED_EXTENSIONS["image"]:
return Image.open(full_path), None, None, None
elif extension in SUPPORTED_EXTENSIONS["audio"]:
return None, full_path, None, None
elif extension in SUPPORTED_EXTENSIONS["video"]:
return None, None, full_path, None
else:
return None, None, None, f"Unsupported file type: {extension}"
except Exception as e:
return None, None, None, f"Error viewing file: {str(e)}"
def refresh_file_explorer():
return gr.update()
#-----------------------------------------------------------------------------------------------------------------------------------
LinPEWFprevious_messages = []
def LinPEWFformat_prompt(current_prompt, prev_messages):
formatted_prompt = textwrap.dedent("""
Previous prompts and responses:
{history}
Current prompt:
{current}
Please respond to the current prompt, taking into account the context from previous prompts and responses.
""").strip()
history = "\n\n".join(f"Prompt {i+1}: {msg}" for i, msg in enumerate(prev_messages))
return formatted_prompt.format(history=history, current=current_prompt)
#-----------------------------------------------------------------------------------------------------------------------------------
def TestGradioClientQwen270b(text):
# client = Client("Qwen/Qwen2-72B-Instruct")
# result = client.predict(
# query=text, #"Hello!!",
# history=[],
# system="You are a helpful assistant.",
# api_name="/model_chat"
# )
client = Client("CohereForAI/c4ai-command-r-v01")
result = client.predict(
user_message="Hello!!",
api_name="/generate_response"
)
print(result)
#print(result[1][0]) #All messages in the conversation
#print(result[2]) # System prompt
return result #result[1][0][1] # If supporting conversations this needs to return the last message instead
#-----------------------------------------------------------------------------------------------------------------------------------
with gr.Blocks() as demo:
with gr.Accordion("Config and Asset Assistance - Click to open", open=False):
gr.HTML("Jonas Tyroller - This problem changes your perspective on game dev - minimise the cost of exploration so you can explore more (17:00) | dont make the same game again but worse (:) <br>https://youtu.be/o5K0uqhxgsE")
with gr.Accordion("Leaveraging LLMs"):
with gr.Tab("ZeroGPU - Placeholder for now"):
gr.HTML("Copy paste any old config to llm and ask to remix is the easiest <br>To bake 'Moral of the story' in you have to be very deliberate")
gr.HTML("UI can be media and all items can have media")
with gr.Tab("Any Request to Qwen2-0.5B"):
gr.HTML("Placeholder for https://huggingface.co/h2oai/h2o-danube3-500m-chat-GGUF and https://huggingface.co/OuteAI/Lite-Mistral-150M-v2-Instruct as alternative")
gr.HTML("https://huggingface.co/spaces/HuggingFaceTB/SmolLM-135M-Instruct-WebGPU 125 mdeol to be tested as alternative (and all up to 1.5b - how to delte a model in your code?) - Need to go over the dataset to see how to prompt it - https://huggingface.co/datasets/HuggingFaceTB/smollm-corpus ")
gr.HTML("Placeholder for qwen 2 72b as alternative use checkbox and gradio client api call")
gr.Markdown("# Qwen-0.5B-Instruct Language Model")
gr.Markdown("This demo uses the Qwen-0.5B-Instruct model to generate responses based on your input.")
gr.HTML("Example prompts: <br>I am writing a story about a chef. please write dishes to appear on the menu. <br>What are the most common decisions that a chef story would include? <br>What are the kinds problems that a chef story would include? <br>What are the kinds of out of reach goals that a chef story would include? <br>Continue this config - Paste any complete block of the config")
with gr.Row():
with gr.Column():
llmguide_prompt = gr.Textbox(lines=2, placeholder="Enter your prompt here...")
llmguide_stream_checkbox = gr.Checkbox(label="Enable streaming")
llmguide_submit_button = gr.Button("Generate")
with gr.Column():
llmguide_output = gr.Textbox(lines=10, label="Generated Response")
llmguide_tokens_per_second = gr.Textbox(label="Tokens per Second")
# llmguide_submit_button.click(
# llmguide_generate_response,
# inputs=[llmguide_prompt, llmguide_stream_checkbox],
# outputs=[llmguide_output, llmguide_tokens_per_second],
# )
with gr.Tab("General RAG (Pathfinder?) Attempt"):
gr.HTML("https://huggingface.co/spaces/mteb/leaderboard - Source for SOTA - current using all-MiniLM-L6-v2")
gr.HTML("Placeholder for weak RAG Type Charcter interaction test aka input for JSON 'Knowledge Base' Input")
# gr.Interface(
# fn=process_query,
# inputs=[
# gr.Textbox(lines=2, placeholder="Enter your question here..."),
# gr.Checkbox(label="Use RAG"),
# gr.Checkbox(label="Stream output")
# ],
# outputs=[
# gr.Textbox(label="Generated Response"),
# gr.Textbox(label="Tokens per second"),
# gr.Textbox(label="RAM Usage"),
# gr.Textbox(label="Referenced Documents")
# ],
# title="RAG/Non-RAG Q&A System",
# description="Ask a question with or without using RAG. The response is generated using a GPU-accelerated model. RAM usage and referenced document IDs (for RAG) are logged."
# )
with gr.Tab("General FAQ Attempt"):
with gr.Tab("Front end as FAQ"):
FAQMainOutput = gr.TextArea(placeholder='Output will show here', value='')
FAQCustomButtonInput = gr.TextArea(lines=1, placeholder='Prompt goes here')
for category_name, category_prompts in FAQAllprompts.items():
with gr.Accordion(f"General {category_name} Pattern based", open=False):
with gr.Group():
for index, (prompt, _) in enumerate(category_prompts):
button = gr.Button(prompt)
# button.click(llmguide_generate_response, inputs=[FAQCustomButtonInput, gr.State(index), gr.State(category_name)], outputs=FAQMainOutput)
with gr.Tab("Function Call as FAQ"):
gr.HTML("Placeholder for media task query routing as dual purpose in workflow and for user queries as psuedo RAG engine")
gr.HTML("https://llama.meta.com/docs/model-cards-and-prompt-formats/llama3_1/#built-in-tooling - The three built-in tools (brave_search, wolfram_alpha, and code interpreter) can be turned on using the system prompt")
with gr.Tab("ZeroGPU refactor"):
model_name = gr.State(modelname)
gr.Markdown(f"# Language Model with RAG and Model Switching")
gr.Markdown("This demo allows you to switch between different Qwen models and use Retrieval-Augmented Generation (RAG).")
gr.Markdown("**Note:** Model switching is intended for testing output quality. Due to GPU limitations, speed differences may not be apparent. Models requiring over 50GB to load will likely not work.")
gr.Markdown("Need to add support for switching models and loading GGUF and GPTQ and BNB")
gr.Markdown("57b MOE takes 6min to load and gets workload evicted - storage limit over 100G")
with gr.Row():
with gr.Column():
model_dropdown = gr.Dropdown(choices=modelnames, value=modelname, label="Select Model")
current_model_info = gr.Markdown(f"Current model: {modelname}")
current_model_info2 = gr.Interface(lambda x: f"Current model: {lastmodelnameinloadfunction[0]} ({lastmodelnameinloadfunction[1]}) (tokeniser = {lastmodelnameinloadfunction[2]})", inputs=None, outputs=["markdown"], description="Check what was last loaded (As the space has memory and I havent figured how spaces work enough eg. how does multiple users affect this)") # gr.Markdown(f"Current model: {lastmodelnameinloadfunction}")
gr.HTML("Need to figure out my test function calling for groq-8b as it doesnt seem to answer chat properly - will need a seperate space - eg. letter counting, plural couting, using a function as form for llm to fill (like choosing which model and input parameters for media in game)?")
prompt = gr.Textbox(lines=2, placeholder="Enter your prompt here...")
stream_checkbox = gr.Checkbox(label="Enable streaming")
rag_checkbox = gr.Checkbox(label="Enable RAG")
submit_button = gr.Button("Generate")
with gr.Column():
with gr.Tab("Current Response"):
output = gr.Textbox(lines=10, label="Generated Response")
tokens_per_second = gr.Textbox(label="Tokens per Second")
ram_usage = gr.Textbox(label="RAM Usage")
doc_references = gr.Textbox(label="Document References")
with gr.Tab("All Responses So far"):
gr.Markdown("As we want a iterative process all old responses are saved for now - will figure how to make per user solution - need some kind of hook onto the loading a space to assign random usercount with timestamp")
gr.Interface(format_output_dict, inputs=None, outputs=["textbox"])
model_dropdown.change(
model_change_handler,
inputs=[model_dropdown],
outputs=[model_name, current_model_info, output]
)
submit_button.click(
generate_response,
inputs=[prompt, rag_checkbox, stream_checkbox],
outputs=[output, tokens_per_second, ram_usage, doc_references],
)
with gr.Tab("Hugging Chat"):
gr.HTML("https://huggingface.co/chat<br>Huggingface chat supports - State Management (Threads), Image Generation and editing, Websearch, Document parsing (PDF?), Assistants and larger models than zero gpu can support in July 2024 (Unquantised 30B and above)")
gr.HTML("Existing Assistants to use and planning custom assistants placeholder")
with gr.Tab("Embedded Spaces and gradio client"):
gr.HTML("In Asset Generation Tab under Text")
with gr.Tab("Gradio Client"):
gr.Interface(fn=TestGradioClientQwen270b, inputs="text", outputs="markdown", description="Single response test of gradio client - Cohere for test as api not working on Qwen/Qwen2-72B-Instruct, Use for testing like using a space and duplicate for heavy testing")
with gr.Tab("Preview APIs"):
gr.HTML("July 2024 - Gemini, Cohere and Groq rate limit free APIs")
gr.Markdown("# Current Workflow = Mermaid Diagram to (1) Story to (2) Initial JSON (through LLM and fix JSON by hand) to JSON Corrections (through LLM and fix JSON by hand) to (4) Media prompts to (5) Asset Generation to (6) JSON Media field population")
with gr.Tab("Workflow Piplines"):
gr.HTML("<br>Workflow is currently based on using ZeroGPU space and resources - will add platform specific (chat changes prompts and native image generation changes order) flows much later <br>Prompt Testing has to be add each parameter level of models as smaller models can get it right with different wording")
with gr.Tab("Mermaid Diagram to (1) Story"):
gr.HTML("Below 70B seem to struggle here")
gr.Code(WFStage1prompt , label="Prompt Used")
with gr.Row():
gr.Textbox(TimeRelatedMermaidStoryAttempttoRefinefrom[0], lines=30)
gr.Textbox(TimeRelatedMermaidStoryAttempttoRefinefrom[1], lines=30)
gr.Textbox(TimeRelatedMermaidStoryAttempttoRefinefrom[2], lines=30)
gr.Textbox(TimeRelatedMermaidStoryAttempttoRefinefrom[3], lines=30)
gr.Textbox(TimeRelatedMermaidStoryAttempttoRefinefrom[4], lines=30)
with gr.Tab("Story to (2) JSON (through LLM and fix JSON by hand)"):
gr.HTML("This Step specifically has to be function call only if you explain the tool can take as many blocks as neccesary")
gr.Code(WFStage2prompt , label="Prompt Used")
with gr.Tab("Initial JSON (through LLM and fix JSON by hand) to (3) JSON Corrections (through LLM and fix JSON by hand)"):
gr.Code("Lets a critique this JSON to find areas fix", label="prompt used")
with gr.Tab("JSON Corrections (through LLM and fix JSON by hand) to (4) Media prompts"):
gr.HTML("This Step specifically has to be function call only")
gr.HTML("Gemma-9b and Mistral 8x7b is better at this prompt than llama 3.1 8b and 70b <br>Can add (each media field must get an entry) and (in python list of list format for plug and play) but they affect final output")
gr.Code("Lets a make a list for the prompts we will use to make media objects in this JSON. Make one for a person to interpret and one for direct media generators that focus on keywords: ", label="prompt used")
with gr.Tab("Media prompts to (5) Asset Generation"):
gr.HTML("This Step specifically has to be function call only")
gr.Code("For each Media item described classify it by media type and comment if in a story setting it would need timing ", label="prompt used")
gr.HTML("This Step can be merged with the next if we can make a editor like in the semi-Auto space in test and edit tailored to just accepting the JSON and exposing only media part for editing")
with gr.Tab("Asset Generation to (6) JSON Media field population"):
gr.Code("Here is a list of file names - assume they are in the order of the empty media sections of the JSON and rewrite the JSON", label="prompt used")
with gr.Tab("All Variations / Themes for entire workflow proccess - to be completed"):
gr.HTML("Trying to abstract the process into one worflow is beyond me so multiple paths to goal (config) is the aim now")
with gr.Tab("Branching - Decisions / Timeline Creation to Story to Config Conversation"):
gr.HTML("Structures for interesting timeline progression")
gr.HTML("Claude Artifacts to illustrate nested structure brainstorms - <br> https://claude.site/artifacts/4a910d81-1541-49f4-8531-4f27fe56cd1e <br> https://claude.site/artifacts/265e9242-2093-46e1-9011-ed6ad938be90?fullscreen=false <br> ")
gr.HTML("Placeholder - Considerations - Story from the perspective of Main character or NPC in the LLM genereated story")
mermaideditoriframebtn = gr.Button("Load Mermaid Editor")
mermaideditoriframe = gr.HTML("")
mermaideditoriframebtn.click(fn=lambda x: "<iframe src='https://mermaid.live/' width='100%' height='1000px'></iframe>", outputs=mermaideditoriframe)
with gr.Accordion("Mermaid Structures - click to open", open=False):
for key, item in mermaidstorystructures.items():
with gr.Accordion(key, open=False):
gr.Code(item, label=key)
with gr.Tab("Linear - Player List to Empty Config with Edit support (Narrative based)"):
with gr.Accordion("Can copy in the Test Example State Machine tab - only linear path for now", open=False):
gr.Markdown("# Story and Timeline Generator")
gr.Markdown("Click the button to generate a random timeline and story based on UI elements and story events. <br>Ask an LLM to use this to write a story around")
with gr.Row():
game_structure_output_text_with_media = gr.Code(language="json")
#game_structure_output_text = gr.Code(language="json")
with gr.Accordion("JSON with no edits"):
gr.HTML("A long game is a bunch of short games")
with gr.Row():
timeline_output_with_assets = gr.Textbox(label="Timeline with Assets Considered (gaps = side quests)", lines=25)
#timeline_output = gr.Textbox(label="Timeline (Order might be different for now)", lines=20)
with gr.Column():
timeline_output_text = gr.Textbox(label="Random Suggestions", lines=10)
timeline_selected_lists_text = gr.Textbox(label="Selected Idea Lists for Inspiration", lines=2)
story_output = gr.Textbox(label="Generated Story (Order might be different for now)", lines=20)
with gr.Row():
generate_no_story_timeline_points = gr.Slider(minimum=1, value=10, step=1, maximum=30, label="Choose the amount of story timeline points")
generate_no_ui_timeline_points = gr.Slider(minimum=1, value=10, step=1, maximum=30, label="Choose the amount of ui timeline points")
#generate_no_media_timeline_points = gr.Slider(minimum=1, value=5, step=1, maximum=30, label="Choose the amount of media timeline points")
#generate_with_media_check = gr.Checkbox(label="Generate with media", value=True)
with gr.Row():
timeline_num_lists_slider = gr.Slider(minimum=1, maximum=len(all_idea_lists), step=1, label="Number of Lists to Consider", value=3)
timeline_items_per_list_slider = gr.Slider(minimum=1, maximum=10, step=1, label="Items per List", value=3)
timeline_include_existing_games = gr.Checkbox(label="Include Existing Game Inspirations", value=True)
timeline_include_multiplayer = gr.Checkbox(label="Include Multiplayer Features", value=True)
# timeline_generate_button = gr.Button("Generate Random Suggestions").click(
# timeline_get_random_suggestions,
# inputs=[timeline_num_lists_slider, timeline_items_per_list_slider, timeline_include_existing_games, timeline_include_multiplayer],
# outputs=[timeline_output_text, timeline_selected_lists_text]
# )
generate_button = gr.Button("Generate Story and Timeline (Click to get UI that will assist with JSON formatting)")
@gr.render(inputs=game_structure_output_text_with_media)
def update(game_structure_output_text_with_media):
return show_elements_json_input(game_structure_output_text_with_media)
generate_button.click(generate_story_and_timeline, inputs=[generate_no_story_timeline_points, generate_no_ui_timeline_points, timeline_num_lists_slider, timeline_items_per_list_slider, timeline_include_existing_games, timeline_include_multiplayer], outputs=[timeline_output_with_assets, story_output, game_structure_output_text_with_media, timeline_output_text, timeline_selected_lists_text]) #, generate_no_media_timeline_points, generate_with_media_check], outputs=[timeline_output_with_assets, timeline_output, story_output, game_structure_output_text_with_media, game_structure_output_text])
with gr.Tab("Linear - Existing Media eg. Songs and Screenshots"):
gr.HTML("Media position in the story part beginning, during or end")
with gr.Tab("Linear - Machine Leaning Architectures as game maps"):
gr.HTML("Transformers, SSMs, Image and Video Generation Architectures, GANs, RNNS, etc.")
with gr.Tab("Linear - Prompt Engineering as basis for ideation process"):
gr.HTML("Current Assited workflow idea - Story timeline events suggestions (LLM / Premade List) | Merging events with premade mermaid structures (LLM + Story Text + Mermaid Text) | Edit mermaid till satisfied (LLM + Story Text) | Ask LLM to convert to config (LLM + JSON Text) | Edit config (LLM / User with format assistance or not) | Playtest and go back to mermaaid or config if there are problems")
gr.HTML("Interactive movie (UI interaction or no progress) vs Branching Paths (Maze)")
gr.HTML("Things that can change the workflow - Asset First (Make Asset and make the transitions using LLM), Export First (Custom JS config, Playcanvas, Unreal Engine reverse engineered to this spaces config?) Game Mechanics First (eg. Player Stats, Inventory and NPCS not implemented yet, so traversal type games best aka graph like structures)")
gr.HTML("Config writing = Remix old one, Ask LLM to make one, Endless combination testing using the prompt engineering above or writing by hand (prompt engineering on yourself)")
gr.HTML("Can use song lyrics as thematic source")
gr.HTML("Placeholder for each below prompt getting a Textbox")
# for item in Storycraftprompts:
# input = gr.State(item)
# output = gr.Textbox("", label=item)
# outputbtn = gr.Button(item).click(fn=llmguide_generate_response, inputs=input, outputs=output)
# for i, item in enumerate(Storycraftprompts, 1):
# input = gr.State(item)
# previous_input = gr.State(lambda: LinPEWFprevious_messages)
# output = gr.Textbox("", label=f"Output {i}")
# def LinPEWF_update_and_generate(prompt, prev_msgs):
# prev_msgs.append(prompt)
# formatted_prompt = LinPEWFformat_prompt(prompt, prev_msgs)
# response = llmguide_generate_response(formatted_prompt)
# full_response = ""
# for chunk in response:
# full_response += chunk
# prev_msgs.append(f"Response: {full_response}")
# return full_response
# outputbtn = gr.Button(f"Generate {i}").click(
# fn=LinPEWF_update_and_generate,
# inputs=[input, previous_input],
# outputs=output
# )
# LinPEWFprevious_messages.append(item)
#with gr.Accordion("Decisions / Timeline Creation to Story to Config Conversation", open=False):
with gr.Tab("Branching - Network analysis to Game config"):
gr.HTML("Placeholder for analysing multiple stories for their network structures and creating general rules for a strucutre generator based of named entity recognition and bias to locations or people - The extreme long way")
with gr.Tab("Linear - Chess PNG to Game config"):
gr.HTML("Any Chess match can serve as end of game final battle")
with gr.Tab("Main problem to solve - Concept combination / integration and non-linear progression planning"):
gr.HTML("The story and the gameplay dont have to occur at the same time - eg. ")
gr.Markdown("## Prompts / Mermaid diagrams to be made from the ideas for workflow")
with gr.Tab("Using Time as a proxy for all conepts?"):
gr.HTML("A timeline is the most important part of the story - once that is set you can do anything?")
with gr.Tab("Concept Bashing? Ideas"):
with gr.Row():
gr.Textbox(TimeRelatedConceptsForIdeaGeneration, lines=30)
gr.Textbox(Nonlinearprogressionideas, lines=30)
gr.Textbox(Adjectivebasedcombinationideatextsv2, lines=30)
gr.Textbox(Adjectivebasedcombinationideatexts, lines=30)
gr.HTML("Media Critiques (eg. Youtube Rants) as Prompts to whole games as interactive explanation")
with gr.Tab("Mermaid Diagrams"):
with gr.Accordion("Mermaid Structures - click to open", open=False):
for key, item in examplemermaidconceptblendingstrutures.items():
gr.Code(item, label=key)
with gr.Tab("Existing Config Crafting Progression"):
with gr.Accordion("Test for config to gradio components order - ignore for now", open=False ):
gr.HTML("Placeholder for changing the render below to the one above for new config but with the ability to upload files aka the media field should be file uploader / dropdowns for all files that have been uploaded")
gr.Markdown("Asset Generation")
gr.HTML("Splits by new line - The idea here was to allow for saving the file ")
input_text = gr.Textbox(label="Input Text", lines=10)
output_group = gr.Group()
@gr.render(inputs=input_text)
def update(text):
return show_elements(text)
with gr.Tab("Quick Ways to evaluate current config"):
gr.HTML("Ask SOTA LLMs This prompt: <br> This config is for a basic text based game engine. I dont have any structural metrics to assess the quality of the config. What JSON things can we look at to see if it may be too bland for a person testing the game? <br> Then Paste the Config with the prompt")
gr.HTML("""Original Claude 3.5 Sonnet Response snippets: <br>
Limited state variety: With only 13 states across 5 locations, the game might feel short and lacking in diversity. Consider adding more locations or states within existing locations.
Low average choices: An average of 1.92 choices per state might make the game feel linear. Increasing the number of choices in more states could improve player engagement.
Limited consequences: Only 3 states have consequences, which might make player choices feel less impactful. Adding more consequences could increase the sense of agency.
Short descriptions: The average description length of 13.15 words might not provide enough detail to immerse players. Consider expanding descriptions to create a richer narrative.
Lack of media: No states currently use media elements, which could make the game feel less engaging. Adding images, sound effects, or other media could enhance the player experience.
Limited narrative branching: While there are some loops and choices, the overall structure is relatively linear. Adding more branching paths could increase replayability and player interest.
To make the game less bland, consider:
Adding more states and locations
Increasing the number of choices in each state
Implementing more consequences for player actions
Expanding descriptions to create a richer narrative
Incorporating media elements
Creating more diverse paths through the game""")
# import originalconfigatbeinningofthisspace, claude3_5_06072024configtips, tipsupdatedconfigatbeinningofthisspace from relatively_constant_variables
with gr.Tab("Improvement of the default config"):
gr.HTML("Example of how to advance a game config with LLM - end goal is to have automatic worflow that takes these considerations into account <br> Things missing from the game engine - Economics and Basic Politics (NPC affiliation)")
gr.HTML("Suggestions from claude 3.5 on how to change config")
display_originalconfigatbeinningofthisspace = originalconfigatbeinningofthisspace.replace(' ', '&nbsp;').replace('\n', '<br>')
display_claude3_5_06072024configtips = claude3_5_06072024configtips.replace(' ', '&nbsp;').replace('\n', '<br>')
display_tipsupdatedconfigatbeinningofthisspace = tipsupdatedconfigatbeinningofthisspace.replace(' ', '&nbsp;').replace('\n', '<br>')
gr.HTML("""<div style="display: flex; justify-content: space-between; height: 900px; overflow: auto; ">
<div style="flex: 1; margin: 0 10px; padding: 20px;">
""" + display_originalconfigatbeinningofthisspace + """
</div>
<div style="flex: 1; margin: 0 10px; padding: 20px; width: 50%">
""" + display_claude3_5_06072024configtips + """
</div>
<div style="flex: 1; margin: 0 10px; padding: 20px;">
""" + display_tipsupdatedconfigatbeinningofthisspace + """
</div>
</div>""")
with gr.Tab("Themes and Topics"):
gr.HTML("https://en.wikipedia.org/wiki/History#Periods https://en.wikipedia.org/wiki/Philosophy https://en.wikipedia.org/wiki/Moral_injury")
with gr.Tab("Old Ideas to merge"):
gr.HTML("Random Scenario / Song to 'full game' manual or auto is end goal ")
gr.HTML("Componets (outside Code Support for Config): Decisions (and context explanation), Nested Sections, Media (Especially to affect decisions), Replayability (GTA and Tekken type mechanics in text form), Theme integration (Modified Varibles that affect UI or config order)")
gr.HTML("Existing Games eg. GTA Heists - Same Map with overlapping branching narratives, Battlefront - Elites amongst Commoners, Tekken Casino (one mistake = 1/2 or 1/3 of your Resources) and Turn based: 'Tactics' type nintendo games, Chess (and any other tile based game) ")
gr.HTML("Existing Game Rules for text - Cyberpunk RED, ")
gr.HTML("Community playthrough = Tally of players choices, Random item placed in a random location - first person to get it wins, Survival by location or characters met")
gr.HTML("Some Kinds of game skeletons ideas - Timelines, Graph as State machine paths, Economy ecosystem")
gr.HTML("One prompt to be used to test models - <br>Please make 10 python lists for the types of media files and their purposes in a game and then use those lists to random generate a timeline of 20 items when the function is called <br>Great next suggest ways to improve this function to create better timelines")
with gr.Tab("Main areas of considerations"):
gr.HTML("")
with gr.Tab("Structural Inspirations"):
gr.HTML("GTA Heists - Replayability and stakes, Tekken - 2/3 mistakes = lost round ")
gr.HTML("Sports Scores, ")
with gr.Tab("Themes"):
gr.HTML("")
with gr.Tab("Current Engine Defects"):
gr.HTML("All realtime events - Text still needs realtime as well")
with gr.Tab("Inventory and Skill Support"):
gr.HTML("Each decision affects Skills or inventory")
with gr.Tab("NPC Support"):
gr.HTML("Shared timeline that the player interfere with")
with gr.Tab("Economics Support"):
gr.HTML("Style Idea for a Basic Idea - Endless Economy (Tiny Tower as well) - Paperclip maximiser and inspirations - https://huggingface.co/spaces/osanseviero/TheMLGame")
with gr.Row():
with gr.Column(scale=1):
gr.HTML("""Main End Goal is Rapid prototypes for education and training purposes eg. Degree of the future is game score <br><div style="width: 100%; text-align: center">A way to prototype basic non-3D parts of a game while trying to understand where models can streamline workflow</div>""")
with gr.Accordion("Temporary Asset Management Assist - click to open", open=False):
gr.HTML("Make Files and Text ideas for the field and paste <br>When Space is restarted it will clear - zip export and import will be added later")
with gr.Accordion("Upload Files for config"):
gr.Markdown("# Media Saver and Explorer (refresh file list to be resolved - for now upload all files and reload the space - they persist as long as the space creator doesnt reset/update the space - will add manual clear options later)")
with gr.Tab("Upload Files"):
file_input = gr.File(label="Choose File to Upload")
save_output = gr.Textbox(label="Upload Status")
with gr.Tab("File Explorer"):
file_explorer = gr.FileExplorer(
root_dir=SAVE_DIR,
glob="*.*",
file_count="single",
height=300,
label="Select a file to view"
)
with gr.Row():
refresh_button = gr.Button("Refresh", scale=1)
view_button = gr.Button("View File")
image_output = gr.Image(label="Image Output", type="pil")
audio_output = gr.Audio(label="Audio Output")
video_output = gr.Video(label="Video Output")
error_output = gr.Textbox(label="Error")
file_input.upload(
save_file,
inputs=file_input,
outputs=[save_output, file_explorer, file_input]
)
view_button.click(
view_file,
inputs=file_explorer,
outputs=[image_output, audio_output, video_output, error_output]
)
refresh_button.click(
refresh_file_explorer,
outputs=file_explorer
)
with gr.Tab("Batch add files to config"):
gr.HTML("Placeholder for Config parser to allow dropdowns for the media parts of the config inserted to make assigning media quick")
gr.HTML("Placeholder for Config parser to allow for current zerospace creation and placement into the config (LLM can give list of media but still have to figure out workflow from there)")
gr.HTML("Placeholder for clearing uploaded assets (public space and temporary persistence = sharing and space problems)")
with gr.Accordion("My Previous Quick Config Attempts", open=False):
for experimetal_config_name, experimetal_config in ExampleGameConfigs.items():
with gr.Tab(experimetal_config_name):
gr.Code(json.dumps(experimetal_config, default=lambda o: o.__dict__, indent=2), label=experimetal_config_name) #str(experimetal_config)
with gr.Column(scale=5):
with gr.Tab("Test and Edit Config"):
with gr.Tab("Semi-Auto - Edit config while playing game"):
gr.HTML("-- Incomplete -- Current problem is passing values from rendered items to the config box <br>Need a way have dropdowns for the filelist and transitions eg. changing transitions must auto update choices <br>Config to components has hardcoded variables based on the auto gen so changes break it")
with gr.Column(scale=1):
gr.Markdown("# Debugging")
with gr.Row():
with gr.Column():
ewpwaerror_box = gr.Textbox(label="Path Errors", lines=4, value=path_errors)
with gr.Accordion("Generate a new config"):
with gr.Accordion("Lists for config - only linear path for now", open=False):
gr.Markdown("# Story and Timeline Generator")
gr.Markdown("Click the button to generate a random timeline and story based on UI elements and story events. <br>Ask an LLM to use this to write a story around")
#with gr.Row():
#ewpgame_structure_output_text_with_media = gr.Code(language="json")
#ewpgame_structure_output_text = gr.Code(language="json")
with gr.Row():
ewptimeline_output_with_assets = gr.Textbox(label="Timeline with Assets Considered", lines=20)
#ewptimeline_output = gr.Textbox(label="Timeline (Order might be different for now)", lines=20)
with gr.Column():
ewptimeline_output_text = gr.Textbox(label="Random Suggestions", lines=10)
ewptimeline_selected_lists_text = gr.Textbox(label="Selected Idea Lists for Inspiration", lines=2)
ewpstory_output = gr.Textbox(label="Generated Story (Order might be different for now)", lines=20)
with gr.Row():
ewpgenerate_no_story_timeline_points = gr.Slider(minimum=1, value=10, step=1, maximum=30, label="Choose the amount of story timeline points")
ewpgenerate_no_ui_timeline_points = gr.Slider(minimum=1, value=10, step=1, maximum=30, label="Choose the amount of ui timeline points")
#ewpgenerate_no_media_timeline_points = gr.Slider(minimum=1, value=5, step=1, maximum=30, label="Choose the amount of media timeline points")
#ewpgenerate_with_media_check = gr.Checkbox(label="Generate with media", value=True)
with gr.Row():
ewptimeline_num_lists_slider = gr.Slider(minimum=1, maximum=len(all_idea_lists), step=1, label="Number of Lists to Consider", value=3)
ewptimeline_items_per_list_slider = gr.Slider(minimum=1, maximum=10, step=1, label="Items per List", value=3)
ewptimeline_include_existing_games = gr.Checkbox(label="Include Existing Game Inspirations", value=True)
ewptimeline_include_multiplayer = gr.Checkbox(label="Include Multiplayer Features", value=True)
ewpgenerate_button = gr.Button("Generate Story and Timeline")
ewpwacustom_config = gr.Textbox(label="Custom Configuration (JSON)", lines=4) #value=json.dumps(all_states, default=lambda o: o.__dict__, indent=2), lines=4) #Commented out due to initial load issues
ewpwacustom_configbtn = gr.Button("Load Custom Config")
with gr.Row():
with gr.Column(scale=1):
with gr.Group():
gr.Markdown("# Text-based Adventure Game")
ewpwadescription = gr.Textbox(label="Current Situation", lines=4, value=initgameinfo[0])
ewpwamediabool = gr.State(value=True)
ewpwamedia = gr.State(["testmedia/Stable Audio - Raindrops, output.wav"])
@gr.render(inputs=ewpwamedia)
def dynamic_with_media(media_items):
print(media_items)
with gr.Group() as ewpwamediagrouping:
gr.HTML("Placeholder to load all media tests - still need to test clearing media on ")
if media_items == []:
gr.Markdown("No media items to display.")
else:
for item in media_items:
render = create_media_component(item)
return ewpwamediagrouping
ewpwachoices = gr.Radio(label="Your Choices", choices=initgameinfo[1])
ewpwasubmit_btn = gr.Button("Make Choice")
ewpwagame_log = gr.Textbox(label="Game Log", lines=20, value=initgameinfo[2])
ewpwagame_session = gr.State(value=initgameinfo[3])
ewpwasubmit_btn.click(
make_choice,
inputs=[ewpwachoices, ewpwagame_session, ewpwamediabool],
outputs=[ewpwadescription, ewpwachoices, ewpwagame_log, ewpwagame_session, ewpwamedia]
)
ewpwacustom_configbtn.click(
load_game,
inputs=[ewpwacustom_config, ewpwamediabool],
outputs=[ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia]
)
with gr.Column(scale=1):
@gr.render(inputs=ewpwacustom_config) #ewpgame_structure_output_text_with_media
def update(ewpwacustom_config):
return show_elements_json_input(ewpwacustom_config)
ewpgenerate_button.click(generate_story_and_timeline, inputs=[ewpgenerate_no_story_timeline_points, ewpgenerate_no_ui_timeline_points, ewptimeline_num_lists_slider, ewptimeline_items_per_list_slider, ewptimeline_include_existing_games, ewptimeline_include_multiplayer], outputs=[ewptimeline_output_with_assets, ewpstory_output, ewpwacustom_config, ewptimeline_output_text, ewptimeline_selected_lists_text]) #ewptimeline_output_with_assets, ewptimeline_output, ewpstory_output, ewpwacustom_config, ewpgame_structure_output_text]) #ewpgame_structure_output_text_with_media, ewpgame_structure_output_text])
with gr.Tab("Manual - Config With Assets"):
gr.HTML("Placeholder as not complete yet (3D not supported, and time (esp need for audio)")
with gr.Row():
with gr.Column(scale=2):
gr.Markdown("# Text-based Adventure Game")
wadescription = gr.Textbox(label="Current Situation", lines=4, value=initgameinfo[0])
wamediabool = gr.State(value=True)
wamedia = gr.State(["testmedia/Stable Audio - Raindrops, output.wav"])
@gr.render(inputs=wamedia)
def dynamic_with_media(media_items):
print(media_items)
with gr.Group() as wamediagrouping:
gr.HTML("Placeholder to load all media tests - still need to test clearing media on ")
if media_items == []:
gr.Markdown("No media items to display.")
else:
for item in media_items:
render = create_media_component(item)
return wamediagrouping
wachoices = gr.Radio(label="Your Choices", choices=initgameinfo[1])
wasubmit_btn = gr.Button("Make Choice")
wagame_log = gr.Textbox(label="Game Log", lines=20, value=initgameinfo[2])
wagame_session = gr.State(value=initgameinfo[3])
wasubmit_btn.click(
make_choice,
inputs=[wachoices, wagame_session, wamediabool],
outputs=[wadescription, wachoices, wagame_log, wagame_session, wamedia]
)
with gr.Column(scale=1):
gr.Markdown("# Debugging")
waerror_box = gr.Textbox(label="Path Errors", lines=4, value=path_errors)
with gr.Accordion("Config (Game Spoiler and Example for llm to remix)", open=False):
wacustom_config = gr.Textbox(label="Custom Configuration (JSON)", value=json.dumps(all_states, default=lambda o: o.__dict__, indent=2), lines=8)
wacustom_configbtn = gr.Button("Load Custom Config")
wacustom_configbtn.click(
load_game,
inputs=[wacustom_config, wamediabool],
outputs=[waerror_box, wagame_log, wadescription, wachoices, wacustom_config, wagame_session, wamedia]
)
with gr.Tab("HF - Asset Generation Considerations"):
with gr.Accordion("Some Idea / Inspiration Sources / Demos", open=False):
with gr.Row():
gr.HTML("Licenses for the spaces still to be evaluated - June 2024 <br> Users to follow with cool spaces - <br>https://huggingface.co/osanseviero - https://huggingface.co/spaces/osanseviero/TheMLGame <br>https://huggingface.co/jbilcke-hf <br>https://huggingface.co/dylanebert <br>https://huggingface.co/fffiloni <br>https://huggingface.co/artificialguybr <br>https://huggingface.co/radames <br>https://huggingface.co/multimodalart, ")
gr.HTML("Some Youtube Channels to keep up with updates <br><br>https://www.youtube.com/@lev-selector <br>https://www.youtube.com/@fahdmirza/videos")
gr.HTML("Social media that shows possiblities <br><br>https://www.reddit.com/r/aivideo/ https://www.reddit.com/r/StableDiffusion/ https://www.reddit.com/r/midjourney/ https://x.com/blizaine https://www.reddit.com/r/singularity/comments/1ead7vp/not_sure_if_this_is_the_right_place_to_post_but_i/ https://www.reddit.com/r/singularity/comments/1ebpra6/the_big_reveal_book_trailer_made_with_runway_gen3/ https://www.reddit.com/r/LocalLLaMA/comments/1e3aboz/folks_with_one_24gb_gpu_you_can_use_an_llm_sdxl/")
gr.HTML("Currently - need to create then save to pc then reupload to use here in test tab")
gr.HTML("Whole game engine in a space? - https://huggingface.co/spaces/thomwolf/test_godot_editor <br><br> https://huggingface.co/godot-demo https://huggingface.co/spaces/thomwolf/test_godot")
with gr.Tab("Text-based"):
gr.HTML("Some Benchmark Leaderboards - https://huggingface.co/spaces/allenai/ZebraLogic | https://huggingface.co/spaces/allenai/WildBench https://scale.com/leaderboard https://livebench.ai")
with gr.Accordion("LLM HF Spaces/Sites (Click Here to Open) - Ask for a story and suggestions based on the autoconfig", open=False):
with gr.Row():
linktochat = gr.Dropdown(choices=["--Function Calling--", "https://groq-demo-groq-tool-use.hf.space",
"--Multiple Models--", "https://lmsys-gpt-4o-mini-battles.hf.space", "https://labs.perplexity.ai/", "https://chat.lmsys.org", "https://sdk.vercel.ai/docs", "https://cyzgab-catch-me-if-you-can.hf.space",
"--70B and above--", "https://llamameta-llama3-1-405b.static.hf.space", "https://qwen-qwen-max-0428.hf.space", "https://cohereforai-c4ai-command-r-plus.hf.space", "https://qwen-qwen1-5-110b-chat-demo.hf.space", "https://snowflake-snowflake-arctic-st-demo.hf.space", "https://databricks-dbrx-instruct.hf.space", "https://qwen-qwen1-5-72b-chat.hf.space",
"--20B and above--", "https://gokaygokay-gemma-2-llamacpp.hf.space", "https://01-ai-yi-34b-chat.hf.space", "https://cohereforai-c4ai-command-r-v01.hf.space", "https://ehristoforu-mixtral-46-7b-chat.hf.space", "https://mosaicml-mpt-30b-chat.hf.space",
"--7B and above--", "https://vilarin-mistral-nemo.hf.space", "https://arcee-ai-arcee-scribe.hf.space", "https://vilarin-llama-3-1-8b-instruct.hf.space", "https://ysharma-chat-with-meta-llama3-8b.hf.space", "https://qwen-qwen1-5-moe-a2-7b-chat-demo.hf.space", "https://deepseek-ai-deepseek-coder-7b-instruct.hf.space", "https://osanseviero-mistral-super-fast.hf.space", "https://artificialguybr-qwen-14b-chat-demo.hf.space", "https://huggingface-projects-llama-2-7b-chat.hf.space",
"--1B and above--", "https://huggingface.co/spaces/eswardivi/Phi-3-mini-128k-instruct", "https://eswardivi-phi-3-mini-4k-instruct.hf.space", "https://stabilityai-stablelm-2-1-6b-zephyr.hf.space",
"--under 1B--", "unorganised", "https://ysharma-zephyr-playground.hf.space", "https://huggingfaceh4-zephyr-chat.hf.space", "https://ysharma-explore-llamav2-with-tgi.hf.space", "https://huggingfaceh4-falcon-chat.hf.space", "https://uwnlp-guanaco-playground-tgi.hf.space", "https://stabilityai-stablelm-tuned-alpha-chat.hf.space", "https://mosaicml-mpt-7b-storywriter.hf.space", "https://huggingfaceh4-starchat-playground.hf.space", "https://bigcode-bigcode-playground.hf.space", "https://mosaicml-mpt-7b-chat.hf.space", "https://huggingchat-chat-ui.hf.space", "https://togethercomputer-openchatkit.hf.space"], label="Choose/Cancel type any .hf.space link here (can also type a link)'", allow_custom_value=True)
chatspacebtn = gr.Button("Use the chosen URL to load interface with a chat model. For sdk.vercel click the chat button on the top left. For lymsys / chat arena copy the link and use a new tab")
chatspace = gr.HTML("Chat Space Chosen will load here")
chatspacebtn.click(display_website, inputs=linktochat, outputs=chatspace)
with gr.Tab("NPCS"):
gr.HTML("For ideas on NPCS check: https://lifearchitect.ai/leta/, ")
with gr.Tab("Save files"):
gr.HTML("For Dynamic events overnight or when player is not active what can LLMS edit? <br><br>eg. Waiting for a letter from a random npc can be decided by the llm <br>eg. Improved Stats on certain days (eg. bitrthday) <br>Privacy <br>User Directed DLC eg. Rockstar Editor with local llm guide")
gr.HTML("Some ideas - In game websites eg. GTA esp stock markets, news; ")
gr.HTML("Placeholder for huggingface spaces that can assist - https://huggingface.co/nvidia/Nemotron-4-340B-Instruct (Purpose is supposed to be synthetic data generation), https://huggingface.co/spaces/gokaygokay/Gemma-2-llamacpp ")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist (9b and under) <br>initial floor for testing can be https://huggingface.co/spaces/Qwen/Qwen2-0.5B-Instruct, https://huggingface.co/spaces/Qwen/Qwen2-1.5b-instruct-demo, https://huggingface.co/spaces/stabilityai/stablelm-2-1_6b-zephyr, https://huggingface.co/spaces/IndexTeam/Index-1.9B, https://huggingface.co/microsoft/Phi-3-mini-4k-instruct")
with gr.Tab("Diagrams"):
gr.HTML("Claude 3.5 sonnet is very good with mermaid graphs - can used for maps, situational explanations")
with gr.Tab("Maths"):
gr.HTML("https://huggingface.co/spaces/AI-MO/math-olympiad-solver")
with gr.Tab("Media Understanding"):
gr.HTML("NPC Response Engines? Camera, Shopkeeper, Companion, Enemies, etc.")
with gr.Accordion("Media understanding model Spaces/Sites (Click Here to Open)", open=False):
with gr.Row():
linktomediaunderstandingspace = gr.Dropdown(choices=[ "--Weak Audio Understanding = Audio to text, Weak Video Understanding = Video to Image to Image Understanding", "https://skalskip-florence-2-video.hf.space", "https://kingnish-opengpt-4o.hf.space",
"--Video Understanding--", "https://ivgsz-flash-vstream-demo.hf.space",
"--Image Understanding--", "https://gokaygokay-florence-2.hf.space", "https://vilarin-vl-chatbox.hf.space", "https://qnguyen3-nanollava.hf.space", "https://skalskip-better-florence-2.hf.space", "https://merve-llava-interleave.hf.space",
"--Img-to-img Understanding--", "https://merve-draw-to-search-art.hf.space",
"--Image Understanding without conversation--", "https://epfl-vilab-4m.hf.space", "https://epfl-vilab-multimae.hf.space", "https://gokaygokay-sd3-long-captioner.hf.space" ],
label="Choose/Cancel type any .hf.space link here (can also type a link)'", allow_custom_value=True)
mediaunderstandingspacebtn = gr.Button("Use the chosen URL to load interface with a media understanding space")
mediaunderstandingspace = gr.HTML("Mdeia Understanding Space Chosen will load here")
mediaunderstandingspacebtn.click(display_website, inputs=linktomediaunderstandingspace, outputs=mediaunderstandingspace)
gr.HTML("Image Caption = https://huggingface.co/spaces/microsoft/Promptist (Prompt Lengthen) ")
with gr.Tab("Images"):
with gr.Accordion("Image Gen or Animation HF Spaces/Sites (Click Here to Open) - Have to download and upload at the the top", open=False):
# with gr.Tabs("General"):
with gr.Row():
linktoimagegen = gr.Dropdown(choices=["--Text-Interleaved--", "https://ethanchern-anole.hf.space",
"--Hidden Image--", "https://ap123-illusiondiffusion.hf.space",
"--Panorama--", "https://gokaygokay-360panoimage.hf.space",
"--General--", "https://pixart-alpha-pixart-sigma.hf.space", "https://stabilityai-stable-diffusion-3-medium.hf.space", "https://prodia-sdxl-stable-diffusion-xl.hf.space", "https://prodia-fast-stable-diffusion.hf.space", "https://bytedance-hyper-sdxl-1step-t2i.hf.space", "https://multimodalart-cosxl.hf.space", "https://cagliostrolab-animagine-xl-3-1.hf.space", "https://stabilityai-stable-diffusion.hf.space",
"--Speed--", "https://radames-real-time-text-to-image-sdxl-lightning.hf.space", "https://ap123-sdxl-lightning.hf.space",
"--LORA Support--", "https://artificialguybr-artificialguybr-demo-lora.hf.space", "https://artificialguybr-studio-ghibli-lora-sdxl.hf.space", "https://artificialguybr-pixel-art-generator.hf.space", "https://fffiloni-sdxl-control-loras.hf.space", "https://ehristoforu-dalle-3-xl-lora-v2.hf.space",
"--Image to Image--", "https://gokaygokay-kolorsplusplus.hf.space", "https://lllyasviel-ic-light.hf.space", "https://gparmar-img2img-turbo-sketch.hf.space",
"--Upscaler--", "https://gokaygokay-tile-upscaler.hf.space",
"--Control of Pose--", "https://instantx-instantid.hf.space", "https://modelscope-transferanything.hf.space", "https://okaris-omni-zero.hf.space"
"--Control of Shapes--", "https://linoyts-scribble-sdxl-flash.hf.space",
"--Control of Text--", ""
"--Foreign Language Input--", "https://gokaygokay-kolors.hf.space"], label="Choose/Cancel type any .hf.space link here (can also type a link)'", allow_custom_value=True)
imagegenspacebtn = gr.Button("Use the chosen URL to load interface with a image generation model")
imagegenspace = gr.HTML("Image Space Chosen will load here")
imagegenspacebtn.click(display_website, inputs=linktoimagegen, outputs=imagegenspace)
linkstobecollectednoembed = "https://artgan-diffusion-api.hf.space", "https://multimodalart-stable-cascade.hf.space", "https://google-sdxl.hf.space", "https://visionmaze-magic-me.hf.space", "https://segmind-segmind-stable-diffusion.hf.space", "https://simianluo-latent-consistency-model.hf.space",
gr.HTML("Concept Art, UI elements, Static/3D Characters, Environments and Objects")
gr.HTML("Images Generation General (3rd Party) = https://www.craiyon.com/")
gr.HTML("Images Generation Posters with text - https://huggingface.co/spaces/GlyphByT5/Glyph-SDXL-v2")
gr.HTML("SVG Generation = Coding models / SOTA LLM ")
gr.HTML("Images Generation - Upscaling - https://huggingface.co/spaces/gokaygokay/Tile-Upscaler")
gr.HTML("Vision Models for descriptions <br> https://huggingface.co/spaces/gokaygokay/Florence-2 <br>https://huggingface.co/spaces/vilarin/VL-Chatbox - glm 4v 9b <br>")
gr.HTML("Upscalers (save data transfer costs? highly detailed characters?) - https://huggingface.co/spaces/gokaygokay/AuraSR")
gr.HTML("Placeholder for huggingface spaces that can assist ")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist")
with gr.Tab("Video"):
with gr.Accordion("Video Spaces/Sites (Click Here to Open)", open=False):
with gr.Row():
linktovideogenspace = gr.Dropdown(choices=["--Genral--", "https://zheyangqin-vader.hf.space", "https://kadirnar-open-sora.hf.space",
"--Talking Portrait--", "https://fffiloni-tts-hallo-talking-portrait.hf.space",
"--Gif / ImgtoImg based video--", "https://wangfuyun-animatelcm-svd.hf.space", "https://bytedance-animatediff-lightning.hf.space", "https://wangfuyun-animatelcm.hf.space", "https://guoyww-animatediff.hf.space",],
label="Choose/Cancel type any .hf.space link here (can also type a link)'", allow_custom_value=True)
videogenspacebtn = gr.Button("Use the chosen URL to load interface with video generation")
videogenspace = gr.HTML("Video Space Chosen will load here")
videogenspacebtn.click(display_website, inputs=linktovideogenspace, outputs=videogenspace)
gr.HTML("Cutscenes, Tutorials, Trailers")
gr.HTML("Portrait Video eg. Solo Taking NPC - https://huggingface.co/spaces/fffiloni/tts-hallo-talking-portrait (Image + Audio and combination) https://huggingface.co/spaces/KwaiVGI/LivePortrait (Non verbal communication eg. in a library, when running from a pursuer)")
gr.HTML("Placeholder for huggingface spaces that can assist - https://huggingface.co/spaces/KingNish/Instant-Video, https://huggingface.co/spaces/multimodalart/stable-video-diffusion, https://huggingface.co/spaces/multimodalart/stable-video-diffusion")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist")
gr.HTML("3rd Party / Closed Source - https://runwayml.com/ <br>")
with gr.Tab("Animations (for lower resource use)"):
gr.HTML("Characters, Environments, Objects")
gr.HTML("Placeholder for huggingface spaces that can assist - image as 3d object in video https://huggingface.co/spaces/ashawkey/LGM")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist")
with gr.Tab("Audio"):
with gr.Accordion("Audio Spaces/Sites (Click Here to Open)", open=False):
with gr.Row():
linktoaudiogenspace = gr.Dropdown(choices=["General", "https://artificialguybr-stable-audio-open-zero.hf.space", "",
"--Talking Portrait--","https://fffiloni-tts-hallo-talking-portrait.hf.space"],
label="Choose/Cancel type any .hf.space link here (can also type a link)'", allow_custom_value=True)
audiogenspacebtn = gr.Button("Use the chosen URL to load interface with audio generation")
audiogenspace = gr.HTML("Audio Space Chosen will load here")
audiogenspacebtn.click(display_website, inputs=linktoaudiogenspace, outputs=audiogenspace)
gr.HTML("Music - Background, Interactive, Cutscene, Menu <br>Sound Effects - Environment, character, action (environmental triggered by user eg. gun), UI <br>Speech - Dialouge, narration, voiceover <br>The new render function means the Config can be made and iframe/api functions can be ordered as neccessary based on the part of the config that needs it to streamline workflows based on current state of config ")
gr.HTML("Placeholder for huggingface spaces that can assist")
gr.HTML("Audio Sound Effects - https://huggingface.co/spaces/artificialguybr/Stable-Audio-Open-Zero")
gr.HTML("Voices - Voice clone eg. actors part of your project - https://huggingface.co/spaces/tonyassi/voice-clone")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist")
gr.HTML("3rd Party / Closed Source - https://suno.com/ <br>https://www.udio.com/")
with gr.Tab("3D"):
with gr.Accordion("3D Model Spaces/Sites (Click Here to Open)", open=False):
with gr.Row():
linktoThreedModel = gr.Dropdown(choices=["--Image prompt--", "https://vast-ai-charactergen.hf.space"
"--Video prompt--", "https://facebook-vggsfm.hf.space",
"--Text prompt--", "https://wuvin-unique3d.hf.space", "https://stabilityai-triposr.hf.space", "https://hysts-shap-e.hf.space", "https://tencentarc-instantmesh.hf.space", "https://ashawkey-lgm.hf.space", "https://dylanebert-lgm-mini.hf.space", "https://dylanebert-splat-to-mesh.hf.space", "https://dylanebert-multi-view-diffusion.hf.space"], label="Choose/Cancel type any .hf.space link here (can also type a link)'", allow_custom_value=True)
ThreedModelspacebtn = gr.Button("Use the chosen URL to load interface with a 3D model")
ThreedModelspace = gr.HTML("3D Space Chosen will load here")
ThreedModelspacebtn.click(display_website, inputs=linktoThreedModel, outputs=ThreedModelspace)
gr.HTML("Characters, Environments, Objects")
gr.HTML("Placeholder for huggingface spaces that can assist - https://huggingface.co/spaces/dylanebert/3d-arena")
gr.HTML("Closed Source - https://www.meshy.ai/")
with gr.Tab("Fonts"):
gr.HTML("Style of whole game, or locations, or characters")
gr.HTML("Placeholder for huggingface spaces that can assist - there was a space that could make letter into pictures based on the prompt but I cant find it now")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist")
with gr.Tab("Shaders and related"):
with gr.Accordion("'Special Effects' Spaces/Sites (Click Here to Open)", open=False):
with gr.Row():
linktospecialeffectsgenspace = gr.Dropdown(choices=["--Distorted Image--", "https://epfl-vilab-4m.hf.space", "https://epfl-vilab-multimae.hf.space"],
label="Choose/Cancel type any .hf.space link here (can also type a link)'", allow_custom_value=True)
specialeffectsgenspacebtn = gr.Button("Use the chosen URL to load interface with special effects generation")
specialeffectsgenspace = gr.HTML("Special Effects Space Chosen will load here")
specialeffectsgenspacebtn.click(display_website, inputs=linktospecialeffectsgenspace, outputs=specialeffectsgenspace)
gr.HTML("Any output that is not understood by the common person can be used as special effects eg. depth map filters on images etc.")
gr.HTML("Post-processing Effects, material effects, Particle systems, visual feedback")
gr.HTML("Visual Effects - eg. explosion can turn all items white for a moment, losing conciousness blurs whole screen")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist")
with gr.Tab("3rd Party - Asset Generation"):
gr.HTML("Image - https://www.midjourney.com/showcase")
gr.HTML("Audio - https://www.udio.com/home")
gr.HTML("Video - https://klingai.com/")
with gr.Tab("Basic Game Engine Mechanics"):
gr.HTML("Placeholder for explanations of Player and Game Session")
with gr.Tab("LLM play testing"):
gr.HTML("LLM can read the contents in full and give critiques but they can also play the game if you make a api interface - gradio allows this in the form of gradio client but you can also reroute the user inputs to function calling")
with gr.Tab("Custom JS Config Creator"):
gr.HTML("-- Incomplete -- Companion Space for zerogpu / client api workflow planning for a way to send a zip to the Basic Game Engine at the bottom of https://huggingface.co/spaces/KwabsHug/TestSvelteStatic (Also to test how much can be done majority on cpu)")
with gr.Tab("Simple Config Creator"):
inventory_items = gr.State([])
skills_items = gr.State([])
objectives_items = gr.State([])
targets_items = gr.State([])
with gr.Tabs():
with gr.TabItem("Inventory"):
inventory_type = gr.Textbox(label="Type")
inventory_name = gr.Textbox(label="Name")
inventory_description = gr.Textbox(label="Description")
add_inventory = gr.Button("Add Inventory Item")
inventory_textbox = gr.JSON(label="Inventory Items", value=[])
with gr.TabItem("Skills"):
skills_branch = gr.Textbox(label="Branch")
skills_name = gr.Textbox(label="Name")
skills_learned = gr.Dropdown(choices=["True", "False"], label="Learned")
add_skill_button = gr.Button("Add Skill")
skills_textbox = gr.JSON(label="Skills", value=[])
with gr.TabItem("Objectives"):
objectives_id = gr.Textbox(label="ID")
objectives_name = gr.Textbox(label="Name")
objectives_complete = gr.Dropdown(choices=["True", "False"], label="Complete")
add_objective_button = gr.Button("Add Objective")
objectives_textbox = gr.JSON(label="Objectives", value=[])
with gr.TabItem("Targets"):
targets_name = gr.Textbox(label="Name")
targets_x = gr.Textbox(label="X Coordinate")
targets_y = gr.Textbox(label="Y Coordinate")
targets_collisionType = gr.Textbox(label="Collision Type")
targets_collisiontext = gr.Textbox(label="Collision Text")
add_target_button = gr.Button("Add Target")
targets_textbox = gr.JSON(label="Targets", value=[])
with gr.TabItem("Placeholders for Modal Target"):
gr.HTML("Placeholder")
with gr.TabItem("Placeholders for State Machine Modal Target"):
gr.HTML("Placeholder")
with gr.TabItem("Placeholders for Background"):
gr.HTML("Placeholder")
config_output = gr.JSON(label="Updated Configuration")
@gr.render(inputs=[inventory_items, skills_items, objectives_items, targets_items]) #, outputs=config_output)
def aggregate_config(inventory, skills, objectives, targets):
config = default_config.copy()
config['inventory'] = inventory
config['skills'] = skills
config['objectives'] = objectives
config['targets'] = targets
return config
add_inventory.click(add_inventory_item, inputs=[inventory_items, inventory_type, inventory_name, inventory_description], outputs=inventory_textbox)
add_inventory.click(aggregate_config, inputs=[inventory_items, skills_items, objectives_items, targets_items], outputs=config_output)
add_skill_button.click(add_skill, inputs=[skills_items, skills_branch, skills_name, skills_learned], outputs=skills_textbox)
add_skill_button.click(aggregate_config, inputs=[inventory_items, skills_items, objectives_items, targets_items], outputs=config_output)
add_objective_button.click(add_objective, inputs=[objectives_items, objectives_id, objectives_name, objectives_complete], outputs=objectives_textbox)
add_objective_button.click(aggregate_config, inputs=[inventory_items, skills_items, objectives_items, targets_items], outputs=config_output)
add_target_button.click(add_target, inputs=[targets_items, targets_name, targets_x, targets_y, targets_collisionType, targets_collisiontext], outputs=targets_textbox)
add_target_button.click(aggregate_config, inputs=[inventory_items, skills_items, objectives_items, targets_items], outputs=config_output)
with gr.Tab("Advanced Config Creator"):
gr.HTML("Config with More than text and images")
with gr.Tab("LLM/Robotics as custom controllers"):
gr.HTML("Controls changed the scope of the game eg. mouse vs keyboard vs console controller vs remote vs touch screen <br>LLM can be vision/surveilance based controler (eg. MGS/GTA camera gauged by an actual camera in real life) or it can be a companion (offline/off console game progrssion ideas)")
gr.HTML("https://github.com/Shaka-Labs/ACT $250 imitation learning/teleoperation - eg. a win loss result alert / NPC 'scout' telling you go or stay")
gr.HTML("https://huggingface.co/posts/thomwolf/809364796644704")
gr.HTML("Robotics - https://www.nvidia.com/en-us/autonomous-machines/embedded-systems/jetson-orin/ https://huggingface.co/lerobot https://github.com/tonyzhaozh/aloha https://github.com/Shaka-Labs/ACT https://github.com/OpenTeleVision/TeleVision https://www.stereolabs.com/ ")
with gr.Tab("Existing Game Developemnt Resources"):
gr.HTML("https://develop.games/#nav-tools-engine ")
with gr.Tab("Other Considerations"):
with gr.Tab("General"):
gr.HTML("https://huggingface.co/docs/hub/api - daily papers is an endpoint so you can turn paper abstract into games with the help of LLM")
gr.HTML("Experiment for https://huggingface.co/spaces/ysharma/open-interpreter/blob/main/app.py inplementation with gradio client api")
gr.HTML("https://huggingface.co/spaces/HuggingFaceTB/SmolLM-135M-Instruct-WebGPU")
gr.HTML("Useful Spaces and links: https://huggingface.co/spaces/artificialguybr/Stable-Audio-Open-Zero https://huggingface.co/spaces/stabilityai/TripoSR https://huggingface.co/spaces/wangfuyun/AnimateLCM-SVD https://huggingface.co/spaces/multimodalart/face-to-all https://huggingface.co/spaces/facebook/MusicGen https://huggingface.co/spaces/Doubiiu/tooncrafter")
gr.HTML("langchain docs as awareness for alot of the integration use cases and providers that are possible - https://python.langchain.com/v0.2/docs/integrations/tools/")
gr.HTML("https://huggingface.co/spaces/linoyts/scribble-sdxl-flash as map planner")
gr.HTML("---------------------------------------Gameplay Ideas-------------------------------")
gr.HTML("https://huggingface.co/spaces/Lin-Chen/ShareCaptioner-Video - game use example police questions a event with multiple eye witnesses needs to give as close to the caption description to win")
with gr.Tab("State management through huggingface?"):
gr.HTML("Huggingface as the login provider? - https://huggingface.co/spaces/Wauplin/gradio-user-history/tree/main https://huggingface.co/spaces/AP123/IllusionDiffusion https://huggingface.co/docs/hub/en/spaces-oauth https://huggingface.co/docs/hub/en/oauth, persistent storage - https://huggingface.co/docs/hub/en/spaces-storage")
with gr.Tab("Finetuning options"):
gr.HTML("https://docs.mistral.ai/guides/finetuning/")
gr.HTML("Unsloth and Colab? - https://github.com/unslothai/unsloth https://huggingface.co/unsloth <br>Mistral Nemo Base - https://huggingface.co/unsloth/Mistral-Nemo-Base-2407 - https://colab.research.google.com/drive/17d3U-CAIwzmbDRqbZ9NnpHxCkmXB6LZ0?usp=sharing <br>Llama 3 8B https://huggingface.co/unsloth/llama-3-8b-Instruct-bnb-4bit")
gr.HTML("Price - https://openpipe.ai/pricing")
with gr.Tab("Backend and/or Hosting?"):
gr.HTML("Deployemnt options - https://huggingface.co/SpacesExamples", "https://huggingface.co/templates")
gr.HTML("Prototyping and freemium <br>free api <br>HF Pro subscription")
gr.HTML("GPU (Data privacy) = No Rate limits? - https://replicate.com/pricing, https://lambdalabs.com/service/gpu-cloud https://huggingface.co/pricing#endpoints https://tensordock.com/cloud-gpus", "https://massedcompute.com/home/pricing/" )
gr.HTML("Speed - Groq, SambaNova, https://www.etched.com/announcing-etched ")
gr.HTML("Price - Coding - https://aider.chat/docs/leaderboards/ - https://www.deepseek.com/ 0.3 per million - is this per token or chinese character as that means converting code to chinese if possible can save api cost?")
gr.HTML("Llama 3.1 405B - https://ai.meta.com/blog/meta-llama-3-1/ https://replicate.com/meta/meta-llama-3.1-405b-instruct https://fireworks.ai/pricing https://www.ibm.com/products/watsonx-ai/foundation-models")
with gr.Tab("Some Interesting Git Repos"):
gr.HTML("https://github.com/NVIDIA/Megatron-LM https://github.com/OpenGVLab/EfficientQAT https://github.com/evintunador/minLlama3/blob/main/model.py https://github.com/evintunador/micro-GPT-sandbox")
with gr.Tab("Old Ideas"):
gr.HTML("""<div style="width: 100%; text-align: center">Main ideas for this space is (June 2024) (Custom component planning?):</div>
<div style="display: flex; justify-content: center; margin-bottom: 20px; align-items: center;">
<div style="width: 20%; text-align: center">We can generate almost any media data and more </div>
<div style="width: 20%; text-align: center">A program exist around data </div>
<div style="width: 20%; text-align: center">Time moves in a straight so all considerations are flattend by the nature of time </div>
<div style="width: 20%; text-align: center">llms good at short questions </div>
<div style="width: 20%; text-align: center">HF + Gradio allows for api use so this my prototype tool for tool use test</div>
</div>""")
with gr.Tab("Asset loading test"):
gr.HTML("SDXL (linoyts/scribble-sdxl-flash), SVD and Stable Audio used for the test assets (For commercial use need a licence) <br>testmedia/")
with gr.Row():
gr.Image(value="testmedia/Flash scribble SDXL - random squiggles as roads.webp")
gr.Video(value="testmedia/SVD - random squiggles as roads video 004484.mp4")
gr.Audio(value="testmedia/Stable Audio - Raindrops, output.wav")
gr.HTML(TestmedialoadinHTML) # imported from relatively_constant_variables
demo.queue().launch()