Help needed for uploading text file from anvil to jupyter notebook

I want to able the user to upload text file using the ‘upload’. Then, the text file will be sent to my jupyter to do preprocessing and then return it back to anvil interface the output.

Here is my code in jupyter notebook:
import anvil.media

@anvil.server.callable
def sentence_tokenization(file):
#with open(file) as f:
#txt = f.read()
  with anvil.media.TempFile(file) as f:
    txt = f.read()
  from nltk.tokenize import sent_tokenize
  sentence_tokens = sent_tokenize(txt)
  return (sentence_tokens)

and here is my code in anvil:

def file_loader_1_change(self, file, **event_args):
  '''This method is called when a new file is loaded into this FileLoader'''
  result = anvil.server.call(‘sentence_tokenization’, file)

  self.text_area_4.text = result

but i am getting this error after I upload the text file:

AttributeError: ‘str’ object has no attribute ‘read’ at , line 9 called from [Form1, line 25](javascript:void(0))

This is my first time with anvil. It will help me a lot if anyone can help/guide me with this.
Thank you :slight_smile: :smile:

2 Likes

In your context manager with statement f is not the file but the filename. ie it’s a str and so has no attribute read.

You can check by doing print(type(f), f)

I believe you’ll have to call open in order to read it’s contents.

Linked docs https://anvil.works/docs/media