Source code

Download source archive ↓

upstream-extended/community/tools/biopython/converters/gff_to_gb_or_embl.py

1#!/usr/bin/env python
2"""
3    Convert a GFF and the associated sequence (FASTA) into GenBank, embl or FASTA format.
4
5    https://raw.github.com/chapmanb/bcbb/master/gff/Scripts/gff/gff_to_genbank.py
6
7    Usage:
8    gff_to_gb_or_embl.py <GFF annotation file> <FASTA sequence file> <Output file> <Output format genbank or embl>
9"""
10import argparse
11
12from BCBio import GFF
13from Bio import SeqIO
14from Bio.Alphabet import generic_dna
15from utils import check_gff, fix_ncbi_id
16
17
18def main(gff_file, fasta_file, outfile, oformat):
19
20    fasta_input = SeqIO.to_dict(SeqIO.parse(fasta_file, "fasta", generic_dna))
21    gff_iter = GFF.parse(gff_file, fasta_input)
22    gff_iter = add_translation(gff_iter)
23    if oformat in ["genbank", "gb"]:
24        SeqIO.write(check_gff(fix_ncbi_id(gff_iter)), outfile, oformat)
25    else:
26        SeqIO.write(check_gff(gff_iter), outfile, oformat)
27
28
29def add_translation(recs):
30    """"""
31    for rec in recs:
32        for f in rec.features:
33            f.qualifiers.update({"translation": f.extract(rec.seq).translate(table=4)})
34        yield rec
35
36
37if __name__ == "__main__":
38    parser = argparse.ArgumentParser(prog="GFF to GenBank converter.")
39    parser.add_argument("--version", action="version", version="%(prog)s 0.1")
40    parser.add_argument("--fasta", "-f", dest="fasta", help="FASTA sequence file")
41    parser.add_argument("--gff", "-g", dest="gff", help="GFF file")
42    parser.add_argument(
43        "--oformat",
44        "-k",
45        dest="oformat",
46        help="output format, embl or genbank",
47        choices=["embl", "genbank"],
48    )
49
50    parser.add_argument("--outfile", "-o", dest="outfile", help="output file")
51    options = parser.parse_args()
52    main(options.gff, options.fasta, options.outfile, options.oformat)