Found Poem Generator – User Interaction – Adding Buttons

Working through my list of enhancements for my ‘Found Poem’ Generator that I documented in a previous blog post: 

1. Output the created poems to a larger screen ie a graphical type large fonted output rather than  using the console window.
2. Provide two methods of running:
a. Auto-generate a new poem every 5 minutes or so
b. Provide buttons for user input to create poems on demand
3. Package the program up to be self-contained
4. Deploy the program onto some sort of platform that wasn’t my Mac laptop ie a Raspberry PI and large screen monitor or TV
5. Make the program auto-run when the device is started / restarted

Further enhancements could then be:

6. Use a text / csv file to load in the words and lines of the poems rather than the hardcoded ones used currently
7. Add buttons to the display to allow user interaction – people viewing the installation could interact with it by asking for poems
8. Check the first letter of each line to capitalise it for poems and un-capitalise it for haikus, and add commas to the end of lines if they are missing or remove for haikus.

This blog post describes the update for item number 2(b):

2. Provide two methods of running:
a. Auto-generate a new poem every 5 minutes or so
b. Provide buttons for user input to create poems on demand

My previous experience with programming GUIs started a long time ago with Microsoft Access 2 and Visual Basic 4 and then, later, a number of Borland Delphi iterations with Microsoft SQL Server. With these development environments you got, well, development environments and that meant a WYSIWIG screen designer and a palette of buttons, text boxes, counters and other widgets to choose from. Not so with Python.

Tkinter Screen Layout Design

I had a google around for a WYSWIG screen designer but there really doesn’t seem to be anything that is recommended, one suggestion was to use graph paper but I’m not sure this project is complex enough to go that far. It seems that hand-coding buttons and labels is the way to go using one of the three Layout or Geometry Managers that Tkinter possess. These are Pack, Grid and Place:

‘Pack’, I’m informed, is the easiest to use but gives least control over placement of widgets, merely their relative positions to each other.

‘Place’ is used explicitly to set the position and size of a window, either in absolute terms or relative to another window. This didn’t sound like the sort of thing for creating and laying out a bunch of buttons.

‘Grid’ is similar to Pack but allows a certain amount of control of the placement of widgets by allocating them x and y co-ordinates within a notional two dimensional grid. The dimensions are then determined by the Grid Manager. This sounded the most likely candidate to try and use.

Tkinter Command Buttons

So now I have an inkling of how to place my buttons, my next task is to find out how to create the buttons and then assign the ‘poem’ and ‘haiku’ commands to them such that I could generate some interactive output.

Turning to the code, the first thing I found was that the label I was using to place the text on the screen, using an example copied from the internet, was using the ‘pack’ command. In order to keep things simple, I decided to change course and stick with the ‘pack’ function and see what the outcome was before deciding if I needed to get more complex with my button placement.

In the end I created three buttons and a slider bar, the buttons were for quitting the program (just to make things simpler for testing, I’ll remove this one later), a ‘haiku’ button and a ‘poem’ button. The slider allows the user to slide the scale from 1 to the number of ‘found’ lines there are available before pressing the ‘poem’ button to generate a poem of that number of lines. 

FoundPoemGenerator_Screen_Buttons

In doing this I uncovered what I thought was a bug in the system where after generating one haiku the program would appear to freeze with the spinning pointer icon, yet the ‘poem’ button worked fine. I say it worked fine, a little more button pressing revealed that the ‘poem’ button also eventually ran into the same problem, and then the penny dropped. The code is designed to mark any lines used in a poem as such ie already used, this meant that the ‘haiku’ function was very quickly running out of 3 and 5 syllable lines to use and so the program got stuck in an endless loop of looking for lines that weren’t there.

The fix was easy, to clear the ‘line already used’ flag between each press of a button. I’m not altogether happy with this outcome as my design was to ensure each poem produced was unique, which logically thinking couldn’t actually work unless I had infinite lines of poem to draw from. A case of having to admit my design was flawed and forge ahead with the new working design.

Source code available here for this update.

Found Poem Generator – Outputting Text To A Graphical Screen

Following on from my last post regarding the proposed additions to the ‘Found Poem’ Generator I started working on the list of enhancements with the aim of building the Found Poem Generator into something that could be used ‘out in the wild’ as a stand-alone art installation:

  1. Output the created poems to a larger screen ie a graphical type large fonted output rather than  using the console window.
  2. Provide two methods of running:
    1. Auto-generate a new poem every 5 minutes or so
    2. Provide buttons for user input to create poems on demand
  3. Package the program up to be self-contained 
  4. Deploy the program onto some sort of platform that wasn’t my Mac laptop ie a Raspberry PI and large screen monitor or TV
  5. Make the program auto-run when the device is started / restarted

Further enhancements could then be:

  1. Use a text / csv file to load in the words and lines of the poems rather than the hardcoded ones used currently
  2. Add buttons to the display to allow user interaction – people viewing the installation could interact with it by asking for poems
  3. Check the first letter of each line to capitalise it for poems and un-capitalise it for haikus, and add commas to the end of lines if they are missing or remove for haikus.

 

This post deals with number 1:

  1. Output the created poems to a larger screen ie a graphical type large fonted output rather than  using the console window.

The first task here was to identify a way of actually doing this, Python is a modular language where a lot of functions exist in external libraries that need to be added in to what ever you are writing. A search on the internet suggested Pygame or Tkinter might be the way to go. Pygame is a game development library whereas Tkinter is a GUI development library. Although neither jumps out as being ideal for simply outputting text to a large screen, Tkinter had the benefit of being built-in / pre-installed with Python so that was my first choice.

Another search on the internet, now looking for how to output text to a graphical screen using Tkinter, turned up a code snippet that I used to very quickly update the code to output to the graphical screen:

1-OutputToLargeScreen

As a proof of concept, this is working great for me at the moment, although there does seem to be some kind of bug or issue where the graphical screen doesn’t display or close properly. This appears to be a Mac specific issue, so I’m not too concerned at the moment as the project will ultimately be running on a Raspberry Pi, although I can foresee some more possible challenges with developing on a Mac and then porting to the Pi.

So onto the next stage now, providing buttons on the screen to allow prospective users to interact with the program and generate their own poems.

 

Source code for this update to the project can be downloaded here.

Found Poem Generator – The Next Level

When the latest Ledbury Poetry Festival e-mail dropped into my inbox last week it set me thinking again about the ‘Found Poem’ Generator I had been working on using Python. The festival was announcing the debut of their collaboration between poet Sara Jane Arbury, Joined Up Heritage and Ledbury Poetry Festival who have created a poetic walk around eight key heritage sites in Ledbury using ‘found poetry’ comprising words from First World War poets and phrases contained in the buildings themselves.

Ledbury has quite a history with poetry, being the birthplace of Poet Laureate John Masefield and has close associations with the Dymock Poets.

With my current interest in ‘found poetry’, following the course I participated in on FutureLearn featuring Michael Simmons Roberts and Helen Mort, and my latent interest in Ledbury and the Ledbury Poetry Festival having lived in Ledbury for a short while, this set the thoughts rolling around in my head: what if I could extend my Found Poem Generator to create a display piece or interactive kiosk? Could this then be utilised as a poetry installation out in the real world?

So, in order to achieve this I need to:

  1. Output the created poems to a larger screen ie a graphical type large fonted output rather than  using the console window.
  2. Provide two methods of running:
    1. Auto-generate a new poem every 5 minutes or so
    2. Provide buttons for user input to create poems on demand
  3. Package the program up to be self-contained 
  4. Deploy the program onto some sort of platform that wasn’t my Mac laptop ie a Raspberry PI and large screen monitor or TV
  5. Make the program auto-run when the device is started / restarted

Further enhancements could then be:

  1. Use a text / csv file to load in the words and lines of the poems rather than the hardcoded ones used currently
  2. Add buttons to the display to allow user interaction – people viewing the installation could interact with it by asking for poems
  3. Check the first letter of each line to capitalise it for poems and un-capitalise it for haikus, and add commas to the end of lines if they are missing or remove for haikus.

 

Subscribe to my blog and watch out for these enhancements and future posts – coming soon!

 

Found Poem Generator – Adding Haikus

Haikus

The wind blows in gusts
little pieces here and there
the fools in the hall

– Shadow The Poet aka James Laurie

Now that I had the Found Poem Generator working and creating poems with the number of lines asked for by the user I thought it was time to move on to the Haiku Generator idea. This would be a similar process but uses the syllable count property of each line of text. I also have the word count stored as a property which I may use later to create poems with lines of equal word length.

The Haiku has a fixed format of three lines, the first is five syllables, the second line is seven syllables, then back to five syllables for the last line.

I already had the code that generated a poem by lines, so I thought I could re-use this piece of code with some small modifications. This is always my methodology when coding – can I re-use something I’ve already done? It’s much easier to copy and paste something used in a previous project or something written in the current project rather than having to write a new section from scratch. 

Functions

When re-using code from the current project my second question is – can I modify the existing code to re-use it ‘in-situ’ rather than copying and pasting it out to the new location. What I mean by this is – can I make it a generic function? For example, we might have a piece of code that adds 1 and 1 together:

result = 1 + 1

If I needed to added two numbers together elsewhere in my program, ie 2 and 2, I could copy and paste the code above and update it to the new requirement:

result = 2 + 2

Nice and simple and works just fine, but, for me, the most elegant and de-buggable code always avoids duplication. Let’s suppose this was a more complex calculation, maybe 10 or 20 or 100 lines long, and I had used it hundreds of times in the program. Then imagine I found a bug in my calculation. Now I have to trawl though dozens or hundreds of lines of code to find and correct the problem wherever I found it. The risk being that I miss some and have now created for myself one of those annoying bugs that only appears under seemingly random circumstances and becomes harder and harder to track down. So, in circumstances like this I would always try to create a function from the original code rather than copy and paste it verbatim:

define adding_together_function(input:number1, number2, output:result):
result = number1 + number 2

Now this new function can be used whenever two numbers need adding together –

the_answer = adding_together_function (1,1)

Creating The Haiku Code

So with this in mind, I firstly updated the program to take the ‘doing’ code for the poem command out of the main loop of the program and put it into its own function. Once this was done I took a copy and changed the code so that it would select lines based on syllable count rather than just maintain a line count:

def output_by_syllable(no_of_syllables):
    found_line = 0
    while found_line == 0:
        random_num = random.randint(1,no_of_lines)
        phrase_meta = ("p" +str(random_num) )
        for phrase in Phrase._registry:
            if str(phrase.name) == str(phrase_meta):
                if phrase.get_used() == False:
                    if phrase.get_syllablecount() == no_of_syllables:
                        phrase.set_used(True)
                        found_line = 1
                        print(phrase.text)    

With an eye to adding other syllabic poem forms to the program in the future, I then created a Haiku function that uses the ‘output_by_syllable’ function to create the Haiku:

def output_haiku():
#line 1 - 5 syllables
    output_by_syllable(5)
#line 2 - 7 syllables
    output_by_syllable(7)
#line 3 - 5 syllables
    output_by_syllable(5)

Finally I added a new menu option for generating the Haiku:

    elif command == "haiku":
        output_haiku()    

I’ve added the updated code to my Dropbox share for this new feature.

the fools in the hall
little pieces here and there
The wind blows in gusts

– Shadow The Poet aka James Laurie

 

See a run through of progress so far:

 

Thinking On

Every day I walk these streets I try to take them in. Every detail, the pall of smog from the incinerator smokestack separating the oily black of the night sky from the neon glow of the streetlights lining the A50 below. The football stadium stands like a citadel in the middle of the middle distance and the drone of the traffic rises up to meet me.

Chamberlain Avenue draws up from London road in a exponential steepness dragging its way upwards from the kebab shops and oatcake shops, broken windows and broken paving slabs. The discarded sweet wrappers, beer cans and broken glass are suddenly gone and fallen leaves take their place in piles of brown and gold. Council workers blow and sweep the leaves into the back of their pickup but they don’t pick up the rubbish in London Road. Chamberlain Avenue leads to Penkhull, London Road is Stoke. Stoke Town. One of the six towns of Stoke-on-Trent.

I take in these details, because one day when I have left here and find my peace, these things, these memories and sights and sounds will become words and stories and songs. But for now they weigh heavily and it is the best I can do to take them in at all.

Found Poem Generator – Introduction

“How do you go back to the beginning?
Short stories are the best,
It’s always one step behind me,
The fools in the hall.
When your life has already flown?
Our life, a wheel within a wheel.”

–  Shadow The Poet aka James Laurie

I recently undertook a course on learning Object Oriented Programming using Python. This is one of the many useful little courses provided by universities and hosted by the FutureLearn website which I occasionally frequent. I wrote about their Song Writing course featuring Martin Simpson a little while ago.

I spent a period of my life writing software using Borland Delphi, so I am familiar with Object Oriented Programming, or OOP as it is known using its TLA. My interest in this course was to get stuck into a language that is relevant to the hobbyist / creative and as pervasive as BASIC used to be back in the good old days of home computing. Python is built in to Linux, so features on many Raspberry Pi’s, and also is therefore MacOS and so fits the bill straight off. What also piqued my interest was that the course would teach using Python by using it to write a text-based adventure game, something I misspent an early part of my youth playing.

As I followed the course I had an idea of using what I had learnt so far to write a ‘Found Poem Generator’. Rather than creating dungeon rooms and items as Objects, I would create lines of a poem. These lines could then have attributes attached to them such as word count and syllable count, perhaps even metre or some other attribute. Once I had collected my lines, counted the words and syllables and fed them into the program I would then be able to generate poems. The results could then be edited and new poems would come into being. 

I felt there was precedent for this firstly as I sometimes do this anyway by looking at my book of fragments and pulling various lines out to create a new poem. Valerie Laws did something similar in 2002, although more organic than technological, by writing her lines on sheep and using the random wanderings and grouping of the sheep to create new poems.

Warm drift, graze gentle, White below the sky, Soft sheep, mirrors, Snow clouds.

– Valerie Law’s Sheep

FoundPoemScreenShot1

At the moment the program can create a random poem based on my found lines which stored in one of its files. The command ‘poem’ followed by a number will cause it to generate a poem of that many random lines. I also store the number of words in the line and the number of syllables too as my next update will be to start incorporating standard poem forms into it. Haiku’s and other syllabic forms will probably be first.

The found lines are currently hardcoded into the program, as I still haven’t found out how to read data from a text file or spreadsheet yet using Python. In order to simplify things for myself I created a spreadsheet that I can use to hold my found lines. It has some text manipulation formulas in it that convert the lines I enter into the correct format for copying and pasting into the program file.

I have uploaded all this into a Dropbox folder here if you fancy a play with it, if you wouldn’t have a clue what to do with them then have a look at the FutureLearn course I did or look out for a future blog where I’ll try to explain.

“When your life has already flown?
Our life, a wheel within a wheel
The fools in the hall
The wind blows in gusts
Looking for that way home”

–  Shadow The Poet aka James Laurie

 

Incantation Number 7

Write something profound,
Write something meaningless,
Write for the joy of writing,
Write for the hate of writing,
Write for the ugly,
Write for the beautiful,
Write the way,
Write the time,
Write for the right now, the long goodbye and the happy ever after
Write for all the dark mornings and the long dark nights,
Write for the summer sun and the winter stars,
Write for the blazing heat, the bitter cold, the warm rain and the cold snow,
Write for the stark mountain peaks and the lush valleys depths below,
Write for rivers of ice, streams of crystal cool, gold filled, earth blood,
Write for the burning horizon an the nothing in-between,
Write for love,
Write to save your soul,
Write for peace,
Write for right and write to make the world whole,
Write to be read,
Write to be ignored,
Write to be indifferent,
Write, just write once more.

I Remember – Bromyard Folk Festival 2018

‘I Remember’, roughly recorded in the campsite of the Bromyard Folk Festival.

I don’t have any way of documenting the melodies for the songs I write, only the chords and lyrics, so recording them is my best option at the moment in case I forget the tune later.

The lyrics are based on the poem style of a pantoum, a form where the lines are repeated throughout the poem / song:

Stanza 1

A
B
C
D

Stanza 2

B
E
D
F

Stanza 3

E
G
F
H

Stanza 4

G
C
H
A

Front Room

Front room,
Drawing room or parlour.
Best room.
Now a store room.
I write at an old table,
With drawers and planks screwed down on top.
A phone, a mug and a crowbar
Are my companions.
The street is silent for a moment.
18:37
Unlike the time the neighbour’s dog
Barked for three nights long, three long nights.
The ink in my pen runs out
And as I return with a new cartridge
Aware of the headache arriving soon
I step on a splinter of wood
From the busted up wardrobe.
My bare foot bared,
Unprotected.
The silence is over.
18:39

 

I Remember

Music has always been with me and I have always been with music, I remember my first ‘personal stereo’ cassette player back when Walkmans were really Walkmans and the Grundigs and Thorns did the same for less money. I don’t really remember my dad being interested in music at all, maybe sometimes humming a big band tune now or then. My mum had a few records, Roy Orbison, the Carpenters and the like. She would always sing along to the radio in the car which was always tuned to BBC Radio 1 back then when we were lucky if the radio had an 8 Track player let alone a cassette tape player. My oldest brother recorded his Bowie records for me and I spent many hours digesting Space Oddity, the Laughing Gnome, the Little Bombardier, Life on Mars and all the others, not really understanding, aged just 9, what was unfolding through my headphones. New music came my way – Beatles tapes from my Mum’s friend Maggie, Queen and Dire Straits, 6th Form influences of Goth with the Sisters of Mercy, the Mission and Fields of the Nephilim and the explosion of the Los Angeles sleaze metal scene headed by the unknown but soon to be very well known Guns n’ Roses, Faster Pussycat and the German metal bands Helloween and Accept and many others in between.

In all of this though, one thing I knew was that no matter how much music I listened to or how many concerts or gigs I saw there was never the slightest possibility that I would ever be able to make music. Of this one thing I was sure, I couldn’t play an instrument, I couldn’t sing and like the other talents in life I didn’t have like being sporty or artistic or out-going I just accepted my place in life because at least I was kind of smart and if I got good grades and a good job everything would be ok.

In my later teenage years I picked up a guitar and learned some rudimentary chords, I learned that although I could remember the chord shapes I could never remember the order to play them in to play a song, let alone remember the words. I saw other friends grow in talent in leaps and bounds and I was left strumming quietly in my bedroom with a couple of song books and a borrowed guitar.

Suddenly it was the mid-nineties and the internet had been invented, I had no hope of tabbing songs for myself of hearing a chord or key being played and knowing what it was. The internet opened a new world of others tabbing songs and uploading them to ftp servers back when the internet was more than just world wide web, it was ftp, it was gopher, it was irc and a whole lot more in between.

I began to download song sheets with chords and found that I could now passably play and sing along to the Dog’s D’Amour and Counting Crows although I knew how bad it must sound and that’s how I remained, occasionally playing on borrowed guitars for the next twenty or so years.

Unlearning the programming, the Shadows of the past is a journey. It started with the gnawing sensation that there must be something more to this, with a two day corporate ‘Effective Communications’ workshop that taught me that I was not my thoughts and opened the door to this journey of discovery.

I wrote a lot of poetry at this time, performed a lot of it until the well ran dry. I’m happy I had it for a time and look forward to its return. Another chance remark from someone asking if I wrote songs as well percolated in my brain for a year or two until last spring half a dozen songs fell out. But what was I to do with them – they don’t read like poems and I can’t sing or play them, other than the in the safety of my own living room. So I picked up the guitar with earnest, learnt to finger pick over the summer and actually, finally, bought my own guitar.

How many hurdles had I crossed to have the stuttering confidence to walk into a guitar shop – a guitar shop! With real musicians playing real music! What the hell did I think I was doing? One corner of the store was a sea of acoustic guitars and we must have played every single one of them. Of course the guitar I fell in love with didn’t tick any of my pre-conceived boxes – it’s fully acoustic, doesn’t have a cut-away so I can’t reach anything below the twelfth fret and it was £150 or so below budget.

So fast forward to now, three weeks ago to be precise when I saw my friend Joey had a banjo. “I just play for myself”, he said, “I don’t care how I sound”. A few days later I heard him play and he could play. He showed me ‘clawhammer’ style – “strike, strum, thumb!” and a blue-grass finger picking roll. As I was leaving he lent me his banjo and urged me to search YouTube for Patrick Costello to learn how to play. I didn’t really understand why as I thought it was just a matter of learning some new chord shapes and getting some speedy finger picking practice in. How wrong could I be, the banjo is a craft all of it’s own, with percussion, chords and melody all in one. Patrick urges us to play, and better than to play is to share and show someone else how to play, to go out in the world and make music. He tells us that anyone can sing, anyone can play.

I made a couple of short videos of me playing the banjo after one week and after three weeks, just something to remember how it was when I started and hopefully see the improvement in the coming weeks and to spread the word and work and boundless enthusiasm of Patrick Costello. I didn’t make a video after week two – I was too self-conscious to record it with anyone else in the house. But then I made this, I’m not sure why. I can see all the flaws in it but in the words of Johnny Cash in his version of the Streets of Laredo I’ll “not mention his name and his name will pass on”.