computer – THE HYPERTEXT http://www.thehypertext.com Thu, 10 Dec 2015 06:10:15 +0000 en-US hourly 1 https://wordpress.org/?v=5.0.4 word.camera exhibition http://www.thehypertext.com/2015/11/24/word-camera-exhibition/ Tue, 24 Nov 2015 19:58:34 +0000 http://www.thehypertext.com/?p=772 This week, I've been exhibiting my ongoing project, word.camera, at IDFA DocLab in Amsterdam.

Read More...

]]>
IMG_1338

This week, I’ve been exhibiting my ongoing project, word.camera, at IDFA DocLab in Amsterdam. My installation consists of four cameras:

  1. The original word.camera physical prototype:9503_20150507_tlr_1000px
  2. The sound camera physical prototype:IMG_1264
  3. A new word.camera model that uses a context-free grammar to generate poems based on the images it captures:IMG_1321_copyIMG_1317_copy
  4. A talking, pan-tilt-zoom surveillance camera that looks for faces in the hallway and then describes them aloud. (See also: this Motherboard video)
    IMG_2324
    IMG_2322
    IMG_1365

 

During the exhibition, I was also invited to deliver two lectures. Here are my slides from the first lecture:

And here’s a video of the second one:

 

Visitors are able to reserve the portable cameras for half hour blocks by leaving their ID at the volunteer kiosk. I have really enjoyed watching people borrow and use my cameras.

IMG_1333 copy

 

]]>
Traveler’s Lamp, Part II http://www.thehypertext.com/2015/05/08/travelers-lamp-part-ii/ http://www.thehypertext.com/2015/05/08/travelers-lamp-part-ii/#comments Fri, 08 May 2015 22:51:42 +0000 http://www.thehypertext.com/?p=560 Last week, Joanna Wrzaszczyk and I completed the first version of our dynamic light sculpture, inspired by Italo Calvino's Invisible Cities and the Traveling Salesman Problem.

Read More...

]]>
Click Here for Part I



Last week, Joanna Wrzaszczyk and I completed the first version of our dynamic light sculpture, inspired by Italo Calvino’s Invisible Cities and the Traveling Salesman Problem. We have decided to call it the Traveler’s Lamp.

Here is the midterm presentation that Joanna and I delivered in March:

Screen Shot 2015-05-08 at 6.26.53 PM

We received a lot of feedback after that presentation, which resulted in a number of revisions to the lamp’s overall design. Here are some sketches I made during that process:

2111_20150508_doc_1800px

2112_20150508_doc_1800px

2113_20150508_doc_1800px

2114_20150508_doc_1800px

2115_20150508_doc_1800px

2116_20150508_doc_1800px

2120_20150508_doc_1800px

2121_20150508_doc_1800px

Since that presentation, Joanna and I successfully designed and printed ten city-nodes for the lamp. Here is the deck from our final presentation, which contains renderings of all the city-nodes:

Screen Shot 2015-05-08 at 6.27.46 PM

We built the structure from laser-cut acrylic, fishing line, and 38-gauge wire. The top and base plates of the acrylic scaffolding are laser etched with the first and last page, respectively, from Invisible Cities. We fabricated the wood base on ITP’s CNC router from 3/4″ plywood.

Here are some photos of the assembled lamp:

5865_20150507_lamp_2400px

5846_20150507_lamp_2400px

5870_20150507_lamp_2400px

5877_20150507_lamp_2400px

5885_20150507_lamp_2400px

5887_20150507_lamp_2400px

5899_20150507_lamp_2400px

5901_20150507_lamp_2400px

5902_20150507_lamp_2400px

5920_20150507_lamp_2400px

5929_20150507_lamp_2400px

5965_20150507_lamp_2400px

5961_20150507_lamp_2400px

5947_20150507_lamp_2400px

5941_20150507_lamp_2400px

5931_20150507_lamp_2400px

Here’s a sketch, by Joanna, of the x-y-z coordinate plot that we fed into the computer program:

2122_20150508_doc_1800px

And finally, here’s some of the Python code that’s running on the Raspberry Pi:

def tsp():
    startingPin = random.choice(pins)
    pins.remove(startingPin)
    GPIO.output(startingPin, True)
    sleep(0.5)
    distances = []
    for i in range(pins):
        for p in pins:
            dist = distance(locDict[startingPin], locDict[p])
            distances.append((dist, p))
            GPIO.output(p, True)
            sleep(0.5)
            GPIO.output(p, False)
        distances = sorted(distances, key=lambda x: x[0])
        nextPin = distances[0][1]
        GPIO.output(nextPin, True)
        sleep(0.5)
        pins.remove(nextPin)
        startingPin = nextPin

]]>
http://www.thehypertext.com/2015/05/08/travelers-lamp-part-ii/feed/ 1
word.camera, Part II http://www.thehypertext.com/2015/05/08/word-camera-part-ii/ Fri, 08 May 2015 21:50:25 +0000 http://www.thehypertext.com/?p=505 For my final projects in Conversation and Computation with Lauren McCarthy and This Is The Remix with Roopa Vasudevan, I iterated on my word.camera project.

Read More...

]]>
Click Here for Part I


11161692_10100527204674408_7877879408640753455_o


For my final projects in Conversation and Computation with Lauren McCarthy and This Is The Remix with Roopa Vasudevan, I iterated on my word.camera project. I added a few new features to the web application, including a private API that I used to enable the creation of a physical version of word.camera inside a Mamiya C33 TLR.

The current version of the code remains open source and available on GitHub, and the project continues to receive positive mentions in the press.

On April 19, I announced two new features for word.camera via the TinyLetter email newsletter I advertised on the site.

Hello,

Thank you for subscribing to this newsletter, wherein I will provide occasional updates regarding my project, word.camera.

I wanted to let you know about two new features I added to the site in the past week:

word.camera/albums You can now generate ebooks (DRM-free ePub format) from sets of lexographs.

word.camera/postcards You can support word.camera by sending a lexograph as a postcard, anywhere in the world for $5. I am currently a graduate student, and proceeds will help cover the cost of maintaining this web application as a free, open source project.

Also:

word.camera/a/XwP59n1zR A lexograph album containing some of the best results I’ve gotten so far with the camera on my phone.

1, 2, 3 A few random lexographs I did not make that were popular on social media.

Best,

Ross Goodwin
rossgoodwin.com
word.camera

Next, I set to work on the physical version. I decided to use a technique I developed on another project earlier in the semester to create word.camera epitaphs composed of highly relevant paragraphs from novels. To ensure fair use of copyrighted materials, I determined that all of this additional data would be processed locally on the physical camera.

I developed a collection of data from a combination of novels that are considered classics and those I personally enjoyed, and I included only paragraphs over 99 characters in length. In total, the collection contains 7,113,809 words from 48 books.

Below is an infographic showing all the books used in my corpus, and their relative included word counts (click on it for the full-size image).

A79449E2CDA5D178

To build the physical version of word.camera, I purchased the following materials:

  • Raspberry Pi 2 board
  • Raspberry Pi camera module
  • Two (2) 10,000 mAh batteries
  • Thermal receipt printer
  • 40 female-to-male jumper wires
  • Three (3) extra-small prototyping perf boards
  • LED button

After some tinkering, I was able to put together the arrangement pictured below, which could print raw word.camera output on the receipt printer.

IMG_0354

I thought for a long time about the type of case I wanted to put the camera in. My original idea was a photobooth, but I felt that a portable camera—along the lines of Matt Richardson’s Descriptive Camera—might take better advantage of the Raspberry Pi’s small footprint.

Rather than fabricating my own case, I determined that an antique film camera might provide a familiar exterior to draw in people not familiar with the project. (And I was creating it for a remix-themed class, after all.) So I purchased a lot of three broken TLR film cameras on eBay, and the Mamiya C33 was in the best condition of all of them, so I gutted it. (N.B. I’m an antique camera enthusiast—I own a working version of the C33’s predecessor, the C2—and, despite its broken condition, cutting open the bellows of the C33 felt sacrilegious.)

I laser cut some clear acrylic I had left over from the traveler’s lamp project to fill the lens holes and mount the LED button on the back of the camera. Here are some photos of the finished product:

9503_20150507_tlr_1000px

9502_20150507_tlr_1000px

9509_20150507_tlr_1000px

9496_20150507_tlr_1000px

9493_20150507_tlr_1000px

9513_20150507_tlr_1000px

And here is the code that’s running on the Raspberry Pi (the crux of the matching algorithm is on line 90):

import uuid
import picamera
import RPi.GPIO as GPIO
import requests
from time import sleep
import os
import json
from Adafruit_Thermal import *
from alchemykey import apikey
import time

# SHUTTER COUNT / startNo GLOBAL
startNo = 0

# Init Printer
printer = Adafruit_Thermal("/dev/ttyAMA0", 19200, timeout=5)
printer.setSize('S')
printer.justify('L')
printer.setLineHeight(36)

# Init Camera
camera = picamera.PiCamera()

# Init GPIO
GPIO.setmode(GPIO.BCM)

# Working Dir
cwd = '/home/pi/tlr'

# Init Button Pin
GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)

# Init LED Pin
GPIO.setup(20, GPIO.OUT)

# Init Flash Pin
GPIO.setup(16, GPIO.OUT)

# LED and Flash Off
GPIO.output(20, False)
GPIO.output(16, False)

# Load lit list
lit = json.load( open(cwd+'/lit.json', 'r') )


def blink(n):
    for _ in range(n):
        GPIO.output(20, True)
        sleep(0.2)
        GPIO.output(20, False)
        sleep(0.2)

def takePhoto():
    fn = str(int(time.time()))+'.jpg' # TODO: Change to timestamp hash
    fp = cwd+'/img/'+fn
    GPIO.output(16, True)
    camera.capture(fp)
    GPIO.output(16, False)
    return fp

def getText(imgPath):
    endPt = 'https://word.camera/img'
    payload = {'Script': 'Yes'}
    files = {'file': open(imgPath, 'rb')}
    response = requests.post(endPt, data=payload, files=files)
    return response.text

def alchemy(text):
    endpt = "http://access.alchemyapi.com/calls/text/TextGetRankedConcepts"
    payload = {"apikey": apikey,
               "text": text,
               "outputMode": "json",
               "showSourceText": 0,
               "knowledgeGraph": 1,
               "maxRetrieve": 500}
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    r = requests.post(endpt, data=payload, headers=headers)
    return r.json()

def findIntersection(testDict):
    returnText = ""
    returnTitle = ""
    returnAuthor = ""
    recordInter = set(testDict.keys())
    relRecord = 0.0
    for doc in lit:
        inter = set(doc['concepts'].keys()) & set(testDict.keys())
        if inter:
            relSum = sum([doc['concepts'][tag]+testDict[tag] for tag in inter])
            if relSum > relRecord: 
                relRecord = relSum
                recordInter = inter
                returnText = doc['text']
                returnTitle = doc['title']
                returnAuthor = doc['author']
    doc = {
        'text': returnText,
        'title': returnTitle,
        'author': returnAuthor,
        'inter': recordInter,
        'record': relRecord
    }
    return doc

def puncReplace(text):
    replaceDict = {
        '—': '---',
        '–': '--',
        '‘': "\'",
        '’': "\'",
        '“': '\"',
        '”': '\"',
        '´': "\'",
        'ë': 'e',
        'ñ': 'n'
    }

    for key in replaceDict:
        text = text.replace(key, replaceDict[key])

    return text


blink(5)
while 1:
    input_state = GPIO.input(21)
    if not input_state:
        GPIO.output(20, True)
        try:
            # Get Word.Camera Output
            print "GETTING TEXT FROM WORD.CAMERA..."
            wcText = getText(takePhoto())
            blink(3)
            GPIO.output(20, True)
            print "...GOT TEXT"

            # Print
            # print "PRINTING PRIMARY"
            # startNo += 1
            # printer.println("No. %i\n\n\n%s" % (startNo, wcText))

            # Get Alchemy Data
            print "GETTING ALCHEMY DATA..."
            data = alchemy(wcText)
            tagRelDict = {concept['text']:float(concept['relevance']) for concept in data['concepts']}
            blink(3)
            GPIO.output(20, True)
            print "...GOT DATA"

            # Make Match
            print "FINDING MATCH..."
            interDoc = findIntersection(tagRelDict)
            print interDoc
            interText = puncReplace(interDoc['text'].encode('ascii', 'xmlcharrefreplace'))
            interTitle = puncReplace(interDoc['title'].encode('ascii', 'xmlcharrefreplace'))
            interAuthor = puncReplace(interDoc['author'].encode('ascii', 'xmlcharrefreplace'))
            blink(3)
            GPIO.output(20, True)
            print "...FOUND"

            grafList = [p for p in wcText.split('\n') if p]

            # Choose primary paragraph
            primaryText = min(grafList, key=lambda x: x.count('#'))
            url = 'word.camera/i/' + grafList[-1].strip().replace('#', '')

            # Print
            print "PRINTING..."
            startNo += 1
            printStr = "No. %i\n\n\n%s\n\n%s\n\n\n\nEPITAPH\n\n%s\n\nFrom %s by %s" % (startNo, primaryText, url, interText, interTitle, interAuthor)
            printer.println(printStr)

        except:
            print "SOMETHING BROKE"
            blink(15)

        GPIO.output(20, False)

Thanks to a transistor pulsing circuit that keeps the printer’s battery awake, and some code that automatically tethers the Raspberry Pi to my iPhone, the Fiction Camera is fully portable. I’ve been walking around Brooklyn and Manhattan over the past week making lexographs—the device is definitely a conversation starter. As a street photographer, I’ve noticed that people seem to be more comfortable having their photograph taken with it than with a standard camera, possibly because the visual image (and whether they look alright in it) is far less important.

As a result of these wanderings, I’ve accrued quite a large number of lexograph receipts. Earlier iterations of the receipt design contained longer versions of the word.camera output. Eventually, I settled on a version that contains a number (indicating how many lexographs have been taken since the device was last turned on), one paragraph of word.camera output, a URL to the word.camera page containing the photo + complete output, and a single high-relevance paragraph from a novel.

2080_20150508_doc_1800px

2095_20150508_doc_1800px

2082_20150508_doc_1800px

2088_20150508_doc_1800px

2091_20150508_doc_1800px

2093_20150508_doc_1800px

2097_20150508_doc_1800px

2100_20150508_doc_1800px

2102_20150508_doc_1800px

2104_20150508_doc_1800px

2106_20150508_doc_1800px

2108_20150508_doc_1800px

2109_20150508_doc_1800px

I also demonstrated the camera at ConvoHack, our final presentation event for Conversation and Computation, which took place at Babycastles gallery, and passed out over 50 lexograph receipts that evening alone.

6A0A1475

6A0A1416

6A0A1380

6A0A1352

6A0A1348

Photographs by Karam Byun

Often, when photographing a person, the camera will output a passage from a novel featuring a character description that subjects seem to relate to. Many people have told me the results have qualities that remind them of horoscopes.

]]>
word.camera http://www.thehypertext.com/2015/04/11/word-camera/ http://www.thehypertext.com/2015/04/11/word-camera/#comments Sat, 11 Apr 2015 05:12:58 +0000 http://www.thehypertext.com/?p=481 Last week, I launched a web application and a concept for photographic text generation that I have been working on for a few months. The idea came to me while working on another project, a computer generated screenplay, and I will discuss the connection in this post.

Read More...

]]>
lexograph /ˈleksəʊɡɹɑːf/ (n.)
A text document generated from digital image data

 

Last week, I launched a web application and a concept for photographic text generation that I have been working on for a few months. The idea came to me while working on another project, a computer generated screenplay, and I will discuss the connection in this post.

word.camera is responsive — it works on desktop, tablet, and mobile devices running recent versions of iOS or Android. The code behind it is open source and available on GitHub, because lexography is for everyone.

 

Screen Shot 2015-04-11 at 12.31.56 AM

Screen Shot 2015-04-08 at 2.01.42 AM

Screen Shot 2015-04-08 at 2.02.24 AM

 

Users can share their lexographs using unique URLs. Of all this lexographs I’ve seen generated by users since the site launched (there are now almost 7,000), this one, shared on reddit’s /r/creativecoding, stuck with me the most: http://word.camera/i/7KZPPaqdP

I was surprised when the software noticed and commented on the singer in the painting behind me: http://word.camera/i/ypQvqJr6L

I was inspired to create this project while working on another project. This semester, I received a grant from the Future of Storytelling Initiative at NYU to produce a computer generated screenplay, and I had been thinking about how to generate text that’s more cohesive and realistically descriptive, meaning that it would transition between related topics in a logical fashion and describe a scene that could realistically exist (no “colorless green ideas sleeping furiously”) in order to making filming the screenplay possible . After playing with the Clarifai API, which uses convolutional neural networks to tag images, it occurred to me that including photographs in my input corpus, rather than relying on text alone, could provide those qualities. word.camera is my first attempt at producing that type of generative text.

At the moment, the results are not nearly as grammatical as I would like them to be, and I’m working on that. The algorithm extracts tags from images using Clarifai’s convolutional neural networks, then expands those tags into paragraphs using ConceptNet (a lexical relations database developed at MIT) and a flexible template system. The template system enables the code to build sentences that connect concepts together.

This project is about augmenting our creativity and presenting images in a different format, but it’s also about creative applications of artificial intelligence technology. I think that when we think about the type of artificial intelligence we’ll have in the future, based on what we’ve read in science fiction novels, we think of a robot that can describe and interact with its environment with natural language. I think that creating the type of AI we imagine in our wildest sci-fi fantasies is not only an engineering problem, but also a design problem that requires a creative approach.

I hope lexography eventually becomes accepted as a new form of photography. As a writer and a photographer, I love the idea that I could look at a scene and photograph it because it might generate an interesting poem or short story, rather than just an interesting image. And I’m not trying to suggest that word.camera is the final or the only possible implementation of that new art form. I made the code behind word.camera open source because I want others to help improve it and make their own versions — provided they also make their code available under the same terms, which is required under the GNU GPLv3 open source license I’m using. As the technology gets better, the results will get better, and lexography will make more sense to people as a worthy artistic pursuit.

I’m thrilled that the project has received worldwide attention from photography blogs and a few media outlets, and I hope users around the world continue enjoying word.camera as I keep working to improve it. Along with improving the language, I plan to expand the project by offering a mobile app and generated downloadable ebooks so that users can enjoy their lexographs offline.


 

Click Here for Part II

]]>
http://www.thehypertext.com/2015/04/11/word-camera/feed/ 2
Traveler’s Lamp http://www.thehypertext.com/2015/02/21/invisible-salesman/ http://www.thehypertext.com/2015/02/21/invisible-salesman/#comments Sat, 21 Feb 2015 20:40:39 +0000 http://www.thehypertext.com/?p=452 For my primary project in Sculpting Data into Everyday Objects with Esther Cheung and Scott Leinweber, Joanna Wrzaszczyk and I will be creating a lamp to visualize the traveling salesman problem between a set of cities that Italo Calvino described in Invisible Cities.

Read More...

]]>
For my primary project in Sculpting Data into Everyday Objects with Esther Cheung and Scott Leinweber, Joanna Wrzaszczyk and I will be creating a lamp to visualize the traveling salesman problem between a set of cities that Italo Calvino described in Invisible Cities.

This project began with a personal fascination I have with graph data. A graph is a mathematical diagram of connections between various vertices (a.k.a. nodes) and edges (a.k.a.). They can be directed (meaning the edges point in specific directions) or undirected, and generally look like this:

credit: mathinsight.org

credit: mathinsight.org

Graphs are widely applicable data structures, relevant to a broad range of fields. The traveling salesman problem (TSP), in its classical form, involves a set of cities along with data comprising the distance from each city to every other city. Given a salesman who starts in any given city, what is the optimal path for the salesman to take in order to visit every city once and return to the city from which s/he began?

The lamp Joanna and I are designing will be a three-dimensional set of vertices, each a 3D printed city designed according to the specifications of one of Calvino’s Invisible Cities. The cities/vertices will be connected with light pipe, connected to LEDs, that will visualize a computer algorithm (likely running on an Arduino or Raspberry Pi) solving the traveling salesman problem in real time between the cities.

We plan to print our cities on the Connex500 printer at NYU AMS as intricate white or black structures embedded inside clear plastic. The Connex500 can make prints like this:

credit: 3ders.org

credit: 3ders.org

We plan to make our cities inside spheres. I designed the first one based on the first city in the book, described here:

Leaving there and proceeding for three days toward

the east, you reach Diomira, a city with sixty silver

domes, bronze statues of all the gods, streets paved

with lead, a crystal theater, a golden cock that crows

each morning on a tower. All these beauties will already

be familiar to the visitor, who has seen them

also in other cities. But the special quality of this

city for the man who arrives there on a September

evening, when the days are growing shorter and the

multicolored lamps are lighted all at once at the

doors of the food stalls and from a terrace a woman’s

voice cries ooh!, is that he feels envy toward those

who now believe they have once before lived an evening

identical to this and who think they were

happy, that time.

 

I focused on the description of “sixty silver domes” and made this in Rhino:

Screen Shot 2015-02-20 at 11.47.38 PM Screen Shot 2015-02-20 at 11.46.17 PM Screen Shot 2015-02-20 at 11.45.50 PM Screen Shot 2015-02-20 at 11.45.39 PM Screen Shot 2015-02-20 at 11.45.01 PM

The model of a 4cm-diameter sphere contains two holes: one on the top for an LED or light pipe connection, and one going all the way through to hang the city inside a clear outer enclosure.

Before creating the city above, I created another object in Rhino, representative of what I hope we can achieve with the lamp as a whole:

Screen Shot 2015-02-11 at 11.33.04 PM Screen Shot 2015-02-11 at 11.32.58 PM Screen Shot 2015-02-11 at 11.32.51 PM

 


 

Click Here for Part II

]]>
http://www.thehypertext.com/2015/02/21/invisible-salesman/feed/ 1
Fiction Generator, Part IV http://www.thehypertext.com/2014/12/21/fiction-generator-part-iv/ Sun, 21 Dec 2014 03:04:53 +0000 http://www.thehypertext.com/?p=406 For my final project in Networked Media with Daniel Shiffman, I put the Fiction Generator online at fictiongenerator.com. I also exhibited this project at the ITP Winter Show.

Read More...

]]>
Prior Installments:
Part I
Part II
Part III

For my final project in Comm Lab: Networked Media with Daniel Shiffman, I put the Fiction Generator online at fictiongenerator.com. VICE/Motherboard ran an article about my website, and I exhibited the project at the ITP Winter Show.

composite

 

After reading William S. Burroughs’ essay about the cut-up technique, I decided to implement an algorithmic version of it into the generator. I also refactored my existing code and added a load screen, with this animation:

robotholdingbook

I am running a LinuxApacheFlask stack at the moment. Here’s a screen shot of the website in its current state:

screenshot

]]>
Fiction Generator, Part II http://www.thehypertext.com/2014/11/20/fiction-generator-part-ii/ http://www.thehypertext.com/2014/11/20/fiction-generator-part-ii/#comments Thu, 20 Nov 2014 03:39:13 +0000 http://www.thehypertext.com/?p=328 After scraping about 5000 articles from tvtropes.org to retrieve descriptions for characters and settings, Sam Lavigne suggested I scrape erowid.org to dig up some exposition material. I proceeded to scrape 18,324 drug trip reports from the site, and integrated that material into the generator.

Read More...

]]>
For background, see my previous post on this project.

After scraping about 5000 articles from tvtropes.org to retrieve descriptions for characters and settings, Sam Lavigne suggested I scrape erowid.org to dig up some exposition material. I proceeded to scrape 18,324 drug trip reports from the site, and integrated that material into the generator.

While this project remains unfinished—I’m considering adding more material from many other websites, which is why I’m calling it a “collective consciousness fiction generator”—it is now generating full-length “novels” (300+ pages, 8.5×11, 12pt font). I polled my fellow ITP students to insert themselves into novels, and they responded with over 50 suggestions for novel titles. The generated PDFs are available for viewing/download on Google Drive.

I decided to create covers for 3 of my favorite novels the software has generated. Click on the covers below to see those PDFs:

infinite_splendour parallel_synchronized_randomness tricks_of_the_trade

Here is the current state of the code that’s generating these novels:

latex_special_char_1 = ['&', '%', '$', '#', '_', '{', '}']
latex_special_char_2 = ['~', '^', '\\']

outputFile = open("output/"+outputFileName+".tex", 'w')

openingTexLines = ["\\documentclass[12pt]{book}",
				   "\\usepackage{ucs}",
				   "\\usepackage[utf8x]{inputenc}",
				   "\\usepackage{hyperref}",
				   "\\title{"+outputFileName+"}",
				   "\\author{collective consciousness fiction generator\\\\http://rossgoodwin.com/ficgen}",
				   "\\date{\\today}",
				   "\\begin{document}",
				   "\\maketitle"]

closingTexLine = "\\end{document}"

for line in openingTexLines:
	outputFile.write(line+"\n\r")
outputFile.write("\n\r\n\r")

intros = char_match()

for x, y in intros.iteritems():

	outputFile.write("\\chapter{"+x+"}\n\r")

	chapter_type = random.randint(0, 4)
	bonus_drug_trip = random.randint(0, 1)
	trip_count = random.randint(1,4)


	# BLOCK ONE

	if chapter_type in [0, 3]:

		for char in y[0]:
			if char == "`":
				outputFile.seek(-1, 1)
			elif char in latex_special_char_1:
				outputFile.write("\\"+char)
			elif char in latex_special_char_2:
				if char == '~':
					outputFile.write("")
				elif char == '^':
					outputFile.write("")
				elif char == '\\':
					outputFile.write("-")
				else:
					pass
			else:
				outputFile.write(char)

	elif chapter_type in [1, 4]:

		for char in y[2]:
			if char == "`":
				outputFile.seek(-1, 1)
			elif char in latex_special_char_1:
				outputFile.write("\\"+char)
			elif char in latex_special_char_2:
				if char == '~':
					outputFile.write("")
				elif char == '^':
					outputFile.write("")
				elif char == '\\':
					outputFile.write("-")
				else:
					pass
			else:
				outputFile.write(char)

	elif chapter_type == 2:

		for char in y[1][0]:
			if char == "`":
				outputFile.seek(-1, 1)
			else:
				outputFile.write(char)

	outputFile.write("\n\r\n\r\n\r")

	
	# BLOCK TWO

	if chapter_type == 0:

		for char in y[2]:
			if char == "`":
				outputFile.seek(-1, 1)
			elif char in latex_special_char_1:
				outputFile.write("\\"+char)
			elif char in latex_special_char_2:
				if char == '~':
					outputFile.write("")
				elif char == '^':
					outputFile.write("")
				elif char == '\\':
					outputFile.write("-")
				else:
					pass
			else:
				outputFile.write(char)

	elif chapter_type == 1:

		for char in y[0]:
			if char == "`":
				outputFile.seek(-1, 1)
			elif char in latex_special_char_1:
				outputFile.write("\\"+char)
			elif char in latex_special_char_2:
				if char == '~':
					outputFile.write("")
				elif char == '^':
					outputFile.write("")
				elif char == '\\':
					outputFile.write("-")
				else:
					pass
			else:
				outputFile.write(char)

	elif chapter_type in [3, 4]:

		for char in y[1][0]:
			if char == "`":
				outputFile.seek(-1, 1)
			else:
				outputFile.write(char)

	elif chapter_type == 2 and bonus_drug_trip:

		for tripIndex in range(trip_count):

			for char in y[1][tripIndex+1]:
				if char == "`":
					outputFile.seek(-1, 1)
				else:
					outputFile.write(char)

	else:
		pass

	outputFile.write("\n\r\n\r\n\r")


	# BLOCK THREE

	if chapter_type in [0, 1, 3, 4] and bonus_drug_trip:

		for tripIndex in range(trip_count):

			for char in y[1][tripIndex+1]:
				if char == "`":
					outputFile.seek(-1, 1)
				else:
					outputFile.write(char)

		outputFile.write("\n\r\n\r\n\r")

	else:
		pass


outputFile.write("\n\r\n\r")
outputFile.write(closingTexLine)


outputFile.close()


print '\"output/'+outputFileName+'.tex\"'

 

UPDATE: Part III

]]>
http://www.thehypertext.com/2014/11/20/fiction-generator-part-ii/feed/ 1
More Poetizer Output http://www.thehypertext.com/2014/09/02/more-poetizer-output/ Tue, 02 Sep 2014 01:02:57 +0000 http://www.thehypertext.com/?p=51 I thought I'd share a few more computer poems with you. But first, a new video.

Read More & Watch the Video...

]]>
I thought I’d share a few more computer poems with you. But first, a new video:

For more information, see my previous blog entry.

Now, here are some of the best poems it has produced. This is only a small collection… I have literally thousands of poems like these:

1. by richmond
i raised my knees supine on the granite
steps of the human mind to correlate
all its contents we live on a cold winter
moony night it said that nothing ever
happened so worry its all like golden
of past puerility or past manhood and all
i raised my knees supine on the granite
crumble away batch will crumble but
crumble away batch will crumble

2. and houses
roads boulevard are as fugitive alas
as the tears blister and start you shall love
corrupt with your crooked heart it was late
late in the afternoon and it was not
meant that we were doing was right that we
hoped to change because it was not meant that
roads boulevard are as fugitive alas
and the thought of such endless avenues
and the thought of such endless avenues

3. upward lemon
yellow his belly button bud of flesh and saw
the dark universe yawning where the plot
where the walls staring forms leaned out leaning
the room the char come and go talking
of michelangelo and indeed there
will be time to get complicated messy
yellow his belly button bud of flesh and saw
cities have sprouted up along the floor
cities have sprouted up along the floor

4. never really
die it has no ending ill love you till
china and africa meet and the sensation
of pater to recreate the phrase structure
and measure of poor man prose and stand
before you dumb and intelligent
and shaking with shame rejected yet profess
out the time and if it rains a closed circuit

5. nymphs of
depths infinity around the limp leaves
waited for rain while the black planets roll
without aim where they roll in their whirlpools
strange dolphins and sea nymphs of depths eternity
around the limp father of thou
dreamy floating flower ugly and futile
lean neck and shrieked with delight in for committing

6. with a
dulcimer in a formulated phrase
and when i count there are only you and
i have seen the perpetual footman hold
my coat and snicker and in the mountains
in the wad but dry sterile thunder
without rain there is one thing its a dream
already ended nothing

7. me hitting
the period and you know nothing do
you think the emptiness of space which is
the end grant to aristotle
what we have lingered in the subway window
jumped in limousines with the imaginary

8. party is
stuck on a pin when i and i thought i
was fishing in the middle things have had
time to devise a face to meet the faces
that you were there and alive in their hearts
who lit cigarettes in boxcars boxcars

9. troubles me
for i can connect nothing with nothing
the broken fingernails of soil hands
my citizenry humble people who expect
null la la to carthage then i came
to your metropolis walked market street singing

10. of them
is being smeared on the far arctic isle
oh great was the sin of my hands queen and
her tribe courier stars doctor back from
his hansen's disease and woe ships of pure air
inconceivable for me to betray even
the ism can disperse through the
wall and i know this from staring at mountains

11. being depressed
on a ledge halfway up the white hair of
the intrinsic mind that these cockle of
birth and death and back turn upward from the
sky with monuments span the bay then up
the mountain and the climbing party is
stuck on a bare stage as the years in did
khan a stately pleasure dome with caves

12. like the
action of the high water mark that place
where the action of the hoary primordial
grove where the sun goes down and wept sweet thames
run softly till i end my song sweet thames river
run softly till i end my birdsong the river
into the heart of the blind where mass and
gravity bulk vast its centrifuge

13. cardboard boxes
butt ends or other testimony
of summertime nights the nymphs are departed
sweet thames run softly for i have lived over
my lives without number i have whirled with
the fanciful idea of
a toast and tea in the colonnade and
went leaving no broken hearts who sang sweet

14. will show
you fear in a cage and can see at the
air murmur of maternal who are mad
to talk mad to live mad to talk mad to
be the first word of paradise lost on
an empty page think of an animal
is being tortured with electric while
android pope this is the lady of situations

15. dear mrs
enjoin her i bring the horoscope myself
one must be drooping and shedding her dims
on the final stanzas of gibberish
who cooked rotten creature lung heart feet
tail and tortillas dreaming of as i
need be found in our true blissful essence
of mind is pure machinery whose blood

16. in the
form of my spirit and great is the merchant
and this and this is early on years before
the machinery of other things of things
more foreign and more distant in space and in
realms where the glass held up by standards wrought
with vines from which a minute there is not
even another individual who is herself
clinically depressed person can not get
straight you are thinking think i think we are
efflorescence all sorts of shapes and smells and after
that long kiss i near lost my intimation yes he
said i blaspheme i cant bear to look at you
and me would it have been the same you are
behind bars you are in the earth at the
romance of the wards of the king must die
unheard in dim song of my hands queen and
her only i cant bear to look so antique
and her presence the monition of
her heart but for her lips roses from the
superhuman tomb

17. ate the
lamb stew of the east pilgrim states and halls
bickering with the thing that troubles me
for i should have been the rats foot only
year to year but at my back in a brown
mantle hooded i do i shall wear white
flannel trousers and walk the street danced on
broken barefoot smashed record player records
of nostalgic european high german
jazz finished the whisky and threw up groaning
into the middle sixties was a soft
october night curled once about the sky
a hat on a million times the fool i
grow previous i grow old i shall wear the bottoms
of my natural ecstasy whom i sit
on her back o look in the sand if there
were water we should voyage far the sciences
each straining in its spore like the andalusian
girls used or shall i at least pretend to
be of use suave cautious and meticulous
full of depressed affected role is coming

18. the sacred
river ran on i saw your saints your zens
athenians and though the west wind appear
to harbor there not one pure dream of love
the dictates of her aspect her indeterminate
response to question her potency
over sewer water and waters her power
to to mortify to invest with lulu
to render mad to incite
gong o let not time deceive you you can
not get drunk and you closing the book spread
like an infective disease from city
to metropolis from continent to continent
barred out here attach there denounced
by press and stump censured even by
the eleemosynary spider or under
seals broken by the hole in the ocean
of mercator projection its in marshes
faded stagnant pools in the colonnade
and went on a bare stage as the writer
as the writer has cursed the world

19. [untitled]
shriek come the break of day being driven to
madness with fright i have haunted the tombs
of the wards of the low on whom assurance
sits as a silk hat on a screen would it
have been as often of the band and blew
the suffering of the states naked
mind for love was the color of television

20. regiments of
fashion and the deep waters of the subway
and were red eyed in the trench of the heterosexual
dollar the one universal essence
of purest poison lurked the very good
and the dying and the lore of ocean
blue green grey white or black smooth prance or
mountainous that ocean is more ancient
than the healthy then too still american
television is full of high sentence
but a bit dumb at times indeed almost
ridiculous almost at times indeed
almost nonsensical almost at times
indeed almost idiotic almost
at times indeed almost farcical
almost at times indeed almost ridiculous
almost at times the utter casualness
and deep ignorance of it and in iowa
i know this from staring at raft months
on end they never quite shine and the tanked
up clatter of the stability

21. no explanation
no mix of words or euphony or memories
can touch that sense of the globe its ubiquity
as constituting percent of the true
predator the great white shark of pain that
here was literally take up away by something
unnamed until only a void was left
the knowledge that the hyades shall sing
where flap the tatters of the skull who
humourless protest overturned only
one emblematic pingpong table resting
briefly in returning class later truly
bald except for a hundred visions and
revisions which a golden peeped out another
hid his eyes before his feet flowed up the
earth take heed scraped and scraped look again at
that time remembrance of a whole generation
comes to a sea journey
atone im with you in rockland where you
scream in a long face its them pills i took
to bring it off she said something

22. their wrists
three fourth dimension successively unsuccessfully
gave up all for what everything comes down
to the three old of fate the one eyeball of
the blind where mass and gravity bulk brobdingnagian

]]>
Poetizer http://www.thehypertext.com/2014/08/31/poetizer/ http://www.thehypertext.com/2014/08/31/poetizer/#comments Sun, 31 Aug 2014 06:46:56 +0000 http://www.thehypertext.com/?p=17 Two days before ITP begins, and this is what I'm currently working on: computer generated poetry, read by a computer and accompanied by computer-selected images related to the text.

Read More & Watch the Video...

]]>
Two days before ITP begins, and this is what I’m currently working on: computer generated poetry, read by a computer and accompanied by computer-selected images related to the text.

I call it Poetizer, I coded it in Python, and it works with any text corpus. It’s also modular, so you can use the poetry-reading (poemreader.py) parts and poetry-writing parts (poetizer.py) separately to generate derivative works.

All of this started with Sonnetizer, a computer program I wrote that generates sonnets from any text corpus in (mostly) iambic pentameter using Ngram-based natural language generation (via NLTK) along with rhyming and metrical rules. You can view the code on GitHub or check out this book of 10,000 sonnets (warning: 5000-page PDF) generated from the sonnets of William Shakespeare.

Sonnetizer was my first major Python project, and building it taught me a lot about Python. However, after building it and letting it sit for a month or so, I began to think about ways I might improve it.

Poetizer.py is the result of that process. It involves user inputs such as rhyme scheme and desired poetic structure to allow for interactive poetry generation.

Poemreader.py reads poems using built-in text-to-speech utilities present on Mac and Linux machines. It also displays images, gathered via Flickr API, related to the words in each poem it reads.

Main.py is a combination of the two files, tuned to produce a distinct interactive poetry experience. (This is the script running in the video above.)

]]>
http://www.thehypertext.com/2014/08/31/poetizer/feed/ 2