Skip to content

Instantly share code, notes, and snippets.

@vallesmarinerisapp
Created November 8, 2023 02:20
Show Gist options
  • Save vallesmarinerisapp/bc7a25e9ac20640fb12171c1d581e54d to your computer and use it in GitHub Desktop.
Save vallesmarinerisapp/bc7a25e9ac20640fb12171c1d581e54d to your computer and use it in GitHub Desktop.
cosmictrip.space prompt generator with GPT-4 for generating DALL-E 3 space images
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.base import JobLookupError
from app import write_log
from models import Prompt, Image
import random
from flask import Flask
import openai
import models
from datetime import datetime
import requests
import uuid
from extensions import db
import time
from PIL import Image as PILImage
# Space Themes as a Python List
space_themes = [
"Exoplanets", "Aliens", "Astronauts", "Spaceships", "Nebulae", "Galaxies", "Black holes",
"Supernovae", "Meteor showers", "Comets", "Moons", "Space stations", "Pulsars", "Quasars",
"Star clusters", "Wormholes", "Space colonies", "Satellite",
"Space telescopes", "Solar flares",
"Alien civilizations", "Dyson spheres", "Space battles",
"Martian landscapes", "Interstellar travel", "Star births",
"Alien fauna and flora", "Distant sunsets", "Gas giants", "Cosmic ice structures",
"Alien architecture", "Advanced propulsion systems", "Outer space exploration",
"Gamma-ray bursts", "White dwarfs", "Red giants",
"Starship fleets", "Intergalactic stations", "Space elevators",
"Alien artifacts",
"Solar systems", "Rings of planets",
"Space pioneers",
"Alien societies", "Distant galaxies colliding", "Space oases",
"Milky way vistas", "Galaxy clusters",
"Galactic cores", "Alien deserts",
"Cosmic paradises", "Alien monuments",
"Alien paradises", "Intergalactic events",
"Terraformed Mars cities",
"Ice geysers on Enceladus or other worlds",
"Interstellar generation ships",
"Crystalline alien lifeforms",
"Subterranean oceans on Europa",
"Venusian surface outposts",
"Orbital habitats around Jupiter",
"Mining operations on asteroids",
"Space-faring nomadic civilizations",
"Hyperspace travel gateways",
"Fusion-powered spacecraft",
"Artificial intelligence companions in space",
"Bioengineered space gardens",
"Zero-gravity sports",
"Interplanetary diplomacy summits",
"Time dilation effects near black holes",
"Magnetic field manipulation in space constructions",
"Ancient alien ruins on distant worlds",
"Silicon-based alien life forms",
"Gravitational lensing telescopes",
"Spacecrafts using solar sails",
"Alien megacities",
"Extrasolar space probes",
"Planetary defense systems against asteroids",
"Space mirages created by black hole light bending",
"Dark energy reactors",
"Retrofuturistic space colonies",
"Eclipses", "planetary alignments",
"Space archeologists at work",
"Astrobiology expeditions",
"Orbiting solar farms",
"Alien megastructure construction sites",
"Underground cities on the Moon",
"Cryovolcanoes on dwarf planets",
"Orbital shipyards",
"Spaceborne botanical gardens",
"Space junk cleanup operations",
"Asteroid belt outposts",
"Time travel departure points",
"Dark matter research facilities",
"Extraterrestrial wildlife reserves",
"Intergalactic smuggler's hideouts",
"Neutron star collision vistas",
"Interplanetary cargo convoys",
"Holographic space navigation charts",
"Shipwrecks on alien shores",
"Habitable zone surveys",
"Nanoscale space fabricators",
"Black hole mining operations",
"Cybernetic space stations",
"Reclaimed derelict spacecraft",
"Interstellar pilgrimages",
"Anti-gravity racing leagues",
"Quantum computing hubs in orbit",
"Teleportation gate networks",
"Space elevator terminals",
"Interstellar espionage",
"Symbiotic planets and their stars",
"Meteorite carved sculptures",
"Warp field experiments",
"Eco-domes on barren worlds",
"Planetary terraforming drones",
"Alien linguistics labs",
]
art_styles = [
"Photorealistic",
"3D render",
"Digital painting",
"Concept art",
"Photorealistic",
]
def create_app():
write_log("prompt generator create app")
app = Flask(__name__)
app.config['SECRET_KEY'] = ''
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SERVER_NAME'] = 'cosmictrip.space'
app.config['APPLICATION_ROOT'] = '/'
app.config['PREFERRED_URL_SCHEME'] = 'https'
db.init_app(app)
with app.app_context():
start_scheduler(app)
return app
# Function to generate DALL-E prompt with specific number of themes
def generate_prompt(num_themes=1):
# Randomly select themes from the list
chosen_style = random.choice(art_styles)
selected_themes = random.sample(space_themes, num_themes)
sentence_limit = "Please keep it to 1 medium-length sentence."
instructions = "The prompt should start with something like, 'Write a DALL-E image prompt..' and it should instruct DALL-E to make a well-thought-out specific-image-in-mind prompt. Do extra planning if necessary to start."
main_prompt = ""
if num_themes == 1:
main_prompt = "Write a concise and detailed DALL-E prompt to generate an image within the theme: {}. The style should be " + chosen_style + ". " + sentence_limit + ". " + instructions
# Insert the selected themes into the main prompt
return main_prompt.format(*selected_themes)
def generate_prompt_prompts(sapp):
with sapp.app_context():
theme_count = 1 # random.choice([1,2,3])
chosen_prompt = generate_prompt(theme_count)
write_log("generate_prompt_prompts " + chosen_prompt)
gpt_response = openai.ChatCompletion.create(
model="gpt-4-0314",
temperature=1.1,
messages=[
{"role": "system", "content": "You are a space and sci-fi nerd. You generate quality prompts for DALL-E to generate sci-fi space images. Keep your prompts descriptive but not too flowery. Make it relatively short but also full of description."},
{"role": "user", "content": chosen_prompt},
]
)
# Get the generated text from GPT's response
gpt_prompt = gpt_response.choices[0].message['content']
write_log("prompt generator " + gpt_prompt)
token_usage = gpt_response.usage
# write_log(token_usage)
new_prompt = models.Prompt(prompt=gpt_prompt, prompt_source=chosen_prompt)
write_log("added prompt")
db.session.add(new_prompt)
db.session.commit()
def start_scheduler(sapp):
scheduler = BackgroundScheduler()
try:
write_log("prompt generator trying to get job")
job = scheduler.get_job('generate_prompt_prompts')
print(job)
except JobLookupError:
write_log("prompt generator job not found, adding it")
scheduler.add_job(generate_prompt_prompts, 'interval', minutes=10, id='generate_prompt_prompts', args=[sapp])
if not scheduler.running:
write_log("prompt generator not running, starting it")
scheduler.start()
scheduler.print_jobs()
else:
write_log("prompt generator already running, not starting")
write_log("going to create app prompt generator")
sapp = create_app()
if __name__ == "__main__":
pass
# Keep the script running
while True:
time.sleep(10)
@vallesmarinerisapp
Copy link
Author

This is the prompt generator for cosmictrip.space. It makes prompts with GPT-4 to be fed to DALL-E 3 to make space images.

Example output prompt and image:

"Create an image showcasing a breathtaking and photorealistic scene set on a rugged dwarf planet, where icy blue cryovolcanoes majestically erupt and spew out plumes of frozen material. The transcendent landscape is surrounded by a rich and mesmerizing tapestry of glittering stars and vibrant, multicolored nebulae, painting the distant cosmos with a breathtaking palette of cosmic hues. This awe-inspiring celestial view perfectly encapsulates the beauty and wonder of the unknown universe, capturing the hearts and imaginations of space and sci-fi enthusiasts alike."

image_20231108_011158_04b7f61bde0b431e86754c4773e3283e (1)
via https://cosmictrip.space/?image=589

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment