Making Art by Judging Reddit

Is the Raspberry Pi 4 powerful enough to judge Reddit? This project is all about answering the important questions.

Overview

Below a quick overview of the content.

  • Introduction and showcase video
  • Fetching the latest Reddit comment
  • Scoring the comment
  • From score to colour
  • Result

Introduction and showcase video

We've all heard about Reddit, and how powerful the new Raspberry Pi is. Let's combine them to answer the age old question, “Can a Pi judge Reddit?”

Fetching the latest Reddit comment

To start of we're going to fetch the latest Reddit comment. Pushshift.io is exactly what we need. With a simple API call we can fetch the latest comment.

url = "https://api.pushshift.io/reddit/search"   
querystring = {"sort":"desc","sort_type":"retrieved_on","limit":"1","lang":"eng"}   
response = requests.request("GET", url, params=querystring)   
d = json.loads(response.text)
comment = str(d['data'][0]['body'])

And that's it for this part, we're fetching the latest comment and can watch them roll in.

Scoring the comment

We now want to know how positive or negative our comment is.

To make our lives easier we're going to use an Azure API, the sentiment analyses.

This API will receive a text and rate it with a number between 0 and 1.

A super positive text will get a score close to 1 and a very negative close to 0.

Before we can use any of this AI magic we need to do some mandatory setup.

With that, our cognitive services is all ready and we can start using it.

Here's the base call:

url = "https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment"
  
payload = '{"documents": [{"text":"' + comment + '",  "language": "en", "id":"1"}]}'
  
headers = {
    'ocp-apim-subscription-key': "<Your Key Here>",    
    'content-type': "text/json; charset=utf-8",    '
    cache-control': "no-cache"}
  
response = requests.request("POST", 
                            url, 
                            data=payload.encode('utf-8'), 
                            headers=headers)
  
d = json.loads(response.text)
score = float(d['documents'][0]['score'])
  

Some example comment with their score:

From score to colour

Almost there, we can start creating some beautiful art.

To limit the API calls we divide the screen in 16 sub screens, each scored comment is represented in a pixel block of 30×30 per sub screen.

To get the colour right we start with red or RGB(255, colour, colour). We calculate the colour placeholder by multiplying the score with 255. Meaning a 1 (positive) will create RGB(255, 255, 255), or white.A negative comment, or 0 will give us red, and that's RGB(255, 0, 0).

The last part is assigning this colour to the pixel block of each sub screen and moving to the next one, completing the logic.

You can find the complete code in de ‘Code' section.

Result

And that's it! We've got a very stylish piece of dynamic art, made by judging Reddit comments.

It also answers our question, the new Pi can judge Reddit, just not sure how well…

Code

import requests
import time
import json
import re
import pygame
import random


def getLatestComment():

    url = "https://api.pushshift.io/reddit/search"
    querystring = {"sort":"desc","sort_type":"retrieved_on","limit":"1","lang":"eng"}
    response = requests.request("GET", url, params=querystring)
    d = json.loads(response.text)
    comment = str(d['data'][0]['body'])
    comment = comment.replace("'", "")
    print('Comment: ' + comment)
    return comment

def getSentimentScore(comment):

    url = "https://westeurope.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment"

    payload = '{"documents": [{"text":"' + comment + '",  "language": "en", "id":"1"}]}'

    headers = {
        'ocp-apim-subscription-key': "xxxxxxx",
        'content-type': "text/json; charset=utf-8",
        'cache-control': "no-cache"
    }

    try:

        response = requests.request("POST", url, data=payload.encode('utf-8'), headers=headers)

        d = json.loads(response.text)
        score =  float(d['documents'][0]['score'])

    except Exception:
        score = random.random()

    print('Score: '  + str(score))
    return score


def run(fillScreen):

    divides = 4
    widthSteps = width/divides
    heightSteps = height/divides
    positions = []

    size = (steps,steps)

    for block in range(divides):

        if block == 0 or block == 2:
            startX = 0
        else:
            startX = (widthSteps * 2)

        if block == 0 or block == 1:
            startY = 0
        else:
            startY = (heightSteps * 2) 

        startPositions = (startX,startY)
     
        for segment in range(divides):

            if segment % 2 != 0:
                posX = startX + (widthSteps * 2 - steps)
            else:
                posX = startX

            if segment == 2 or segment == 3:
                posY = startY + (heightSteps * 2 - steps)
            else:
                posY = startY

            position = (posX,posY)
            positions.append(position)

    rightDown = [0,4,8,12]
    rightUp =   [2,6,10,14]

    
    leftDown = [1,5,9,13]
    leftUp =   [3,7,11,15]

    for i in range(120):

        index = 0

        if fillScreen == False:
            time.sleep(2)
            comment = getLatestComment()
            score = getSentimentScore(comment)
            randomColour = 255 * score
        else:
            randomColour = random.random() * 255

    
        colour = (255,randomColour,randomColour)

        
        for position in positions:
            
            pygame.draw.rect(surface,colour,(position,size))
            pygame.display.update()

            if index in rightDown:

                if index == 0 or index == 8:
                    if position[0] == 420:
                        position = (0 , position[1] + steps)
                    else:
                        position = (position[0] + steps, position[1])

                elif index == 4 or index == 12:
                    if position[0] == 1320:
                        position = (900 , position[1] + steps)
                    else:
                        position = (position[0] + steps, position[1])


            elif index in rightUp:

                if index == 2 or index == 10:
                    if position[0] == 420:
                        position = (0 , position[1] - steps)
                    else:
                        position = (position[0] + steps, position[1])

                elif index == 6 or index == 14:
                    if position[0] == 1320:
                        position = (900 , position[1] - steps)
                    else:
                        position = (position[0] + steps, position[1])


            elif index in leftDown:

                if index == 1 or index == 9:
                    
                    if position[0] == 450:
                        position = (870 , position[1] + steps)
                    else:
                        position = (position[0] - steps, position[1])

                elif index == 5 or index == 13:

                    if position[0] == 1350:
                        position = (1770 , position[1] + steps)
                    else:
                        position = (position[0] - steps, position[1])

            if index in leftUp:

                if index == 3 or index == 11:
                    
                    if position[0] == 450:
                        position = (870 , position[1] - steps)
                    else:
                        position = (position[0] - steps, position[1])

                elif index == 7 or index == 15:

                    if position[0] == 1350:
                        position = (1770 , position[1] - steps)
                    else:
                        position = (position[0] - steps, position[1])
            
            
            positions[index] = position
            index += 1





pygame.init()
width = 1800
height = 960
steps = 30

#Create a displace surface object
surface = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)

run(True)

while True:
    run(False)

Source: Making Art by Judging Reddit


About The Author

Muhammad Bilal

I am highly skilled and motivated individual with a Master's degree in Computer Science. I have extensive experience in technical writing and a deep understanding of SEO practices.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top