You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

26 KiB

... and I whish that your question has been answered

this tool includes two functions that intervene on text by replacing specific targeted words with either other words or single characters. The 2 main functions are based in a very simple mechanism, but the scope and results one could get by using them in different ways and with different intentions can be very compelling. One could break down the meaning of a text, by exposing its structure, taking out specific and meaningful words and detaching such text from its original context. If then, these words would be substituted for others, the text can be given a new meaning, reclaiming concepts or ideas. The words could be also erased and replaced for blank spaces in order to create a new narrative meaning with what is left on the page, as well as to create abstract compositions. This tool offers a broad spectrum of possibilities in which it can be used, from a very political and subversive use, to a more playful and artistic (or poetic) one.

import

In [2]:
from flask import Flask, request, json, render_template, url_for, redirect
from jinja2 import Environment, PackageLoader, select_autoescape
from weasyprint import HTML, CSS
from nltk.tokenize import word_tokenize


import os 
import json

for the receipt printer:

In [3]:
from escpos.printer import Network

functions

In [4]:
# function: respell
# '''replace all the occurrences of a targeted word in a given text'''
# def swap(text, target, replacement):
#     result = text.replace(target, replacement)
#     return result

def swap(text, target, replacement):
    target = target.lower()
    txt = word_tokenize(text)
    new = []
    
#     print(f"swap target:'{target}'")
    for w in txt:
        if w == target:
            w = replacement
            new = new + [w]
        elif w == target[0:1].upper() + target[1:]:
            w = replacement[0:1].upper() + replacement[1:] 
            new = new + [w]
        elif w == target.upper():
            w = replacement.upper()
            new = new + [w]
        else:
            new = new + [w]
    text = ' '.join(new)
    final= text.replace(' .','.').replace(' ,',',').replace(' :',':').replace(' ;',';').replace('< ','<').replace(' >','>').replace(' / ','/').replace('& ','&')
    return final

# function: stitch
# '''replace all the occurrences of a target word with a single character that is repeated as many times as the length of the target'''
## example: stitch('halo stitch this', 'this', '*') ----> result:'halo stitch ****'
def mend(text, target, replacement):
    target = target.lower()
    txt = word_tokenize(text)
    new = []
    
    for w in txt:
        if w == target:
            w = len(w)*replacement
            new = new + [w]
        elif w == target[0].upper() + target[1:]:
            w = len(w)*replacement
            new = new + [w]
        elif w== target.upper():
            w = len(w)*replacement 
            new = new + [w]
        else:
            new = new + [w]
    text = ' '.join(new)
    final= text.replace(' .','.').replace(' ,',',').replace(' :',':').replace(' ;',';').replace('< ','<').replace(' >','>').replace(' / ','/').replace('& ','&')
    return final


# reveal 
def underline(text,Group):
    txt = word_tokenize(text)
    
    txt_linebr = []
    for token in txt:
        if token == '<':
            continue
        elif token == 'br/':
            token='<br/>'
            txt_linebr.append(token)
        elif token == '>':
            continue
        else:
            txt_linebr.append(token)    
    new = []
    group = Group.split(",")
    for w in txt_linebr:
        if w=='<br/>':
            new = new + [w]
        elif w not in group:
            w = len(w) * ' '
            new = new + [w]
        elif w in group :
            new = new + [w]
    text = ' '.join(new)
    final= text.replace(' .','.').replace(' ,',',').replace(' :',':').replace(' ;',';').replace('< ','<').replace(' >','>').replace(' / ','/').replace('& ','&')
    return final

#function: txt_br
#to read the line breaks in a .txt file, returns string readable in html 
def txt_br(any_text):
    lines= any_text.readlines()
    replaced = ''
    for line in lines:
        replaced+= line.replace('\n', ' <br/> ')   
    return replaced

flask

!pwd todo: adjust the width of the text on the right

In [ ]:
app = Flask(__name__)



# @app.route(f"/~grgr/api/")
# def replace():
    
#     text=request.values.get('text', '')
#     target = request.values.get('target', '')
#     replacement = request.values.get('replacement', '')
#     title = f"<h2>{request.values.get('title', '')}</h2>"
#     txt_result = f"<p>{swap(text, target, replacement)}</p>"
#     contents= title + txt_result
    
#     with open("./assets/outputs/db.txt", "a") as db:
#         db.write(contents+ " \n")
        
#     with open ("archive_section.html", "a") as output:
#         print(contents, file=output)
    
#     return render_template("index.html",
#                           text=text,
#                           contents=contents)


  

# archive page
@app.route(f"/~grgr/api/archive/", methods=['GET'])
def archive():
    with open("./assets/question.txt", 'r') as q_file:
        question = txt_br(q_file)
    #read the json file
    with open("archive.json", "r") as file:
            archive_input = json.loads(file.read())
            archive = archive_input['archive']
            answers=[]
#           # create a list with all the sections contents from the json
            for section in archive:
                answers.append(section['answers']) 
        
    return render_template("archive.html",
                           answers = answers,
                          question=question)



# main page with the form:
temp_changes=[]

@app.route("/~grgr/api/and_i_wish_that_your_question_has_been_answered/", methods=['GET', 'POST'])
def interact():
    target = request.values.get('target', '')
    f_replacement = request.values.get('f_replacement','')
    function = request.values.get('function', 'replace') 
    text = request.values.get('text','')
    result = ''
    
    with open("./assets/question.txt", 'r') as q_file:
        question = txt_br(q_file)
    
    with open("./assets/mitsotakis.txt", 'r') as file:
        source = txt_br(file)
   
    if request.method == 'POST':  
            if function == 'mend': 
                stitch = f_replacement
                if ' ' in stitch:
                    space = stitch.replace(' ','&nbsp; ')
                    result= mend(text, target, space)
                else:
                    result= mend(text, target, stitch)
            elif function == 'underline':
                popup =underline(source, target)
                result= popup.replace(' ','&nbsp; ')
            else:
                replacement = f_replacement
                result = swap(text, target, replacement)
                print('target is:'+ target)
            # now save temporary all the changes in the list changes
            temp_changes.append(result)

    if not text:
        # the first time we open the url the text is not saved, so plz flask, use the original source as text!
        if function == 'mend':
            result = mend(source, target, f_replacement)
        elif function== 'underline':
            popup = underline(source, target)
            result= popup.replace(' ','&nbsp; ')
            
        else:
            result = swap(source, target, f_replacement)
            
    print('result is:'+result)

    return render_template('postform.html', question=question, text=text, result=result, source= source, function=function, f_replacement=f_replacement)



#save the changes to the archive
@app.route("/~grgr/api/save/", methods=['GET', 'POST'])
def save_to_archive():
    if request.method == 'POST':
        
        with open("./assets/question.txt", 'r') as q_file:
            question = txt_br(q_file)
        
        with open("archive.json", "r") as file:
            archive_input = json.loads(file.read())
            archive = archive_input['archive']
            i = len(temp_changes)-1
            while i >= 0:
                last_change = temp_changes[i]
                if last_change:
                    last_change= temp_changes[i]
                    
                    section = {"question":question, 
                       "answers": last_change}
                    archive.append(section)
                    print('saved')
                    break
                else:
                    i = i-1  
            
        #print to the archive    
        with open("archive.json", "w") as file:
            file.write(json.dumps({"archive":archive}))
            
        #print with the line printer 
#         with open('/dev/usb/lp0', 'w') as lp:
#             print(last_change, file=lp) 
#             print_last = last_change.replace('&nbsp; ',' ').replace('<br/>', '\n')
#             print(f'last print is:{print_last}')
        
        #for ethernet receipt printer
#         kitchen = Network("192.168.1.140") #Printer IP Address
#         kitchen.text(print_last) 
        
#         temp_changes.clear()iii
             
    return redirect("https://hub.xpub.nl/soupboat/~grgr/api/and_i_wish_that_your_question_has_been_answered/")

app.run(port=9087)
 * Serving Flask app '__main__' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:9087/ (Press CTRL+C to quit)
127.0.0.1 - - [17/Dec/2021 11:43:28] "GET /~grgr/api/and_i_wish_that_your_question_has_been_answered/ HTTP/1.0" 200 -
result is:KYRIAKOS MITSOTAKIS, GREEK PRIME MINISTER <br/> <br/> I understand that in the Netherlands you have a culture of asking direct questions to politicians, which I very much respect. <br/> What I will not accept is that, in this office, you will insult me, or the Greek people, with accusations and expressions that are not supported by material facts when this country has been dealing with a migration crisis of unprecedented intensity, has been saving hundreds, if not thousands of people at sea. <br/> We just rescued 250 people in danger of drowning south of Crete, we are doing this every single day rescuing people at sea, while, at the same time, we are intercepting boats that come from Turkey, as we have the right to do in accordance with European regulations and waiting for the Turkish Coast Guard to come and pick them up and return them to Turkey. <br/> So, rather than putting the blame on Greece, you should put the blame on those who have been instrumentalizing migration systematically pushing people in to a desperate situation from a safe country, because I need to remind you that people who are in Turkey are not in danger, their life is not in danger and you should put the blame on others and not us. <br/> We have a tough, but fair, policy on migration, we have processed and given the right to protection in Greece to 50,000 people, including tens of thousands of Afghans, in accordance… <br/> Allow me. Have you visited the new camps on our islands ? Have you been to Samos ? … No listen to me, you have not been to Samos… No you have not been… <br/> Please…Look, you will not come into this building and insult me. <br/> Am I very clear on this ? <br/> I am answering now and you will not interrupt me, in the same way that I listened to you very carefully. <br/> If you go to Samos, you will find an impeccable camp, with impeccable conditions, funded by EU money, with clean facilities, with playgrounds for…the children to play, no comparison to what we had in the past. <br/> This is our policy, we will stand by it, and I will not accept anyone pointing the finger to this government and accusing it of inhumane behavior. <br/> <br/> <br/> <br/> MARK RUTTE, DUTCH PRIME MINISTER <br/> <br/> I am absolutely convinced that this prime minister and this government is applying the highest standards and the fact that they have immediately launched an investigation on the issue of the pushbacks is testimony of that. <br/> I will now go back on the situation of 2015 and 2016 when we had many people dying on the Aegean Sea trying to get from Turkey into Greece and then to Germany, Sweeden, the Netherlands etc. And I am happy that Germany and we -were holding at that time the rotating presidency of the EU- were able to negotiate the EU and Turkey agreement. <br/> By which indeed Turkey is a safe country for people to stay. <br/> And Turkey at this moment is hosting over 3 million Syrian refugees in the South of Turkey in camps but also in the local communities. <br/> What this country is trying to do is to defend the outer borders of the European Union. <br/> It is a lot of tasks that countries have who are lying on the outside like Italy, Spain, Hungary, Slovenia, but also Poland and Greece, and there is an extremely difficult situation. <br/> What I don  t want again is for people to take boats that are not fully equipped to pass the Mediterranean or to pass the Aegean Sea, to die in those circumstances. <br/> I want them to stay there, to be safe, and then we are willing as European Union to take a fair share of people from Africa, from Turkey  refugees, in line with the plans devised in 2015 and 2016. <br/> So this is my answer and I wish that your question has been answered.
127.0.0.1 - - [17/Dec/2021 11:43:31] "GET /~grgr/api/archive/ HTTP/1.0" 200 -
In [48]:
temp= ['']
print(len(temp))
1

teeeeeesstttssssss

In [ ]:
 
In [5]:
from weasyprint import HTML, CSS

# with is nice cause it auto-closes the file once "outside" the with block
with open ("test.html", "a") as output:
    print ("<pre>", file=output)
    print (sent + " ", file=output)
    print ("</pre>", file=output)
HTML(filename="test.html").write_pdf('./test.pdf')
In [106]:
def ifcap(text, target, replacement):
    result=[]
    index= 0
    for w in text.split():
        w_lower = w.lower()
        if w_lower == target and w.isupper()==true:
            while w[index].isupper() == true and index<len(w):
                change=''
                for l in replacement:
                    change= l.upper()
                index +=1
            result += [w_lower.replace(target, replacement)]
    print(result)
In [128]:
def ifcap(text, target, replacement):
    result=[]
    index= 0
    for w in text.split():
        w_lower = w.lower()
        change=''
        if w_lower == target:
            
            while index < len(w):
                print('oo')
#                 if str(w[index]).isupper() == true:
#                     change+= str(replacement[index]).upper()
#                     print (change)
#                 else:
#                     change+= replacement[index]
                index+=1
        result += [w_lower.replace(target, change)]
    print(result)
In [129]:
ifcap('Capital and capital', 'c', 'CC')
['apital', 'and', 'apital']
In [130]:
word ='ciao'
print(len(word))
4
- img - multiple targets
In [13]:
with open("./assets/mitsotakis.txt", 'r') as source:
    print(source)
<_io.TextIOWrapper name='./assets/mitsotakis.txt' mode='r' encoding='UTF-8'>
In [ ]:
 
In [44]:
sentence= "stitches //Have something <\repairing\ have HAVE"
In [17]:
# stitch function, replace a target with stitches

def change(text, target, replacement):
    result = text.replace(target, replacement)
    return result
In [30]:
#updated swap function!
from nltk.tokenize import word_tokenize

def stitch(text, target, replacement):
    target = target.lower()
    txt = word_tokenize(text)
    new = []
    
    for w in txt:
        if w == target:
            w = len(w)*replacement
            new = new + [w]
        elif w == target[0].upper() + target[1:]:
            w = len(w)*replacement
            new = new + [w]
        elif w== target.upper():
            w = len(w)*replacement 
            new = new + [w]
        else:
            new = new + [w]
    text = ' '.join(new)
    return text
In [ ]:
 
In [54]:
mend(sentence, 'have', ' ')
Out[54]:
'stitches //Have something <epairing\\          '
In [ ]:

In [ ]:
 
In [15]:
source = 'ciao come va'
In [16]:
print(source.index('ciao'))
0
In [ ]:
 
In [ ]: