Welcome, guest | Sign In | My Account | Store | Cart

This script uses the csv module to convert gmail.com contacts data to the "raw" gnokii phonbook format, which is another CSV variant, while preserving cell/home/work/fax numbers, street address, URL and notes data entries.

gnokii (www.gnokii.org) is an open source program for communicating with mobile phones that runs under Windows and Linux/Unix. Note that gmail.com supports exporting contacts in both Outlook and Gmail CSV formats. This script needs the Gmail format.

Run this script with a command like: cat gmail.csv | gmail-csv-to-gnokii | gnokii --writephonebook --overwrite

Python, 286 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
import codecs
import csv
import re
import urlparse
import itertools
import cStringIO

GMAIL_CSV_HEADER_FIELDS = (
    'Name',
    'E-mail',
    'Notes',
)
GMAIL_CSV_SECTION_FIELDS = (
    'Description',
    'Email',
    'IM',
    'Phone',
    'Mobile',
    'Pager',
    'Fax',
    'Company',
    'Title',
    'Other',
    'Address',
)

# gnokii raw format constants
# format: ENTRY_NUMBER.NUMBER_x or ENTRY_x.0
# copied from include/gnokii/common.h
GN_NUMBER_HOME    = 0x02
GN_NUMBER_MOBILE  = 0x03
GN_NUMBER_FAX     = 0x04
GN_NUMBER_WORK    = 0x06
GN_NUMBER_GENERAL = 0x0a

GN_ENTRY_NAME       = 0x07
GN_ENTRY_EMAIL      = 0x08
GN_ENTRY_POSTAL     = 0x09
GN_ENTRY_NOTE       = 0x0a
GN_ENTRY_NUMBER     = 0x0b
GN_ENTRY_RINGTONE   = 0x0c
GN_ENTRY_DATE       = 0x13   # Date is used for DC,RC,etc (last calls)
GN_ENTRY_POINTER    = 0x1a   # Pointer to the other memory
GN_ENTRY_LOGO       = 0x1b
GN_ENTRY_LOGOSWITCH = 0x1c
GN_ENTRY_GROUP      = 0x1e
GN_ENTRY_URL        = 0x2c
GN_ENTRY_RINGTONEADV= 0x37

# Mappings from gmail to gnokii in
# ((gmail_section, gmail_field), (gnokii_entry, gnokii_number))
# format.
# None is wildcard. Order matters, list most specific first
FIELD_PAIR = (
    (('Home', 'Phone'),(GN_ENTRY_NUMBER, GN_NUMBER_HOME)),
    ((None, 'Mobile'), (GN_ENTRY_NUMBER, GN_NUMBER_MOBILE)),
    ((None, 'Fax'),    (GN_ENTRY_NUMBER, GN_NUMBER_FAX)),
    (('Work', 'Phone'),(GN_ENTRY_NUMBER, GN_NUMBER_WORK)),
    ((None,   'Phone'),  (GN_ENTRY_NUMBER, GN_NUMBER_GENERAL)),
    ((None, 'Name'),   (GN_ENTRY_NAME, 0)),# special case, is primary key
    ((None, 'E-mail'), (GN_ENTRY_EMAIL, 0)),
    ((None, 'Email'), (GN_ENTRY_EMAIL, 0)),# they should just pick one spelling
    ((None, 'Address'),(GN_ENTRY_POSTAL, 0)),
    ((None, 'Notes'),  (GN_ENTRY_NOTE, 0)),
)

def field_match(section, field):
    '''field_match(None, "Name") -> (GN_ENTRY_NAME, 0)
    returns None when not found'''
    # naive linear scan of patterns
    for ((s, f), (e, n)) in FIELD_PAIR:
        if field == f and (s == None or s == section):
            return (e, n)
    else: # not found
        return None

def field_extract_section(field):
    m = re.compile(r'Section (\d+) -').match(field)
    sec = None
    if m:
        sec = int(m.group(1))
        (i, j) = m.span()
        field = field[j:].strip()
    return (sec, field)

def get_item(l, index):
    try:
        return l[index]
    except IndexError:
        return ''

def is_url(s):
    (s, h) = urlparse.urlparse(s)[:2]
    return s and h

def phone_number_filter(s):
    out = []
    for i in s:
        if i.isdigit():
            out.append(i)
    return ''.join(out)

def isspace_to_space(s):
    out = []
    for i in s:
        if i.isspace():
            out.append(' ')
        else:
            out.append(i)
    return ''.join(out)

def transform(field_to_sec_field, section_description_fields, csv_record):
    def split_value(value):
        for i in value.split(':::'):
            i = i.strip()
            if i:
                yield isspace_to_space(i) # FIXME: hackish
    sec_num_to_section = [ None ] + list( get_item(csv_record,i)
        for i in section_description_fields )
    for (i, v) in enumerate(csv_record):
        if not v:
            continue
        (sec_num, field) = field_to_sec_field[i]
        try:
            section = sec_num_to_section[sec_num]
        except TypeError:
            section = None
        t = field_match(section, field)

        (entry, number) = (None, 0)
        if t:
            (entry, number) = t
        elif field == 'Other':
            for j in split_value(v):
                if is_url(j):
                    yield (GN_ENTRY_URL, 0, j)
                else:
                    yield (GN_ENTRY_NOTE, 0, j)

        if entry:
            for j in split_value(v):
                if entry == GN_ENTRY_NUMBER:
                    yield (entry, number, phone_number_filter(j))
                else:
                    yield (entry, number, j)

def iter_first(iterable):
    try:
        return iter(iterable).next()
    except StopIteration:
        return '' #FIXME: all my data are strings ...

def guess_primary_number(entry_list):
    #FIXME: should find a way to let user specify this in the Gmail CSV format
    'guess_primary_number( [ (e, n, v), ... ] ) -> v'
    l = list(entry_list)
    number_priority = (
        GN_NUMBER_MOBILE,
        GN_NUMBER_HOME,
        GN_NUMBER_WORK,
        GN_NUMBER_GENERAL,
    )
    d = dict( (v,i) for (i,v) in enumerate(number_priority) )
    l.sort(key=lambda (e,n,v): d.get(n, len(d)))
    try:
        return l[0][2]
    except IndexError:
        return ''

def gnokii_raw_gen(entry_list):
    name_entry = iter_first( (e, n, v) for (e, n, v) in entry_list
            if e == GN_ENTRY_NAME)
    if not name_entry:
        return ()
    entry_list.remove(name_entry)
    name = name_entry[2]
    primary_number = guess_primary_number( (e, n, v)
            for (e, n, v) in entry_list if e == GN_ENTRY_NUMBER )
    return (name, primary_number, entry_list)

def gnokii_write_phone_book(fout, phone_book):
    cl = csv.writer(fout, delimiter=';', lineterminator='\n')
    for (person_counter,(name, primary_number, entry_list)) in enumerate(phone_book):
        h =  [ name,
                primary_number,
                'ME', #mem_type, (ME: phone, SM: SIM card)
                person_counter+1, #mem_index, counts from 1
                5, #call_group, (5: not in any group)
            ]
        entries = []
        for (i, (e, n, v)) in enumerate(entry_list):
            entries.extend([e, n,
                    i+2, # entry counter, got the 2 starting value by experiment
                    v])
        cl.writerow(h + entries)

class UTF8Lines(object):
    '''Work around UnicodeEncodingError when using unicode with the csv module,
    just encode the data to utf-8.'''
    def __init__(self, fin):
        self.fin = fin
    def next(self):
        l = self.fin.readline()
        if l:
            return l.encode('utf-8')
        else:
            raise StopIteration
    def __iter__(self):
        return self

def gmail_csv_unicode_open(fin):
    'only supports utf-16 and utf-8'
    # byte order mark
    t = fin.read(2)
    if t == codecs.BOM_UTF16_LE:
        return UTF8Lines(codecs.getreader('utf-16le')(fin))
    elif t == codecs.BOM_UTF16_BE:
        return UTF8Lines(codecs.getreader('utf-16be')(fin))
    else: # assume utf-8
        l = fin.readline()
        return itertools.chain([ t + l ], fin)

def gmail_csv_to_gnokii(fin, fout):
    data = csv.reader(gmail_csv_unicode_open(fin))
    it = iter(data)
    fields = it.next() # first line is field names

    (field_to_sec_field, sec_description_fields) = ([], [])
    for (i, f) in enumerate(fields):
        (sec_num, f) = field_extract_section(f)
        field_to_sec_field.append((sec_num, f))
        if f == 'Description':
            sec_description_fields.append(i)
    phone_book = list( list(transform(field_to_sec_field, sec_description_fields, x))
            for x in it )
    phone_book.sort()

    gnokii_raw_data = filter(None, (gnokii_raw_gen(list(x)) for x in phone_book) )
    gnokii_write_phone_book(fout,  gnokii_raw_data)

GMAIL_CSV_EXAMPLE = (
','.join([ 'Name', 'E-mail', 'Notes', 'Section 1 - Description',
    'Section 1 - Email', 'Section 1 - IM', 'Section 1 - Phone',
    'Section 1 - Mobile', 'Section 1 - Pager', 'Section 1 - Fax',
    'Section 1 - Company', 'Section 1 - Title', 'Section 1 - Other',
    'Section 1 - Address', 'Section 2 - Description', 'Section 2 - Email',
    'Section 2 - IM', 'Section 2 - Phone', 'Section 2 - Mobile',
    'Section 2 - Pager', 'Section 2 - Fax', 'Section 2 - Company',
    'Section 2 - Title', 'Section 2 - Other', 'Section 2 - Address\n',
]) + ','.join([
    'Scott Tsai', 'scottt.tw@nospam', 'Scott Tsai', 'Personal',
    'email1@nospam ::: mail2@nospam', '', '', '123456789', '', '', '', '', '', '',
    '\n'
]))
GNOKII_EXAMPLE = ';'.join(
['Scott Tsai', '123456789', 'ME', '1', '5', '8', '0', '2', 'scottt.tw@nospam',
 '10', '0', '3', 'Scott Tsai', '8', '0', '4', 'email1@nospam', '8', '0', '5',
 'mail2@nospam', '11', '3', '6', '123456789\n'])
def test():
    assert field_match(None, 'Name') == (GN_ENTRY_NAME, 0)
    s = 'Phone'
    assert field_match('Work', s) == (GN_ENTRY_NUMBER, GN_NUMBER_WORK)
    assert field_match('Home', s) == (GN_ENTRY_NUMBER, GN_NUMBER_HOME)
    assert field_match('Other', s) == (GN_ENTRY_NUMBER, GN_NUMBER_GENERAL)

    out = cStringIO.StringIO()
    gmail_csv_to_gnokii(cStringIO.StringIO(GMAIL_CSV_EXAMPLE), out)
    out.seek(0)
    assert out.read() == GNOKII_EXAMPLE

def main(args):
    if not args:
        gmail_csv_to_gnokii(sys.stdin, sys.stdout)
    else:
        for i in args:
            (fin, fout) = (file(i, 'ra'),
                    file(os.path.splitext(i)[0]+'.gnokii_raw', 'wa'))
            gmail_csv_to_gnokii(fin, fout)

if __name__ == '__main__':
    main(sys.argv[1:])

Gmail allows users to add more than one Personal/Work or custom named sections, so I end up doing a field_match on every field in the CSV file instead of just the table headers. The data structures used and the names I came up for them can certainly use some improvement.

3 comments

Scott Tsai (author) 18 years, 2 months ago  # | flag

slight revision. Added the guess_primary_number() function that uses a fixed priority. Added example data for unit testing.

Scott Tsai (author) 17 years, 11 months ago  # | flag

support utf-16 encoded gmail.csv. Just found out gmail.com started exporting utf-16 encoded contacts. Had to feed utf-8 encoded strings instead of unicode to csv.reader to make it happy.

Scott Tsai (author) 16 years, 10 months ago  # | flag

ignore empty input lines.