Python – Nutrition – NOMS – USDA API

# noms -

import noms
import pickle
import os

key=open('myapikey.txt', 'r').read()

#client=noms.Client(key)
#results = client.search_query('Raw Broccoli')
#print(results)

food_dict_daily={
        '747447': 100, # Raw Broccoli
        '1103064': 1 * 180, # Ripe plantain, raw
        '169753' : 100, # Rice, white, long-grain, regular, cooked, enriched, with salt
        '1103657': 100, # Vegetable curry
        '1100622': 100, # Bread, white, toasted
        '1100187': 100, # Egg, whole, fried no added fat
        '1099246': 100, # Chicken curry
        '1097525': 100, # Milk, lactose free, whole
        '1097524': 100, # Milk, lactose free, reduced fat (2%)
        '1429086': 100, # ENSURE, HIGH PROTEIN POWDER, VANILLA, VANILLA
        '168833' : 100, # Sugars, brown
        '1103067': 100, # Plantain chips
        '1101716': 100, # Cereal, corn flakes
        }
food_dict_daily ={
        '1103064': 1 * 180, # Ripe plantain, raw 
        '169753' : 2 * 185, # Rice, white, long-grain, regular, cooked, enriched, with salt cup
        '1103657': 1 * 245, # Vegetable curry cup
        '1100622': 0 * 25, # Bread, white, toasted
        '1100187': 2 * 49.6, # Egg, whole, fried no added fat
        '1099246': 1 * 235, # Chicken curry cup
        '1097525': 2 * 244, # Milk, lactose free, whole cup
        '1097524': 0 * 244, # Milk, lactose free, reduced fat (2%) cup
        '1429086': 1 * (57 * 2)/16, # ENSURE, HIGH PROTEIN POWDER, VANILLA, VANILLA 1 cup = 16 tablespoons, 0.5 cup --> 57 g
        '168833' : 2 * 13.56, # Sugars, brown tablespoon
        '1103067': 0 * 60, # Plantain chips 1 cup
        '1101716': 1 * 88, # Cereal, corn flakes, cup
        }
#food_objs = client.get_foods(food_dict_daily)
food_objs = pickle.load(open('mydailyfoodtestbar.pkl', 'rb'))
meal = noms.Meal(food_objs)

r = noms.report(meal)
for i in r:
    #print(i)
    print(i['name'], '\t', i['rda'], '\t', i['value'])

# scale the y values to 100
for data in r:
    if data['rda'] != 0:
        conv = 100/data['rda']
        data['rda'] = 100
        data['value'] *= conv

# termgraph
with open('ytclass_data.dat', 'w') as f:
    print('@', 'rda,y_value', file=f)
    for data in r:
        print(data['name'], data['rda'], data['value'], sep=',', file=f)

#os.system('termgraph ytclass_data.dat --color red blue')

pantry_foods = pickle.load(open('pantry_foods_data.pkl','rb'))

recommendations = noms.generate_recommendations(meal, pantry_foods, noms.nutrient_dict, 3)
for rec in recommendations:
    print(round(rec[2] * 100, 2), 'g', "of", pantry_foods[rec[1]].desc)

Python – numpy – pillow – translate text on canvas

A python program to draw a text on canvas using pillow and translate it using numpy arrays.

"""
A program to translate text on canvas.
Uses numpy arrays for translating and pillow to draw text.
Author: Jithesh Kuyyalil (https://jitheshkuyyalil.com)
Date  : May 29, 2019
"""
from PIL import Image, ImageDraw, ImageFont
import numpy as np

img = Image.new("L", (500, 500))
array_raw = np.asarray(img)
font_size = 20
font_path = 'DroidSansMono.ttf'
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(font_path, font_size)
# draw text to extract the image array
draw.text((0, 0), "HELLO", fill='white', font=font)
img_array = np.asarray(img)
# non zero elements in the image array
non_zero = np.nonzero(img_array)
# find the edges of the text row and column wise
row_min, row_max = min(non_zero[0]), max(non_zero[0])
col_min, col_max = min(non_zero[1]), max(non_zero[1])
# extract the text pixels as array
text_pixel = img_array[row_min:row_max+1, col_min:col_max + 1]
# make array_raw writable
array_raw.setflags(write=1)
# amount of translation
trans_row = 20
trans_col = 400
# check for boundary condtions so that text don't cross canvas edges
# 500x500 is the canvas size
if row_min+trans_row >=0 and row_max+1+trans_row =0 and col_max+1+trans_col <=500:
    # paste the text into the original canvas
    array_raw[row_min+trans_row: row_max+1+trans_row, col_min+trans_col:col_max+1+trans_col] = text_pixel
else:
    # just draw the original text, no translation
    array_raw = img_array
arraytoimg = Image.fromarray(array_raw)
arraytoimg.show()

Random words on canvas – python/pillow

A program to place words randomly on a canvas. Words are place around a spiral starting from the center. Uses AABB – AABB bounding box collision detection for letter-letter collision.
Ref: Real-time Collision Detection by Christer Ericson

"""
May 9, 2019
A program to palce a list of words, randomly on a canvas. 
Places words around spiral. Uses bounding box collision detection.
Author: jithesh Kuyyalil https://jitheshkuyyalil.com
Date: April 26, 2019
"""
from PIL import Image, ImageDraw, ImageFont
import numpy as np
from random import randint
from spiral import spiral

img = Image.new("L", (500, 500))
#word = "b"
word_list = ['a', 'b', 'c', 'd', 'e', 'f']
#word_list = 'thebookthiefishere'
font_size = 50
font_path = 'DroidSansMono.ttf'
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(font_path, font_size)
# save bounding box co-ordinates [[(), ()], [(), ()]]
box_coord = []  
for word in word_list:  # for each letter
    # x, y, where the word/letter is placed, somewhere top-left
    sp = spiral(500, 500, 250, 250)
    count = 0
    while True:
        x, y = next(sp)
        # font metrics to construct bounding box around letter
        (x1, y1, x2, y2) = font.getmask(word).getbbox()
        (width, baseline), (offset_x, offset_y) = font.font.getsize(word)
        # top left corner
        rect_1 = (x1 + x + offset_x, y1 + y + offset_y)   
        # bottom right corner. Not clear about -1  
        # Rectangle fits well with -1.
        rect_2 = (x2 + x + offset_x -1, y2 + y + offset_y) 
        intersect = False  # both letter-boundary, letter-letter collision
        # boundary collision testing - boundary (0,0), (500,500)
        # hitting the boundary
        if not (rect_2[0] < 500 and rect_2[1] < 500): 
            intersect = True
        # only if letter doesn't hit boundary
        if intersect == False: 
            # checking for collision
            if box_coord != []:
                #print(box_coord)
                for box in box_coord:
                    # not intersecting
                    if (rect_1[0] > box[1][0]) or (rect_2[0] < box[0][0]): 
                        continue 
                    # intersecting
                    if (rect_1[1] > box[1][1]) or (rect_2[1] < box[0][1]): 
                        continue
                    intersect = True
                    break # interesecting; find new x, y
        if not intersect :            
            #draw.rectangle([rect_1, rect_2], outline='white')
            draw.text((x, y), word, fill='white', font=font) # 175, 90
            box_coord.append([rect_1, rect_2])
            break
        count = count + 1;
        if count > 500 * 500:
            break
img.show()

Python code to generate spiral co-ordinates.

"""
A program to generate spiral co-ordinates in a 2D square lattice.
Algorithm due to Can Berk Güder at stackoverflow.com
author: jithesh kuyyalil
Date:   May 1, 2019
"""
def spiral(m, n, Xc = 0, Yc = 0):
    # 0, 0 at the top left corner
    # Xc, Yc somewhere on the canvas
    x = 0
    y = 0
    dx =  0
    dy = -1
    for i in range(max(m,n)**2): 
        if (-m/2 < x <= m/2) and (-n/2 < y <= n/2): # from each matrix \
                # what is necessary
            #print(x, y)
            if Xc != 0 or Yc != 0:
                yield x + Xc, y + Yc
            else:
                yield x, y
        if x == y or (x < 0 and x == -y) or (x > 0 and x == 1-y): # each turn \
                # change dx and dy
            temp = dx
            dx = -dy
            dy =  temp
            #print('dx, dy ', dx, dy)
        x = x + dx
        y = y + dy

if __name__ == '__main__':
    import matplotlib.pyplot as plt
    sp = spiral(300,300, 150, 150)
    X = []
    Y = []
    for i in range(150):
        #print(next(x))
        x, y = next(sp)
        X.append(x)
        Y.append(y)
    plt.plot(X, Y, 'o')
    plt.show()

Bounding Box Collision – python

A python program using PIL (pillow) to place a letter randomly on the canvas of fixed dimension. Uses AABB – AABB bounding box collision detection for letter-letter collision.
Ref: Real-time Collision Detection by Christer Ericson

"""
April 30, 2019
A program to palce letter a letter randomly on the canvas. 
Letter Bounding Box Collision Test
Author: jithesh Kuyyalil https://jitheshkuyyalil.com
Date: April 26, 2019
"""
from PIL import Image, ImageDraw, ImageFont
import numpy as np
from random import randint

img = Image.new("L", (500, 500))
word = "b"
font_size = 100
font_path = 'DroidSansMono.ttf'
draw = ImageDraw.Draw(img)
font = ImageFont.truetype(font_path, font_size)
box_coord = []  # save bounding box co-ordinates [[(), ()], [(), ()]]
for i in range(100):
    # x, y, where the word/letter is placed
    x = randint(0, 500)  # 110 400
    y = randint(0, 500)  # 110 400
    print('xrand, yrand', x, y)
    (x1, y1, x2, y2) = font.getmask(word).getbbox()
    (width, baseline), (offset_x, offset_y) = font.font.getsize(word)
    rect_1 = (x1 + x + offset_x, y1 + y + offset_y)   # top left corner
    rect_2 = (x2 + x + offset_x -1, y2 + y + offset_y) # bottom right corner \
            # don't know -1 ? \
            # Rectangle fits well with -1.
    intersect = False  # both letter-boundary, letter-letter collision
    # boundary collision testing - boundary (0,0), (500,500)
    if not (rect_2[0] < 500 and rect_2[1] < 500): # hitting the boundary
        intersect = True
    if intersect == False: # only if letter doesn't hit boundary
        # checking for collision
        if box_coord != []:
            print(box_coord)
            for box in box_coord:
                if (rect_1[0] > box[1][0]) or (rect_2[0] < box[0][0]): # not \ 
                    # intersecting
                    continue 
                if (rect_1[1] > box[1][1]) or (rect_2[1] < box[0][1]): # not \
                        # interesecting
                    continue
                intersect = True
                break # interesecting; find new x, y

    if not intersect :            
        #draw.rectangle([rect_1, rect_2], outline='white')
        draw.text((x, y), word, fill='white', font=font) # 175, 90
        box_coord.append([rect_1, rect_2])
img.show()

Birth and Death – fifteen hours of you

I wait for Wednesdays
Wait so eagerly, impatiently
Counting every breath
That I can seen you.
But when you leave,
Say goodbye every night
My heart is broken.
And I am okay
As it get patched up,
Piece by piece
In the hope that I see you
See you again the next evening.
But on Friday,
Friday, when you leave
I am devastated
I fall into the depths,
Depths of Eternity
Depths of Darkness
A Place of No Return
My heart is broken
Broken into millions of pieces
And I am okay
For when I close my eyes
All I can see is you.

(So I wake up
Wake up from my slumber
From the Eternal Sleep
Start to breathe
Breathe again to wait
Wait for another Wednesday
For another fifteen hours of you.)

Ode On Your Belly

This morning I sat down
Sat down to write that poem
The poem about your belly
It made me vulnerable
So vulnerable that I stopped writing
Realizing that it is not about me
Its your belly, the poem about
I sat down again, to jot down few lines
Then I didn’t know what to write
I did word association
Your belly, soft, puffy, plummy, yummy..
..electrifying, enamoring…
I felt dissatisfied, a taste of jealousy
The thin layer of shirt between
Between your belly and my palm was the villain
I wished he hadn’t been there
I might want to move left or right or up or down
To explore all other soft puffy areas
Areas nature carved out so beautifully
A ray of shudder passed through my skin
And I melted into a brook and flowed all over
May be that shirt was a blessing
Lest I should lose myself
I still wonder,
Was I writing about your belly
Or the feel I felt about your belly
I don’t know, I don’t care
It all feel puffy and soft and good
Knowing that your belly is
Another marvel of nature

Thinking ball – random walk, biased

Here is a code which employs biased random walk to help a ball get out of a box with one exit. It is coded in python using tkinter module. Does the ball have an intelligence?

"""
Thinking ball
Ball 'tries' to find way out of a box with exit on one side.
Strategy: random walk, biased
Author: Jithesh Kuyyalil
web: https://jitheshkuyyalil.com
"""

from tkinter import *
import time

width  = 600
height = 600

gui = Tk()
dimension = str(width)+'x'+str(height)                              
gui.geometry(dimension)
gui.title("Thinking ball")
canvas = Canvas(gui, width=width, height=height, bg='black')
canvas.pack()
ov1 = canvas.create_oval(225, 225, 275, 275, fill='pink')  # ball width 50
#print(help(ov1))
canvas.create_line(50, 50, 50, 550, fill='blue')    # left
canvas.create_line(50, 550, 550, 550, fill='blue')  # bottom
canvas.create_line(550, 550, 550, 150, fill='blue') # right
canvas.create_line(550, 50, 50, 50, fill='blue')    # top
def moveBall():
    gui.update()
    time.sleep(3)
    from random import random
    while True:
        x_oval = canvas.coords(ov1)[0]  # top left
        y_oval = canvas.coords(ov1)[1]  # top left
        X_oval = canvas.coords(ov1)[2]  # bottom right
        Y_oval = canvas.coords(ov1)[3]  # bottom right
        rnd = random()
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        # Is intelligence?
        # No memory?
        # boundary conditions + moving logic
        if rnd  50 and Y_oval < 150:
                canvas.move(ov1, 5, 0)
            else:
                if X_oval + 5 = 0.5 and rnd < 0.6 and Y_oval + 5 =0.6 and rnd  50: # left
            canvas.move(ov1, -5, 0)
        else:
            if y_oval -5 > 50: # top 
                canvas.move(ov1, 0, -5)
        # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        gui.update()
        print(canvas.winfo_x(), canvas.winfo_y())
        time.sleep(0.09)

moveBall()
mainloop()

Ball: Initial Configuration
Ball: Final Configuration

I was a bit too early

Love called me from behind
I turned back and saw your face
I did some math
The math didn’t seem to work
I was here a bit too early
If I had known you would come
I would have waited
Waited as long as it takes
I see a world of wonders before you
So I let you go, set you free
And I said goodbye
I am sure love will be calling you
When you turn back, it wouldn’t be my face
A prince will come to charm your world
To steal your heart away
Love asked “what about you?”
I said “I’ll be okay, I am okay”