User:Mirjam Dissel/haiku dream mixer

From XPUB & Lens-Based wiki

Haiku dream3.png



svg_template.py

this is the svg template that changes every time

def dump (f, text):
	f.write("""<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->

<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   width="2560"
   height="1440"
   id="svg2"
   version="1.1"
   inkscape:version="0.47 r22583"
   sodipodi:docname="New document 1">
  <sodipodi:namedview
     id="base"
     pagecolor="#FFFFF0"
     bordercolor="#666666"
     borderopacity="1.0"
     inkscape:pageopacity="0.0"
     inkscape:pageshadow="2"
     inkscape:zoom="0.25"
     inkscape:cx="1041.6471"
     inkscape:cy="680"
     inkscape:document-units="px"
     inkscape:current-layer="g2826"
     showgrid="false"
     inkscape:window-width="895"
     inkscape:window-height="709"
     inkscape:window-x="0"
     inkscape:window-y="24"
     inkscape:window-maximized="0" />
  <defs
     id="defs4">
    <inkscape:perspective
       id="perspective10"
       inkscape:persp3d-origin="372.04724 : 350.78739 : 1"
       inkscape:vp_z="744.09448 : 526.18109 : 1"
       inkscape:vp_y="0 : 1000 : 0"
       inkscape:vp_x="0 : 526.18109 : 1"
       sodipodi:type="inkscape:persp3d" />
  </defs>
  <metadata
     id="metadata7">
    <rdf:RDF>
      <cc:Work
         rdf:about="">
        <dc:format>image/svg+xml</dc:format>
        <dc:type
           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
        <dc:title></dc:title>
      </cc:Work>
    </rdf:RDF>
  </metadata>
  <g
     transform="translate(0,387.63782)"
     id="layer1"
     inkscape:groupmode="layer"
     inkscape:label="Layer 1" />
  <g
     id="g2826"
     inkscape:groupmode="layer"
     inkscape:label="lorem ipsum">
    <path
       style="fill:#FCFCD9;fill-opacity:0.90829695000000021"
       d="m -8,4 c 858.66667,0 1717.3333,0 2576,0 0,480 0,960 0,1440 -858.6667,0 -1717.33333,0 -2576,0 C -8,964 -8,484 -8,4 z"
       id="rect2988"
       inkscape:connector-curvature="0" />
    <flowRoot
       id="flowRoot2828"
       xml:space="preserve"
       transform="matrix(0.67110742,0,0,1,496.10214,444)"><flowRegion
         id="flowRegion2830"><rect
           id="rect2832"
           width="2327.5483"
           height="672"
           x="0"
           y="0" /></flowRegion><flowPara
         id="flowPara2852"
         style="font-size:158.68918586px;-inkscape-font-specification:Georgia Bold;font-family:Georgia;font-weight:bold;font-style:normal;font-stretch:normal;font-variant:normal;text-anchor:middle;text-align:center;writing-mode:lr;line-height:130%;fill:#440000">""")
	f.write(text)
	f.write("""</flowPara></flowRoot>  </g>
</svg>""")

dream.txt

From this file small snippets of new dreams will be composed

There was a Sims 3 like situation, there were thousands of cities and I was in one of them. I got assigned a house, but apparently it belonged to someone else already. I moved to another house but the man of the other house, a pastor, kept calling me because he wanted to be friends. I could live with him in the house, no problem. I was talking to him on the phone while I was lying on a kitschy roman sofa, the room had dark red walls, real Sims interior..
All of a sudden I was in my parents' bedroom, looking past the curtains I could see my parents and sister sitting just outside the window (apparently there was a big balcony put in place, it seemed odd that my parents were floating outside of the window). I was in a cook-off and in my pan (still in my parents' bedroom) was something white with pasta and I had to cook 3 things inside, first one I don't remember, second one was a chunk of cheese in bread crumbs, and the last one was a big piece of white meat in bread crumbs. When I tried to cook the last one it fell apart even before I put it in the pan, as if it was some sort of fish. It stuck to the outside of the pan and pieces were in the fire. I remember being scared of never being able to get out of that place for failing the test.

I applied for a school as 'with filmcrew', apparently this was an option. I remember dreaming everything twice: the first time as I performed everything (opening doors for myself and leaving them open for the crew before closing them) and the second time I saw everything how the camera recorded it. The school was very old fashioned: high solid wooden doors and marble floors. I was wearing a school uniform and behaving as if I was important and could get away with being a bitch.
I got a call from my grandma, asking if I could come over. I went to school and inside a square room she was babysitting kids. On one side there was a bouncy castle with a giant chair in it. The chair was half a sphere, brown carpet on the outside and purple longer carpet on the inside. There was another, smaller sphere inside and above it hovered the other half, it had bear ears. A woman asked my grandma to come with here, she would be back in half an hour, but then she said one and a half hours. I asked for some water before she left. In two corners there were water pipes that were leaking, they were spraying water over the old blonde woman sunbathing on the bouncy castle and the two black sisters in the canopy bed on the other side. I tried closing the taps without disturbing them, but all of a sudden the whole room (yes, they were sunbathing in the square room inside the school) overflowed with water. I felt like drowning and everything was dark and wet. There was bacteria that made the toys (mostly lego) come to life, but the toys were evil. My only solution was to put red dust on them and they slowly disintegrated and we were in my grandma's living room, but it still had her old stone table and carpet.

http://pzwart3.wdka.hro.nl/wiki/User:Mirjam_Dissel#Dream_Files

poetry_gen_markov2.py

this puts the dream into a database and defines how to build up a new dream snippet

import random, os, time

# one class to parse Haikus and build a Markov DB
class HaikuParser(object):
	def __init__(self, markov_db):
		self.db = markov_db

	def parse(self, filename):
		#import textfile
		f = open(filename)

		prev_word = None
		#make words of textblock
		for line in f:
			if len(line.strip()):
				for word in line.split():
					if prev_word:
						if prev_word in self.db:
							self.db[prev_word].append(word)
						else:
							self.db[prev_word] = [word]
						
					else:
						if "<BEGIN>" in self.db:
							self.db["<BEGIN>"].append(word)
						else:
							self.db["<BEGIN>"] = [word]
							
					prev_word = word
			else:
				prev_word = None
			
		f.close()

#loop through each word and put in dictionary: word as index and next word as value.
	#if word exists, append next word to existing index


class HaikuMaker(object):
	def __init__(self, markov_db):
		self.db = markov_db

	def make(self):
		out = ""
		num_words = random.randrange(9,12)
		# take a <BEGIN> word
		word = random.choice(self.db["<BEGIN>"])
		for i in range(num_words):
			out = out + word + " "
			if word in self.db:
				word = random.choice(self.db[word])
			else:
				#break
				key = random.choice(self.db.keys())
				word = random.choice(self.db[key])
				
		return out.strip()

#choose index in dictionary (starting point), take value and look for value in dictionary.
#do the same: take this new index and take the value and see if it exist in the dictionary.

#print print print
#(everything below here will not be imported when importing this file from somwhere else) so you don't need this code, it's copied and adapted in the next piece of code, but I left it here to demonstrate if __name__ etc

if __name__ == "__main__":
	

	#create dictionary
	d = {}
	
	hp = HaikuParser(d)
	hp.parse("dream.txt")
	

#	print(hm.make())

# output should be an image with with a font blabla
	for i in range(20):
		hm = HaikuMaker(d)
		thenewHaiku = hm.make()
		i += 1
		conv = "convert -background white  -fill black  -font Times-Roman -pointsize 50 -size 600x   caption:'%s' haiku%s.gif" % (thenewHaiku, i)
		os.system(conv)
		time.sleep(0.50)




haiku_dream_mixer.py

this is the one you execute, you have to have pygame installed. Generates the new dream in text and image (svg/png) and shows it on your screen.

import sys, pygame, os, time, svg_template, codecs
pygame.init()

#change to your resolution
width, height = (1680, 1050)

screen = pygame.display.set_mode((width, height), pygame.FULLSCREEN)
#x, y = screen.get_size()
clock = pygame.time.Clock()



from poetry_gen_markov2 import *

d = {}

hp = HaikuParser(d)
hp.parse("dream.txt")

i = 0

while True:
	for event in pygame.event.get():
		if event.type == pygame.QUIT or \
			(event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
			sys.exit()
#		if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
			# THE SPACE BAR HAS BEEN PRESSED!
			#os.system("gst-launch-0.10 v4l2src ! ffmpegcolorspace !  pngenc ! filesink location=haiku1.gif")
	hm = HaikuMaker(d)
	thenewHaiku = hm.make()
	i += 1

	haiku_dream = 'haiku_dream%s.png' % (i)
	
	
	out = codecs.open('haiku_dream.svg', 'w', 'utf-8')
	svg_template.dump(out, thenewHaiku)
	out.close()
	os.system(' inkscape %s --export-png=%s --export-width=%s --export-height=%s' % ('haiku_dream.svg', haiku_dream, width, height))

#	conv = "convert -background white  -fill black  -font Times-Roman -pointsize 50 -size 600x   caption:'%s' haiku.gif" % thenewHaiku.replace("'", r"\'")
#	os.system(conv)

	try:
		img = pygame.image.load(haiku_dream)
	except pygame.error:
		i += 1

	screen.fill((255, 255, 255))
	screen.blit(img, (0, 0))
	pygame.display.flip()
	clock.tick(0.1)
#	i += 1

results

Haiku dream1.png Haiku dream2.png Haiku dream4.png Haiku dream5.png



notes

Just want to take pygame out and generate an animated svg or even better: an animated gif.