-
Notifications
You must be signed in to change notification settings - Fork 4
/
GeneanetForGramps.py
executable file
·2056 lines (1859 loc) · 78.6 KB
/
GeneanetForGramps.py
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
#
# GeneanetForGramps
#
# Copyright (C) 2020 Bruno Cornec
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the Affero GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# $Id: $
"""
Geneanet Import Tool
Import into Gramps persons from Geneanet
"""
#-------------------------------------------------------------------------
#
# Used Python Modules
#
#-------------------------------------------------------------------------
import os
import time
import io
import sys
import re
import random
from lxml import html, etree
import argparse
from datetime import datetime
import uuid
#------------------------------------------------------------------------
#
# GTK modules
#
#------------------------------------------------------------------------
from gi.repository import Gtk
from gi.repository import GObject
from gramps.gen.const import GRAMPS_LOCALE as glocale
try:
_trans = glocale.get_addon_translator(__file__)
except ValueError:
_trans = glocale.translation
_ = _trans.gettext
#------------------------------------------------------------------------
#
# Gramps modules
#
#------------------------------------------------------------------------
import logging
from gramps.gen.config import config
from gramps.gen.db import DbTxn
from gramps.gen.dbstate import DbState
from gramps.cli.grampscli import CLIManager
from gramps.gen.lib import Person, Name, Surname, NameType, Event, EventType, \
Date, Place, EventRoleType, EventRef, PlaceName, Family, ChildRef, FamilyRelType, \
Tag, Url, UrlType
# Gramps GUI
from gramps.gen.const import URL_MANUAL_PAGE
from gramps.gen.display.name import displayer as name_displayer
from gramps.gui.managedwindow import ManagedWindow
from gramps.gui.display import display_help
from gramps.gui.plug import MenuToolOptions, PluginWindows
from gramps.gen.plug.menu import StringOption, PersonOption, BooleanOption, NumberOption, FilterOption, MediaOption
from gramps.gui.utils import ProgressMeter
LOG = logging.getLogger("GeneanetForGramps")
handler = logging.FileHandler('info.log')
LOG.addHandler(handler)
TIMEOUT = 5
# TODO: Is it useful ?
LANGUAGES = {
'cs' : 'Czech', 'da' : 'Danish','nl' : 'Dutch',
'en' : 'English','eo' : 'Esperanto', 'fi' : 'Finnish',
'fr' : 'French', 'de' : 'German', 'hu' : 'Hungarian',
'it' : 'Italian', 'lt' : 'Latvian', 'lv' : 'Lithuanian',
'no' : 'Norwegian', 'po' : 'Polish', 'pt' : 'Portuguese',
'ro' : 'Romanian', 'sk' : 'Slovak', 'es' : 'Spanish',
'sv' : 'Swedish', 'ru' : 'Russian',
}
WIKI_HELP_PAGE = '%s_-_Tools' % URL_MANUAL_PAGE
WIKI_HELP_SEC = _('manual|GeneanetForGramps')
# Global variables
db = None
gname = None
verbosity = 0
force = False
ascendants = False
descendants = False
spouses = False
LEVEL = 2
ROOTURL = 'https://gw.geneanet.org/'
PROFIL = None
GUIMODE = False
progress = None
CONFIG_NAME = "geneanetforgramps"
CONFIG = config.register_manager(CONFIG_NAME)
CONFIG.register("pref.ascendants", ascendants)
CONFIG.register("pref.descendants", descendants)
CONFIG.register("pref.spouses", spouses)
CONFIG.register("pref.level", LEVEL)
CONFIG.register("pref.force", force)
CONFIG.register("pref.verbosity", verbosity)
CONFIG.load()
def save_config():
CONFIG.set("pref.ascendants", ascendants)
CONFIG.set("pref.descendants", descendants)
CONFIG.set("pref.spouses", spouses)
CONFIG.set("pref.level", LEVEL)
CONFIG.set("pref.force", force)
CONFIG.set("pref.verbosity", verbosity)
CONFIG.save()
save_config()
# Generic functions
def format_ca(date):
"""
Change the 'ca' chain into the 'vers' chain for now in Geneanet analysis
"""
# If ca for an about date, replace with vers (for now)
if date[0:2] == "ca":
date = _("about")+date[2:]
return(date)
def format_year(date):
"""
Remove potential empty month/day coming from Gramps (00)
"""
if not date:
return(date)
if (date[-6:] == "-00-00"):
return(date[0:-6])
else:
return(date)
def format_iso(date_tuple):
"""
Format an iso date.
"""
year, month, day = date_tuple
# Format with a leading 0 if needed
month = str(month).zfill(2)
day = str(day).zfill(2)
if year == None or year == 0:
iso_date = ''
elif month == None or month == 0:
iso_date = str(year)
elif day == None or day == 0:
iso_date = '%s-%s' % (year, month)
else:
iso_date = '%s-%s-%s' % (year, month, day)
return iso_date
def format_noniso(date_tuple):
"""
Format an non-iso tuple into an iso date
"""
day, month, year = date_tuple
return(format_iso(year, month, day))
def convert_date(datetab):
''' Convert the Geneanet date format for birth/death/married lines
into an ISO date format
'''
if verbosity >= 3:
print(_("datetab received:"),datetab)
if len(datetab) == 0:
return(None)
idx = 0
if datetab[0] == 'en':
# avoid a potential month
if datetab[1].isalpha():
return(datetab[2][0:4])
# avoid a potential , after the year
elif datetab[1].isnumeric():
return(datetab[1][0:4])
if (datetab[0][0:2] == _("about")[0:2] or datetab[0][0:2] == _("after")[0:2] or datetab[0][0:2] == _("before")[0:2]) and (len(datetab) == 2):
return(datetab[0]+" "+datetab[1][0:4])
# In case of french language remove the 'le' prefix
if datetab[0] == 'le':
idx = 1
# In case of french language remove the 'er' prefix
if datetab[idx] == "1er":
datetab[idx] = "1"
bd1 = datetab[idx]+" "+datetab[idx+1]+" "+datetab[idx+2][0:4]
bd2 = datetime.strptime(bd1, "%d %B %Y")
return(bd2.strftime("%Y-%m-%d"))
# GUI Part
class GeneanetForGrampsOptions(MenuToolOptions):
"""
Defines options and provides handling interface.
"""
def __init__(self, name, person_id=None, dbstate=None):
""" Initialize the options class """
if verbosity >= 3:
print(_("Init Plugin Options"))
MenuToolOptions.__init__(self, name, person_id, dbstate)
def add_menu_options(self, menu):
"""
Add all menu options to the tool window.
"""
if verbosity >= 3:
print(_("Add Plugin Menu Options"))
#category_name = _("Options")
category_name = _("Geneanet Import Options")
# Do not know if this works!
# Not registered for possible privacy issues, so only local settings
self.__user = 'user'
self.__user = StringOption(_("Account"), 'Identifiant ou adresse e-mail')
self.__user.set_help(_("Experimental field for setting geneanet stuff (user)"))
menu.add_option(category_name, "user", self.__user)
self.__pass = 'pass'
self.__pass = StringOption(_("Password"), 'Mot de passe')
self.__pass.set_help(_("Experimental field for setting geneanet stuff (password)"))
menu.add_option(category_name, "pass", self.__pass)
self.__pid = PersonOption(_("Center Person"))
self.__pid.set_help(_("The center person for the filter"))
menu.add_option(category_name, "pid", self.__pid)
if verbosity >= 3:
print(_("Before URL"))
self.__gui_url = StringOption(_("Geneanet URL for the selected person"), ROOTURL)
self.__gui_url.set_help(_("URL on Geneanet of the person you have selected which will be used as an import base such as https://gw.geneanet.org/agnesy?lang=fr&n=queffelec&oc=17&p=marie+anne"))
menu.add_option(category_name, "gui_url", self.__gui_url)
if verbosity >= 3:
print(_("Before ASC"))
gui_asc = CONFIG.get('pref.ascendants')
if verbosity >= 3:
if gui_asc:
print(_("ASC True"))
else:
print(_("ASC False"))
self.__gui_asc = BooleanOption(_("Import ascendants"), gui_asc)
self.__gui_asc.set_help(_("Import ascendants of the selected person up to level number"))
menu.add_option(category_name, "gui_asc", self.__gui_asc)
if verbosity >= 3:
print(_("Before DSC"))
gui_dsc = CONFIG.get('pref.descendants')
if verbosity >= 3:
if gui_dsc:
print(_("DSC True"))
else:
print(_("DSC False"))
self.__gui_dsc = BooleanOption(_("Import descendants"), gui_dsc)
self.__gui_dsc.set_help(_("Import descendants of the selected person up to level number"))
menu.add_option(category_name, "gui_dsc", self.__gui_dsc)
if verbosity >= 3:
print(_("Before SPO"))
gui_spo = CONFIG.get('pref.spouses')
if verbosity >= 3:
if gui_spo:
print(_("SPO True"))
else:
print(_("SPO False"))
self.__gui_spo = BooleanOption(_("Import spouses"), gui_spo)
self.__gui_spo.set_help(_("Import all spouses of the selected person"))
menu.add_option(category_name, "gui_spo", self.__gui_spo)
if verbosity >= 3:
print(_("Before LVL"))
gui_lvl = CONFIG.get('pref.level')
if verbosity >= 3:
print(_("LVL:"), gui_lvl)
self.__gui_level = NumberOption(_("Level of Import"), gui_lvl, 1, 100)
self.__gui_level.set_help(_("Maximum of upper or lower search done in the family tree - keep it small"))
menu.add_option(category_name, "gui_level", self.__gui_level)
if verbosity >= 3:
print(_("Before FORCE"))
gui_force = CONFIG.get('pref.force')
if verbosity >= 3:
if gui_force:
print(_("FORCE True"))
else:
print(_("FORCE False"))
self.__gui_force = BooleanOption(_("Force Import"), gui_force)
self.__gui_force.set_help(_("Force import of existing persons"))
menu.add_option(category_name, "gui_force", self.__gui_force)
if verbosity >= 3:
print(_("Before VRB"))
gui_verb = CONFIG.get('pref.verbosity')
if verbosity >= 3:
print(_("VRB:"), gui_verb)
self.__gui_verb = NumberOption(_("Verbosity"), gui_verb, 0, 3)
self.__gui_verb.set_help(_("Verbosity level from 0 (minimal) to 3 (very verbose)"))
menu.add_option(category_name, "gui_verb", self.__gui_verb)
if verbosity >= 3:
print(_("Menu Added"))
class GeneanetForGramps(PluginWindows.ToolManagedWindowBatch):
"""
Plugin that gives simplified interface to the import from Geneanet
"""
def __init__(self, dbstate, user, options_class, name, callback):
if verbosity >= 3:
print(_("Init Plugin itself"))
PluginWindows.ToolManagedWindowBatch.__init__(self, dbstate, user, options_class, name, callback)
def get_title(self):
if verbosity >= 3:
print(_("Plugin get_title"))
return _("Geneanet Import Tool") # tool window title
def initial_frame(self):
if verbosity >= 3:
print(_("Plugin initial_frame"))
return _("Geneanet Import Options") # tab title
def run(self):
"""
Main function running the Geneanet Import Tool
"""
global db
global GUIMODE
global progress
if verbosity >= 3:
print(_("Plugin run"))
db = self.dbstate.db
self.__get_menu_options()
hdr = _('Importing from %s for user %s') % (self.purl, self.gid)
msg = _('Geneanet Import into Gramps')
progress = ProgressMeter(msg, hdr)
#progress = ProgressMeter(msg, hdr, False, None, True, None)
progress.set_pass(hdr,100,mode=ProgressMeter.MODE_ACTIVITY)
if verbosity >= 2:
print(msg)
GUIMODE = True
g2gaction(self.gid, self.purl)
def __get_menu_options(self):
"""
General menu option processing.
"""
global force
global ascendants
global descendants
global spouses
global LEVEL
global verbosity
if verbosity >= 3:
print(_("Plugin __get_menu_options"))
menu = self.options.menu
self.gid = self.options.menu.get_option_by_name('pid').get_value()
if verbosity >= 3:
print(_("GID:"),self.gid)
self.purl = self.options.menu.get_option_by_name('gui_url').get_value()
if verbosity >= 3:
print(_("URL:"),self.purl)
force = self.options.menu.get_option_by_name('gui_force').get_value()
ascendants = self.options.menu.get_option_by_name('gui_asc').get_value()
if verbosity >= 3:
if ascendants:
print(_("ASC True"))
else:
print(_("ASC False"))
descendants = self.options.menu.get_option_by_name('gui_dsc').get_value()
spouses = self.options.menu.get_option_by_name('gui_spo').get_value()
LEVEL = self.options.menu.get_option_by_name('gui_level').get_value()
verbosity = self.options.menu.get_option_by_name('gui_verb').get_value()
if verbosity >= 3:
print(_("LVL:"),LEVEL)
save_config()
class GBase:
def __init__(self):
pass
def _smartcopy(self,attr):
'''
Smart Copying an attribute from geneanet (g_ attrs) into attr
Works for GPerson and GFamily
'''
if verbosity >= 3:
print(_("Smart Copying Attributes"),attr)
# By default do not copy as Gramps is the master reference
scopy = False
# Find the case where copy is to be done
# Nothing yet
if not self.__dict__[attr]:
scopy = True
# Empty field
if self.__dict__[attr] and self.__dict__[attr] == "" and self.__dict__['g_'+attr] and self.__dict__['g_'+attr] != "":
scopy = True
# Force the copy
if self.__dict__[attr] != self.__dict__['g_'+attr] and force:
scopy = True
# Managing sex, Gramps is always right except when unknown
# Warn on conflict
if attr == 'sex' and self.__dict__[attr] == 'U' and self.__dict__['g_'+attr] != 'U':
scopy = True
if (self.__dict__[attr] == 'F' and self.__dict__['g_'+attr] == 'M') \
or (self.__dict__[attr] == 'M' and self.__dict__['g_'+attr] == 'F'):
if verbosity >= 1:
print(_("WARNING: Gender conflict between Geneanet (%s) and Gramps (%s), keeping Gramps value")%(self.__dict__['g_'+attr],self.__dict__[attr]))
scopy = False
if attr == 'lastname' and self.__dict__[attr] != self.__dict__['g_'+attr]:
if verbosity >= 1 and self.__dict__[attr] != "":
print(_("WARNING: Lastname conflict between Geneanet (%s) and Gramps (%s), keeping Gramps value")%(self.__dict__['g_'+attr],self.__dict__[attr]))
if attr == 'lastname' and self.__dict__[attr] == "":
scopy = True
if attr == 'firstname' and self.__dict__[attr] != self.__dict__['g_'+attr]:
if verbosity >= 1 and self.__dict__[attr] != "":
print(_("WARNING: Firstname conflict between Geneanet (%s) and Gramps (%s), keeping Gramps value")%(self.__dict__['g_'+attr],self.__dict__[attr]))
if attr == 'firstname' and self.__dict__[attr] == "":
scopy = True
# Copy only if code is more precise
match = re.search(r'code$', attr)
if match:
if not self.__dict__[attr]:
scopy = True
else:
if not self.__dict__['g_'+attr]:
scopy = False
else:
try:
if int(self.__dict__[attr]) < int(self.__dict__['g_'+attr]):
scopy = True
except ValueError:
LOG.debug(str(self.__dict__[attr]))
# Copy only if date is more precise
match = re.search(r'date$', attr)
if match:
if not self.__dict__[attr]:
scopy = True
else:
if not self.__dict__['g_'+attr]:
scopy = False
else:
if self.__dict__[attr] == "" and self.__dict__['g_'+attr] != "":
scopy = True
elif self.__dict__[attr] < self.__dict__['g_'+attr]:
scopy = True
if scopy:
if verbosity >= 2:
print(_("Copying Person attribute %s (former value %s newer value %s)")%(attr, self.__dict__[attr],self.__dict__['g_'+attr]))
self.__dict__[attr] = self.__dict__['g_'+attr]
else:
if verbosity >= 3:
print(_("Not Copying Person attribute (%s, value %s) onto %s")%(attr, self.__dict__[attr],self.__dict__['g_'+attr]))
def get_or_create_place(self,event,placename):
'''
Create Place for Events or get an existing one based on the name
'''
try:
pl = event.get_place_handle()
except:
place = Place()
return(place)
if pl:
try:
place = db.get_place_from_handle(pl)
if verbosity >= 2:
print(_("Reuse Place from Event:"), place.get_name().value)
except:
place = Place()
else:
if placename == None:
place = Place()
return(place)
keep = None
# Check whether our place already exists
for handle in db.get_place_handles():
pl = db.get_place_from_handle(handle)
explace = pl.get_name().value
if verbosity >= 4:
LOG.debug((("search for "), str(placename),str(explace)))
if str(explace) == str(placename):
keep = pl
break
if keep == None:
if verbosity >= 2:
print(_("Create Place:"), placename)
place = Place()
else:
if verbosity >= 2:
print(_("Reuse existing Place:"), placename)
place = keep
return(place)
def get_or_create_event(self, gobj, attr, tran, timelog):
'''
Create Birth and Death Events for a person
and Marriage Events for a family or get an existing one
self is GPerson or GFamily
gobj is a gramps object Person or Family
'''
if config.get('preferences.tag-on-import'):
pref = config.get('preferences.tag-on-import-format')
default_tag = time.strftime(pref)
else:
default_tag= timelog
event = None
# Manages name indirection for person
if gobj.__class__.__name__ == 'Person':
role = EventRoleType.PRIMARY
func = getattr(gobj,'get_'+attr+'_ref')
reffunc = func()
if reffunc:
event = db.get_event_from_handle(reffunc.ref)
if verbosity >= 2:
print(_("Existing ")+attr+_(" Event"))
elif gobj.__class__.__name__ == 'Family':
role = EventRoleType.FAMILY
if attr == 'marriage':
marev = None
for event_ref in gobj.get_event_ref_list():
event = db.get_event_from_handle(event_ref.ref)
if (event.get_type() == EventType.MARRIAGE and
(event_ref.get_role() == EventRoleType.FAMILY or
event_ref.get_role() == EventRoleType.PRIMARY)):
marev = event
if marev:
event = marev
if verbosity >= 2:
print(_("Existing ")+attr+_(" Event"))
else:
print(_("ERROR: Unable to handle class %s in get_or_create_all_event")%(gobj.__class__.__name__))
if event is None:
event = Event()
uptype = getattr(EventType,attr.upper())
event.set_type(EventType(uptype))
try:
event.set_description(str(self.title[0]))
except:
event.set_description(_("No title"))
if db.get_tag_from_name(default_tag):
tag = db.get_tag_from_name(default_tag)
else:
tag = Tag()
tag.set_name(default_tag)
db.add_tag(tag, tran)
event.add_tag(tag.handle)
db.add_event(event, tran)
eventref = EventRef()
eventref.set_role(role)
eventref.set_reference_handle(event.get_handle())
if gobj.__class__.__name__ == 'Person':
func = getattr(gobj,'set_'+attr+'_ref')
reffunc = func(eventref)
db.commit_event(event, tran)
gobj.add_tag(tag.handle)
db.commit_person(gobj, tran)
elif gobj.__class__.__name__ == 'Family':
eventref.set_role(EventRoleType.FAMILY)
gobj.add_event_ref(eventref)
if attr == 'marriage':
gobj.set_relationship(FamilyRelType(FamilyRelType.MARRIED))
db.commit_event(event, tran)
gobj.add_tag(tag.handle)
db.commit_family(gobj, tran)
if verbosity >= 2:
print(_("Creating ")+attr+" ("+str(uptype)+") "+_("Event"))
if self.__dict__[attr+'date'] \
or self.__dict__[attr+'place'] \
or self.__dict__[attr+'placecode'] :
# Get or create the event date
date = event.get_date_object()
if self.__dict__[attr+'date']:
idx = 0
mod = Date.MOD_NONE
if self.__dict__[attr+'date'][0:2] == _("about")[0:2]:
idx = 1
mod = Date.MOD_ABOUT
elif self.__dict__[attr+'date'][0:2] == _("before")[0:2]:
idx = 1
mod = Date.MOD_BEFORE
elif self.__dict__[attr+'date'][0:2] == _("after")[0:2]:
idx = 1
mod = Date.MOD_AFTER
# Only in case of french language analysis
elif self.__dict__[attr+'date'][0:2] == _("in")[0:2]:
idx = 1
else:
pass
if idx == 1:
# we need to removed the first word
string = self.__dict__[attr+'date'].split(' ',1)[1]
else:
string = self.__dict__[attr+'date']
# ISO string, put in a tuple, reversed
tab = string.split('-')
if len(tab) == 3:
date.set_yr_mon_day(int(tab[0]),int(tab[1]),int(tab[2]))
elif len(tab) == 2:
date.set_yr_mon_day(int(tab[0]),int(tab[1]),0)
elif len(tab) == 1:
date.set_year(int(tab[0]))
elif len(tab) == 0:
print(_("WARNING: Trying to affect an empty date"))
pass
else:
print(_("WARNING: Trying to affect an extra numbered date"))
pass
if mod:
date.set_modifier(mod)
if verbosity >= 2 and self.__dict__[attr+'date']:
print(_("Update ")+attr+_(" Date to ")+self.__dict__[attr+'date'])
event.set_date_object(date)
db.commit_event(event, tran)
if self.__dict__[attr+'place'] \
or self.__dict__[attr+'placecode'] :
if self.__dict__[attr+'place']:
placename = self.__dict__[attr+'place']
else:
placename = ""
place = self.get_or_create_place(event, placename)
# TODO: Here we overwrite any existing value.
# Check whether that can be a problem
place.set_name(PlaceName(value=placename))
if self.__dict__[attr+'placecode']:
place.set_code(self.__dict__[attr+'placecode'])
place_tag = _('place from geneanet')
if db.get_tag_from_name(place_tag):
ptag = db.get_tag_from_name(place_tag)
else:
ptag = Tag()
ptag.set_name(place_tag)
db.add_tag(ptag, tran)
place.add_tag(ptag.handle)
db.add_place(place, tran)
event.set_place_handle(place.get_handle())
db.commit_event(event, tran)
db.commit_event(event, tran)
return
def get_gramps_date(self, evttype):
'''
Give back the date of the event related to the GPerson or GFamily
as a string ISO formated
'''
if verbosity >= 4:
print(_("EventType: %d")%(evttype))
if not self:
return(None)
if evttype == EventType.BIRTH:
ref = self.grampsp.get_birth_ref()
elif evttype == EventType.DEATH:
ref = self.grampsp.get_death_ref()
elif evttype == EventType.MARRIAGE:
eventref = None
for eventref in self.family.get_event_ref_list():
event = db.get_event_from_handle(eventref.ref)
if (event.get_type() == EventType.MARRIAGE
and (eventref.get_role() == EventRoleType.FAMILY
or eventref.get_role() == EventRoleType.PRIMARY)):
break
ref = eventref
else:
print(_("Didn't find a known EventType: "),evttype)
return(None)
if ref:
if verbosity >= 4:
print(_("Ref:"),ref)
try:
event = db.get_event_from_handle(ref.ref)
except:
print(_("Didn't find a known ref for this ref date: "),ref)
return(None)
if event:
if verbosity >= 4:
print(_("Event")+":",event)
date = event.get_date_object()
moddate = date.get_modifier()
tab = date.get_dmy()
if verbosity >= 4:
print(_("Found date: "),tab)
if len(tab) == 3:
tab = date.get_ymd()
if verbosity >= 4:
print(_("Found date2: "),tab)
ret = format_iso(tab)
else:
ret = format_noniso(tab)
if moddate == Date.MOD_BEFORE:
pref = _("before")+" "
elif moddate == Date.MOD_AFTER:
pref = _("after")+" "
elif moddate == Date.MOD_ABOUT:
pref = _("about")+" "
else:
pref = ""
if verbosity >= 3:
print(_("Returned date: ")+pref+ret)
return(pref+ret)
else:
return(None)
else:
return(None)
class GFamily(GBase):
'''
Family as seen by Gramps and Geneanet
'''
def __init__(self,father,mother):
# The 2 GPersons parents in this family should exist
# and properties filled before we create the family
# Gramps properties
self.title = ""
self.marriagedate = None
self.marriageplace = None
self.marriageplacecode = None
self.gid = None
# Pointer to the Gramps Family instance
self.family = None
# Geneanet properties
self.g_marriagedate = None
self.g_marriageplace = None
self.g_marriageplacecode = None
self.g_childref = []
if verbosity >= 1:
print(_("Creating GFamily: ")+father.firstname+" "+father.lastname+" - "+mother.firstname+" "+mother.lastname)
self.url = father.url
if self.url == "":
self.url = mother.url
# TODO: what if father or mother is None
self.father = father
self.mother = mother
def create_grampsf(self):
'''
Create a Family in Gramps and return it
'''
with DbTxn("Geneanet import", db) as tran:
grampsf = Family()
db.add_family(grampsf, tran)
self.gid = grampsf.gramps_id
self.family = grampsf
if verbosity >= 2:
print(_("Create new Gramps Family: ")+self.gid)
def find_grampsf(self):
'''
Find a Family in Gramps and return it
'''
if verbosity >= 2:
print(_("Look for a Gramps Family"))
f = None
ids = db.get_family_gramps_ids()
for i in ids:
f = db.get_family_from_gramps_id(i)
if verbosity >= 3:
print(_("Analysing Gramps Family ")+f.gramps_id)
# Do these people already form a family
father = None
fh = f.get_father_handle()
if fh:
father = db.get_person_from_handle(fh)
mother = None
mh = f.get_mother_handle()
if mh:
mother = db.get_person_from_handle(mh)
if verbosity >= 3:
if not father:
fgid = None
else:
fgid = father.gramps_id
if not fgid:
fgid = "None"
sfgid = self.father.gid
if not sfgid:
sfgid = "None"
print(_("Check father ids: ")+fgid+_(" vs ")+sfgid)
if not mother:
mgid = None
else:
mgid = mother.gramps_id
if not mgid:
mgid = "None"
smgid = self.mother.gid
if not smgid:
smgid = "None"
print(_("Check mother ids: ")+mgid+_(" vs ")+smgid)
if self.father and father and father.gramps_id == self.father.gid \
and self.mother and mother and mother.gramps_id == self.mother.gid:
return(f)
#TODO: What about preexisting families not created in this run ?
return(None)
def from_geneanet(self):
'''
Initiate the GFamily from Geneanet data
'''
# Once we get the right spouses, then we can have the marriage info
idx = 0
for sr in self.father.spouseref:
if verbosity >= 3:
print(_("Comparing sr %s to %s (idx: %d)")%(sr,self.mother.url,idx))
if sr == self.mother.url:
if verbosity >= 2:
print(_("Spouse %s found (idx: %d)")%(sr,idx))
break
idx = idx + 1
if idx < len(self.father.spouseref):
# We found one
try:
self.g_marriagedate = self.father.marriagedate[idx]
self.g_marriageplace = self.father.marriageplace[idx]
self.g_marriageplacecode = self.father.marriageplacecode[idx]
except:
LOG.debug('marriage, father and spouse(%s)' % idx)
try:
for c in self.father.childref[idx]:
LOG.info(c)
self.g_childref.append(c)
except:
LOG.debug('child, father and spouse(%s)' % idx)
if self.g_marriagedate and self.g_marriageplace and self.g_marriageplacecode:
if verbosity >= 2:
print(_("Geneanet Marriage found the %s at %s (%s)")%(self.g_marriagedate,self.g_marriageplace,self.g_marriageplacecode))
def from_gramps(self,gid):
'''
Initiate the GFamily from Gramps data
'''
if verbosity >= 2:
print(_("Calling from_gramps with gid: %s")%(gid))
# If our gid was already setup and we didn't pass one
if not gid and self.gid:
gid = self.gid
if verbosity >= 2:
print(_("Now gid is: %s")%(gid))
found = None
try:
found = db.get_family_from_gramps_id(gid)
self.gid = gid
self.family = found
if verbosity >= 2:
print(_("Existing gid of a Gramps Family: %s")%(self.gid))
except:
if verbosity >= 1:
print(_("WARNING: Unable to retrieve id %s from the gramps db %s")%(gid,gname))
if not found:
# If we don't know which family this is, try to find it in Gramps
# This supposes that Geneanet data are already present in GFamily
self.family = self.find_grampsf()
if self.family:
if verbosity >= 2:
print(_("Found an existing Gramps family ")+self.family.gramps_id)
self.gid = self.family.gramps_id
# And if we haven't found it, create it in gramps
if self.family == None:
self.create_grampsf()
if self.family:
self.marriagedate = self.get_gramps_date(EventType.MARRIAGE)
if self.marriagedate == "":
self.marriagedate = None
for eventref in self.family.get_event_ref_list():
event = db.get_event_from_handle(eventref.ref)
if (event.get_type() == EventType.MARRIAGE
and (eventref.get_role() == EventRoleType.FAMILY
or eventref.get_role() == EventRoleType.PRIMARY)):
place = self.get_or_create_place(event,None)
self.marriageplace = place.get_name().value
self.marriageplacecode = place.get_code()
break
if verbosity >= 2:
if self.marriagedate and self.marriageplace and self.marriageplacecode:
print(_("Gramps Marriage found the %s at %s (%s)")%(self.marriagedate,self.marriageplace,self.marriageplacecode))
def to_gramps(self):
'''
'''
# Smart copy from Geneanet to Gramps inside GFamily
self.smartcopy()
with DbTxn("Geneanet import", db) as tran:
# When it's not the case create the family
if self.family == None:
self.family = Family()
db.add_family(self.family, tran)
try:
grampsp0 = db.get_person_from_gramps_id(self.father.gid)
except:
if verbosity >= 2:
print(_("No father for this family"))
grampsp0 = None
if grampsp0:
try:
self.family.set_father_handle(grampsp0.get_handle())
except:
if verbosity >= 2:
print(_("Can't affect father to the family"))
db.commit_family(self.family, tran)
grampsp0.add_family_handle(self.family.get_handle())
db.commit_person(grampsp0, tran)
try:
grampsp1 = db.get_person_from_gramps_id(self.mother.gid)
except:
if verbosity >= 2:
print(_("No mother for this family"))
grampsp1 = None
if grampsp1:
try:
self.family.set_mother_handle(grampsp1.get_handle())
except:
if verbosity >= 2:
print(_("Can't affect mother to the family"))
db.commit_family(self.family, tran)
grampsp1.add_family_handle(self.family.get_handle())
db.commit_person(grampsp1, tran)
# Now celebrate the marriage ! (if needed)
timelog = _('marriage from Geneanet')
self.get_or_create_event(self.family, 'marriage', tran, timelog)
def smartcopy(self):
'''
Smart Copying GFamily
'''
if verbosity >= 2:
print(_("Smart Copying Family"))
self._smartcopy("marriagedate")
self._smartcopy("marriageplace")
self._smartcopy("marriageplacecode")
def add_child(self, child):
'''
Adds a child GPerson child to the GFamily
'''
found = None
i = 0
# Avoid handling already processed children in Gramps
for cr in self.family.get_child_ref_list():