local variable 'counter' referenced before assignment

Question:

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

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]
Asked By: MonsterMMORPG

||

Answers:

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.

Answered By: lmiguelvargasf
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.