Skip to content

Non-ASCII non-UTF-8 characters in GenBank files break on Python 3 #1361

Closed

Description

@hmkim

Setup

I am reporting a problem with Biopython version, Python version, and operating
system as follows:

import sys; print(sys.version)
import platform; print platform.python_implementation(); print(platform.platform())
import Bio; print(Bio.__version__)

import sys; print(sys.version)
3.6.1 |Continuum Analytics, Inc.| (default, May 11 2017, 13:04:09)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
import platform; print platform.python_implementation(); print(platform.platform())
import Bio; print(Bio.version)>>> import platform; print platform.python_implementation(); print(platform.platform())
File "", line 1
import platform; print platform.python_implementation(); print(platform.platform())
^
import Bio; print(Bio.version)SyntaxError: invalid syntax
import Bio; print(Bio.version)
1.69

Expected behaviour

print ("Converted 1674 records")
with no Error

Actual behaviour

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    count = SeqIO.convert("data/SB1200000043.gb", "genbank", "test.fasta", "fasta")
  File "/Users/brandon/miniconda3/lib/python3.6/site-packages/Bio/SeqIO/__init__.py", line 1019, in convert
    alphabet)
  File "/Users/brandon/miniconda3/lib/python3.6/site-packages/Bio/SeqIO/_convert.py", line 372, in _handle_convert
    return f(in_handle, out_handle, alphabet)
  File "/Users/brandon/miniconda3/lib/python3.6/site-packages/Bio/SeqIO/_convert.py", line 38, in _genbank_convert_fasta
    return SeqIO.write(records, out_handle, "fasta")
  File "/Users/brandon/miniconda3/lib/python3.6/site-packages/Bio/SeqIO/__init__.py", line 490, in write
    count = writer_class(fp).write_file(sequences)
  File "/Users/brandon/miniconda3/lib/python3.6/site-packages/Bio/SeqIO/Interfaces.py", line 208, in write_file
    count = self.write_records(records)
  File "/Users/brandon/miniconda3/lib/python3.6/site-packages/Bio/SeqIO/Interfaces.py", line 192, in write_records
    for record in records:
  File "/Users/brandon/miniconda3/lib/python3.6/site-packages/Bio/GenBank/Scanner.py", line 480, in parse_records
    record = self.parse(handle, do_features)
  File "/Users/brandon/miniconda3/lib/python3.6/site-packages/Bio/GenBank/Scanner.py", line 464, in parse
    if self.feed(handle, consumer, do_features):
  File "/Users/brandon/miniconda3/lib/python3.6/site-packages/Bio/GenBank/Scanner.py", line 438, in feed
    self.parse_features(skip=True)  # ignore the data
  File "/Users/brandon/miniconda3/lib/python3.6/site-packages/Bio/GenBank/Scanner.py", line 187, in parse_features
    line = self.handle.readline()
  File "/Users/brandon/miniconda3/lib/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xae in position 7634: invalid start byte

Steps to reproduce

$ python2 test.py OK

$ python3 test.py ERROR

I think below code is not compatible with my python3 on this genbank file.

Test CODE:

from Bio import SeqIO
gb_file = 'data/SB1200000043.gb'
from Bio import SeqIO
count = SeqIO.convert("data/SB1200000043.gb", "genbank", "test.fasta", "fasta")

genbank file is
https://www.dropbox.com/s/lwwbdyijhyyrjkz/SB1200000043.gb?dl=0

Activity

  1. peterjc commented on Aug 10, 2017

    @peterjc
    Member

    It seems our suggested Python commands to report the Python version and platform failed somehow, but it looks like Biopython 1.69 under Python 3.6 via miniconda under Mac OS X?

    (Update: That's been fixed in f0a8d67)

    Note we've fixed several encoding specific bugs since Biopython 1.70 was released in XML files.

    Thank you for the test case, I can reproduce this with the latest Biopython code:

    $ more test.py
    from Bio import SeqIO
    gb_file = 'SB1200000043.gb'
    count = SeqIO.convert("SB1200000043.gb", "genbank", "test.fasta", "fasta")
    print("Converted %i records" % count)
    
    $ python test.py 
    Converted 1674 records
    
    $ python3 test.py 
    Traceback (most recent call last):
      File "test.py", line 3, in <module>
        count = SeqIO.convert("SB1200000043.gb", "genbank", "test.fasta", "fasta")
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Bio/SeqIO/__init__.py", line 1026, in convert
        alphabet)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Bio/SeqIO/_convert.py", line 372, in _handle_convert
        return f(in_handle, out_handle, alphabet)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Bio/SeqIO/_convert.py", line 38, in _genbank_convert_fasta
        return SeqIO.write(records, out_handle, "fasta")
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Bio/SeqIO/__init__.py", line 491, in write
        count = writer_class(fp).write_file(sequences)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Bio/SeqIO/Interfaces.py", line 214, in write_file
        count = self.write_records(records)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Bio/SeqIO/Interfaces.py", line 198, in write_records
        for record in records:
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Bio/GenBank/Scanner.py", line 489, in parse_records
        record = self.parse(handle, do_features)
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Bio/GenBank/Scanner.py", line 473, in parse
        if self.feed(handle, consumer, do_features):
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Bio/GenBank/Scanner.py", line 447, in feed
        self.parse_features(skip=True)  # ignore the data
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Bio/GenBank/Scanner.py", line 191, in parse_features
        line = self.handle.readline()
      File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/codecs.py", line 321, in decode
        (result, consumed) = self._buffer_decode(data, self.errors, final)
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xae in position 7634: invalid start byte
    
  2. peterjc commented on Aug 10, 2017

    @peterjc
    Member

    I think these are the problem lines:

    $ grep "MegAlign" SB1200000043.gb 
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
                Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
    

    Those "question marks" after Lasergene seem to be 0xAE, or in decimal character 174:

    $ grep "MegAlign" SB1200000043.gb | hexdump -C
    00000000  20 20 20 20 20 20 20 20  20 20 20 20 41 73 73 65  |            Asse|
    00000010  6d 62 6c 79 20 4d 65 74  68 6f 64 20 20 20 20 20  |mbly Method     |
    00000020  20 20 3a 3a 20 43 6c 75  73 74 61 6c 57 2c 20 4d  |  :: ClustalW, M|
    00000030  65 67 41 6c 69 67 6e 20  28 4c 61 73 65 72 67 65  |egAlign (Laserge|
    00000040  6e 65 ae 2c 20 44 4e 41  53 54 41 52 2c 0a 20 20  |ne., DNASTAR,.  |
    ...
    

    On my computer in emacs they show up as R in a circle (®) which is a symbol for registered trade mark https://en.wikipedia.org/wiki/Registered_trademark_symbol

    $ python3 -c "print('®'.encode('utf-8'))"
    b'\xc2\xae'
    

    Where did you get this GenBank format file from? The NCBI directly? If so was it via FTP, Entrez, ... and can you share the original URL?

  3. peterjc commented on Aug 10, 2017

    @peterjc
    Member

    According to https://www.compart.com/en/unicode/U+00AE and https://www.compart.com/en/unicode/charsets/containing/U+00AE under UTF-8 the registered trademark should be two bytes (0xC2 0xAE), but the single byte encoding 0xAE (as used in your file) did get used in some legacy encodings. Explicitly using one of those encodings might be a workaround for Python 3 without changing Biopython.

    We need to find out if the NCBI has an explicit policy on the encoding used in GenBank files...

  4. peterjc commented on Aug 10, 2017

    @peterjc
    Member

    Quoting ftp://ftp.ncbi.nlm.nih.gov/genbank/gbrel.txt

    2.1 Overview

    GenBank releases consist of a set of ASCII text files, most of which
    contain sequence data. A few supplemental files are also supplied,
    containing lists of new, modified, and deleted sequence records.
    The line-lengths of these files is variable.

    Spotted by @idoerg - thanks.

    This is not quite as strong as saying all GenBank format files should be ASCII only, but it strongly suggests your files are invalid due to the non-ASCII registered trade mark symbol in some of the COMMENT entries. If the files are from the NCBI, we ought to contact them for clarification.

  5. peterjc commented on Aug 11, 2017

    @peterjc
    Member

    I've checked an example directly from the NCBI website, https://www.ncbi.nlm.nih.gov/nuccore/KU996377

    As per this screenshot, the problem character in the comment is shown there as a question-mark-in-black-diamond:

    screenshot 2017-08-11 09 50 36

    I will email the NCBI about this.

  6. changed the title [-]UnicodeDecodeError: 'utf-8' codec can't decode byte 0xae in position 7634: invalid start byte[/-] [+]Non-ASCII non-UTF-8 characters in GenBank files break on Python 3[/+] on Aug 11, 2017
  7. peterjc commented on Aug 14, 2017

    @peterjc
    Member

    This identifies all the accessions in the shared GenBank file with a unicode problem:

    $ python3
    Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13) 
    [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> filename = "SB1200000043.gb"
    >>> from Bio import SeqIO
    >>> d = SeqIO.index(filename, "gb")
    >>> bad = []
    >>> for id in d:
    ...     try:
    ...         r = d[id]
    ...     except UnicodeDecodeError:
    ...         bad.append(id)
    ... 
    >>> bad = sorted(bad)
    >>> len(d)
    1674
    >>> len(bad)
    19
    >>> bad
    ['KU996361.1', 'KU996362.1', 'KU996363.1', 'KU996364.1', 'KU996365.1', 'KU996366.1', 'KU996367.1', 'KU996368.1', 'KU996369.1', 'KU996374.1', 'KU996375.1', 'KU996376.1', 'KU996377.1', 'KU996378.1', 'KU996379.1', 'KU996380.1', 'KU996381.1', 'KU996388.1', 'KU996389.1']
    

    [Update: Example now sorts and reports as a list along with counts, 19 out of 1674 are problematic]

  8. peterjc commented on Aug 16, 2017

    @peterjc
    Member

    It sounds like the NCBI will curate these records to remove the problem character.

    To do that yourself, the following command will remove these characters under Mac OS X or Linux. This works because the problem character is 0xAE in hex, 174 in decimal, and thus 256 in octal.

    $ LC_CTYPE=C tr -d '\256' < SB1200000043.gb > SB1200000043_clean.gb
    

    Note this deliberately temporarily changes the locale settings, it wasn't essential on the Linux machine I tested, but it was on my Mac where the default is UTF-8:

    $ tr -d '\256' < SB1200000043.gb > SB1200000043_clean.gb
    tr: Illegal byte sequence
    

    This should confirm the problem characters have been removed:

    $ diff SB1200000043.gb SB1200000043_clean.gb 
    96398c96398
    <             Assembly Method       :: ClustalW, MegAlign (Lasergene?, DNASTAR,
    ---
    >             Assembly Method       :: ClustalW, MegAlign (Lasergene, DNASTAR,
    ...
    
  9. hmkim commented on Aug 17, 2017

    @hmkim
    Author

    Thank you so much.
    For your close investigation of this.

  10. peterjc commented on Aug 17, 2017

    @peterjc
    Member

    Thanks for raising the issue - the NCBI should be fixing those 19 records, and it has given us a better awareness of some of the encoding things to watch out for in future.

  11. wiebepo commented on Feb 16, 2022

    @wiebepo

    For anyone else who might come across this post while searching for a solution. I encountered this issue recently. In my case, I was using compressed Genbank files. In Python 3.8, I used gzip module to avoid encountering the error by ignoring any bytes that did not conform to utf-8.
    for r in SeqIO.parse(gzip.open(file, 'rt', encoding='utf8', errors='ignore'), "genbank"):

  12. bucongfan commented on Mar 27, 2023

    @bucongfan

    For anyone else who might come across this post while searching for a solution. I encountered this issue recently. In my case, I was using compressed Genbank files. In Python 3.8, I used gzip module to avoid encountering the error by ignoring any bytes that did not conform to utf-8. for r in SeqIO.parse(gzip.open(file, 'rt', encoding='utf8', errors='ignore'), "genbank"):

    Please let more people see this reply

  13. hagen-wende commented on Aug 2, 2024

    @hagen-wende

    I also ran into a similar issue. I got this error:
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1960: ordinal not in range(128)
    I tried to resolve it by detecting the encoding and converting to utf-8, which unfortunately did not solve the issue. I also checked that there where no non-utf-8 characters in the file. but as it was stating ASCII I then checked for non-ascii characters and found some, removing those solved the issue. This was a user Vector NTI file that hat "5´" instead of "5'" in one of the features.

    I solved the issue by parsing the file and removing all non-ASCII characters.

    import chardet
    
    # check encoding and save as utf-8, remove any non-ASCII characters
                        with open(gb_file_path, 'rb') as f:
                            result = chardet.detect(f.read())
                            encoding = result['encoding']
    
                        with open(gb_file_path, 'r', encoding=encoding) as f:
                            gb_content = f.read()
    
                        # Create a new content string without non-ASCII characters
                        filtered_gb_content = ''.join(char for char in gb_content if ord(char) <= 127)
    
    
                        with open(gb_file_path, 'w', encoding="utf-8") as f:
                            f.write(filtered_gb_content)
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions