Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

local variable 'counter' referenced before assignment

I am running the below code and getting this error.

I am used to c# syntax but this doesn’t make any sense

The rest of the code is working i have tested. Only counter is the problem at the moment

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

import logging
from transformers import pipeline


counter = 1
#summarizer = pipeline("summarization", model="csebuetnlp/mT5_multilingual_XLSum")

f = open("TextFile1.txt", "r")

ARTICLE = f.read()

#print(summarizer(ARTICLE, max_length=900, do_sample=False))

summarizer = pipeline("summarization", model="facebook/bart-large-cnn")

def summarize_text(text: str, max_len: int) -> str:
    try:
        #logging.warning("max_len " + str(max_len))
        summary = summarizer(text, max_length=max_len, min_length=100, do_sample=False)
        with open('parsed_'+str(counter)+'.txt', 'w') as f:
            f.write(text)
        counter += 1
        return summary[0]["summary_text"]
    except IndexError as ex:
        logging.warning("Sequence length too large for model, cutting text in half and calling again")
        return summarize_text(text=text[:(len(text) // 2)], max_len=max_len) +" "+ summarize_text(text=text[(len(text) // 2):], max_len=max_len)

gg = summarize_text(ARTICLE, 1024)

with open('summarized.txt', 'w') as f:
    f.write(gg)

[![enter code here][1]][1]

>Solution :

You are changing counter inside your function summarize_text and this is a global variable. By using global counter, you are stating that counter is a global variable, so when you change it, the interpreter knows you are changing the global variable and not a local variable to the function summarize_text called counter.

...
counter = 1
...

def summarize_text(text: str, max_len: int) -> str:
    global counter
    ...

Btw, It is not a good practice to use global variables because it will make your code very hard to debug.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading