def getargs_dialog(**kwargs): # type: () -> bool """ This code should really be in SuperTool.py because it contains user interface code... """ from types import SimpleNamespace from gi.repository import Gtk from gramps.gen.const import GRAMPS_LOCALE as glocale, CUSTOM_FILTERS _ = glocale.translation.gettext config = configman.register_manager("supertool") config.load() dialog = Gtk.Dialog( title=_("Parameters"), parent=None, flags=Gtk.DialogFlags.MODAL ) dialog.add_button(_("Ok"), Gtk.ResponseType.OK) dialog.add_button(_("Cancel"), Gtk.ResponseType.CANCEL) dialog.set_default_response(Gtk.ResponseType.OK) grid = Gtk.Grid() widgets = [] for row, param in enumerate(kwargs.items()): param_name, title = param key = "default-params." + param_name config.register(key, "") value = config.get(key) lbl_title = Gtk.Label(title) lbl_title.set_halign(Gtk.Align.START) widget = Gtk.Entry() #self.get_widget(opttype) widget.set_text(value) grid.attach(lbl_title, 0, row, 1, 1) grid.attach(widget, 1, row, 1, 1) widgets.append((param_name, widget)) dialog.vbox.pack_start(grid, False, False, 5) dialog.show_all() result = dialog.run() if result != Gtk.ResponseType.OK: dialog.destroy() raise RuntimeError("canceled") return False values = {} for param_name, widget in widgets: value = widget.get_text() values[param_name] = value key = "default-params." + param_name config.set(key, value) config.save() dialog.destroy() return SimpleNamespace(**values)
def init_config(self): """ If you need a view with a config, then call this method in the build_widget or __init__ method. It will set up a config file for the view, and use CONFIGSETTINGS to set the config defaults. The config is later accessbile via self._config So you can do self._config.get("section.variable1") self._config.set("section.variable1", value) self._config.save() CONFIGSETTINGS should be a list with tuples like ("section.variable1", value) """ if self._config: return self._config = config.register_manager(self.ident, use_config_path=True) for section, value in self.CONFIGSETTINGS: self._config.register(section, value) self._config.init() self.config_connect()
) elif locals().get('uistate'): # don't start GUI if in CLI mode, just ignore from gramps.gen.config import config from gramps.gui.dialog import QuestionDialog2 from gramps.gen.config import logging if not module1: warn_msg = _( "NetworkChart Warning: Python networkx module not found.") logging.log(logging.WARNING, warn_msg) if not (module2 or module3): warn_msg = _( "NetworkChart Warning: NetworkChart needs one of the following to work: \n" " Python module pydotplus OR\n" " Python module pygraphviz OR\n") logging.log(logging.WARNING, warn_msg) inifile = config.register_manager("networkchartwarn") inifile.load() sects = inifile.get_sections() if 'networkchartwarn' not in sects: yes_no = QuestionDialog2( _("NetworkChart Failed to Load"), _("\n\nNetworkChart is missing python modules or programs. Networkx AND at\n" "least one of (pydotplus OR pygraphviz) must be\n" "installed. For now, it may be possible to install the files manually. See\n\n" "https://gramps-project.org/wiki/index.php?title=NetworkChart \n\n" "To dismiss all future NetworkChart warnings click Dismiss."), _(" Dismiss "), _("Continue"), parent=uistate.window) prompt = yes_no.run() if prompt is True:
def importReferenceSources(db, filename, user): def findNextRidno(ridstrt): with DbTxn(_("Find next ridno"), db): prefix_save = db.get_repository_prefix() db.set_repository_id_prefix(ridstrt + '%04d') next_ridno = db.find_next_repository_gramps_id() LOG.debug('Next ridno = ' + next_ridno) db.set_repository_id_prefix(prefix_save) return next_ridno def findNextSidno(ridno): with DbTxn(_("Find next sidno"), db): prefix_save = db.get_source_prefix() db.set_source_id_prefix(ridno + '%04d') next_sidno = db.find_next_source_gramps_id() LOG.debug('Next sidno = ' + next_sidno) db.set_source_id_prefix(prefix_save) return next_sidno def addRepository(repositoryName, repositoryUrl, reftag): ridno = db.find_next_repository_gramps_id() repository = Repository() repositoryType = RepositoryType() repositoryType.set(RepositoryType.ARCHIVE) repository.set_type(repositoryType) repository.set_gramps_id(ridno) repository.set_name(repositoryName) urlList = [] # for urlPath in repositoryUrls: url = Url() url.set_path(repositoryUrl) url.set_description('Sshy') url.set_type(UrlType.WEB_HOME) urlList.append(url) repository.set_url_list(urlList) repository.set_change_time(chgtime) if reftag != None: repository.add_tag(reftag.get_handle()) with DbTxn(_("Add Repository"), db) as trans: rhandle = db.add_repository(repository, trans) return repository def addSource(sourceName, attribs, reftag, repository): snote = addNote(attribs[3], NoteType.SOURCE) sidno = db.find_next_source_gramps_id() source = Source() source.set_gramps_id(sidno) source.set_title(sourceName) source.set_author(attribs[0]) source.set_publication_info(attribs[1]) source.set_abbreviation(attribs[2]) source.add_note(snote.get_handle()) if reftag != None: source.add_tag(reftag.get_handle()) repoRef = RepoRef() repoRef.set_reference_handle(repository.get_handle()) source.add_repo_reference(repoRef) source.set_change_time(chgtime) with DbTxn(_("Add Source"), db) as trans: shandle = db.add_source(source, trans) return source def addNote(ntext, ntype): nidno = db.find_next_note_gramps_id() note = Note(ntext) note.set_gramps_id(nidno) note.set_type(ntype) if reftag != None: note.add_tag(reftag.get_handle()) note.set_change_time(chgtime) with DbTxn(_("Add Note"), db) as trans: nhandle = db.add_note(note, trans) LOG.debug('Note added: ' + ntext + ' ' + nhandle) return note def checkTagExistence(otext): with DbTxn(_("Read Tag"), db): tag = db.get_tag_from_name(otext) if tag != None: LOG.debug('Tag found by name, no duplicates: ' + otext + ' ' + tag.get_name()) else: tag = Tag() tag.set_name(otext) tag.set_color("#EF2929") with DbTxn(_("Add Tag"), db) as trans: thandle = db.add_tag(tag, trans) LOG.debug('Tag added: ' + tag.get_name() + ' ' + thandle) return tag fdir = os.path.dirname(filename) fh = logging.FileHandler(fdir + '\\sourceimport.log') formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) LOG.addHandler(fh) LOG.info(" fdir = " + fdir) # cout = fdir + "\\sresult.csv" LOG.debug('ini file handling') config = configman.register_manager("importsources") config.register("options.refstring", "r") config.load() config.save() refstr = config.get('options.refstring') r_count = 0 s_count = 0 u_count = 0 reftext = 'Referenssi' reftag = checkTagExistence(reftext) chgtime = int(time.time()) LOG.info(" chgtime = " + str(chgtime)) try: with open(filename, 'r', encoding="utf-8") as t_in: t_dialect = csv.Sniffer().sniff(t_in.read(2048)) t_dialect.delimiter = ";" t_in.seek(0) t_reader = csv.reader(t_in, t_dialect) LOG.info('CSV input file delimiter is ' + t_dialect.delimiter) for row in t_reader: rectype = row[ 0] # Record type = Gramps object id prefix character # otext = row[4].strip() if rectype == 'Arkisto': repoName = row[1] LOG.debug('New repository: ' + repoName) r_count += 1 # repotype = row[1] # repository type number repoUrl = row[3] LOG.debug("===========================> " + repoUrl) repository = addRepository(repoName, repoUrl, reftag) elif rectype == 'Lähde': sourceName = row[1] LOG.debug('Source row: ' + sourceName) s_count += 1 sourceNote = 'Sshy: ' + row[4] attribs = ( "", "", "", sourceNote ) # Author, Publication-info, Abbreviation, Note-text LOG.debug('New source: ' + sourceName) addSource(sourceName, attribs, reftag, repository) else: u_count += 1 LOG.debug('Unknown rectype: ' + rectype) # raise GrampsImportError('Unknown record type ' + rectype) except: exc = sys.exc_info()[0] LOG.error('*** Something went really wrong! ', exc) return ImportInfo({_('Results'): _('Something went really wrong ')}) results = { _('Results'): _('Input file handled.'), _(' Repositories '): str(r_count), _(' Sources '): str(s_count) } LOG.info('Input file handled.') LOG.info(' Repositories ' + str(r_count)) LOG.info(' Sources ' + str(s_count)) db.enable_signals() db.request_rebuild() return ImportInfo(results)
def importSourceHierarchies(db, filename, user): def findNextRidno(ridstrt): with DbTxn(_("Find next ridno"), db): prefix_save = db.get_repository_prefix() db.set_repository_id_prefix(ridstrt + '%04d') next_ridno = db.find_next_repository_gramps_id() LOG.debug('Next ridno = ' + next_ridno) db.set_repository_id_prefix(prefix_save) return next_ridno def findNextSidno(ridno): with DbTxn(_("Find next sidno"), db): prefix_save = db.get_source_prefix() db.set_source_id_prefix(ridno + '%04d') next_sidno = db.find_next_source_gramps_id() LOG.debug('Next sidno = ' + next_sidno) db.set_source_id_prefix(prefix_save) return next_sidno def addRepository(repositoryName, reftag): ridno = db.find_next_repository_gramps_id() repository = Repository() repositoryType = RepositoryType() repositoryType.set(RepositoryType.ARCHIVE) repository.set_type(repositoryType) repository.set_gramps_id(ridno) repository.set_name(repositoryName) repository.set_url_list(()) repository.set_change_time(chgtime) if reftag != None: repository.add_tag(reftag.get_handle()) with DbTxn(_("Add Repository"), db) as trans: rhandle = db.add_repository(repository, trans) return repository def addSource(sourceName, attribs, reftag, repository): snote = addNote(attribs[3], NoteType.SOURCE) sidno = db.find_next_source_gramps_id() source = Source() source.set_gramps_id(sidno) source.set_title(sourceName) source.set_author(attribs[0]) source.set_publication_info(attribs[1]) source.set_abbreviation(attribs[2]) source.add_note(snote.get_handle()) if reftag != None: source.add_tag(reftag.get_handle()) repoRef = RepoRef() repoRef.set_reference_handle(repository.get_handle()) source.add_repo_reference(repoRef) source.set_change_time(chgtime) with DbTxn(_("Add Source"), db) as trans: shandle = db.add_source(source, trans) return source def addNote(ntext, ntype): nidno = db.find_next_note_gramps_id() note = Note(ntext) note.set_gramps_id(nidno) note.set_type(ntype) if reftag != None: note.add_tag(reftag.get_handle()) note.set_change_time(chgtime) with DbTxn(_("Add Note"), db) as trans: nhandle = db.add_note(note, trans) LOG.debug('Note added: ' + ntext + ' ' + nhandle) return note def checkTagExistence(otext): with DbTxn(_("Read Tag"), db): tag = db.get_tag_from_name(otext) if tag != None: LOG.debug('Tag found by name, no duplicates: ' + otext + ' ' + tag.get_name()) else: tag = Tag() tag.set_name(otext) tag.set_color("#EF2929") with DbTxn(_("Add Tag"), db) as trans: thandle = db.add_tag(tag, trans) LOG.debug('Tag added: ' + tag.get_name() + ' ' + thandle) return tag fdir = os.path.dirname(filename) fh = logging.FileHandler(fdir + '\\sourceimport.log') formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setLevel(logging.INFO) fh.setFormatter(formatter) LOG.addHandler(fh) LOG.info(" fdir = " + fdir) LOG.debug('ini file handling') config = configman.register_manager("importsources") ''' config.register("options.repositoryidrng", "1000") config.register("options.repositoryincr", "1") config.register("options.sourceidrng", "1000") config.register("options.sourceidincr", "1") ''' config.register("options.refstring", "r") config.load() config.save() r_count = 0 s_count = 0 reftag = checkTagExistence('Referenssi') chgtime = int(time.time()) LOG.info(" chgtime = " + str(chgtime)) try: currRepoName = '' with open(filename, 'r', encoding="utf-8-sig") as t_in: t_dialect = csv.Sniffer().sniff(t_in.read(1024)) t_dialect.delimiter = ";" t_in.seek(0) t_reader = csv.reader(t_in, t_dialect) LOG.info('CSV input file delimiter is ' + t_dialect.delimiter) global repository for row in t_reader: repoName = row[0].strip() # Repository name if repoName != currRepoName: currRepoName = repoName LOG.debug('New repository: ' + currRepoName) repository = addRepository(currRepoName, reftag) r_count += 1 sourceName = repoName + " " + row[1].strip( ) + " " + row[2].strip() attribs = (repoName, "", row[3], row[4]) LOG.debug('New source: ' + sourceName) addSource(sourceName, attribs, reftag, repository) s_count += 1 # LOG.debug('Unknown rectype: ' + rectype) # raise GrampsImportError('Unknown record type ' + rectype) except: exc = sys.exc_info()[0] LOG.error('*** Something went really wrong! ', exc) return ImportInfo({_('Results'): _('Something went really wrong ')}) results = { _('Results'): _('Input file handled.'), _(' Repositories '): str(r_count), _(' Sources '): str(s_count) } LOG.info('Input file handled.') LOG.info(' Repositories ' + str(r_count)) LOG.info(' Sources ' + str(s_count)) db.enable_signals() db.request_rebuild() return ImportInfo(results)
from gramps.gen.plug import Gramplet from gramps.gui.configure import GrampsPreferences from gramps.gen.config import config as configman from gramps.gen.const import GRAMPS_LOCALE as glocale try: _TRANS = glocale.get_addon_translator(__file__) except ValueError: _TRANS = glocale.translation _ = _TRANS.gettext VERSION_DIR = "gramps%s%s" % VERSION_TUPLE[0:2] DEFAULT_URL = "https://raw.githubusercontent.com/gramps-project/addons/master/" + VERSION_DIR ISOTAMMI_URL = "https://raw.githubusercontent.com/Taapeli/isotammi-addons/master/addons/" + VERSION_DIR isotammi_config = configman.register_manager("isotammi") isotammi_config.register("options.apikey", "") isotammi_config.register("options.apiurl", "") def get_apikey(): isotammi_config.load() apikey = isotammi_config.get('options.apikey') return apikey def set_apikey(apikey): isotammi_config.load() isotammi_config.set('options.apikey', apikey) isotammi_config.save()
#------------------------------------------------------------------------- # # face detection module # #------------------------------------------------------------------------- sys.path.append(os.path.abspath(os.path.dirname(__file__))) import facedetection #------------------------------------------------------------------------- # # configuration # #------------------------------------------------------------------------- GRAMPLET_CONFIG_NAME = "phototagginggramplet" CONFIG = config.register_manager(GRAMPLET_CONFIG_NAME) CONFIG.register("detection.box_size", (50, 50)) CONFIG.register("detection.inside_existing_boxes", False) CONFIG.register("detection.sensitivity", 10) CONFIG.register("selection.replace_without_asking", False) CONFIG.load() CONFIG.save() MIN_FACE_SIZE = CONFIG.get("detection.box_size") REPLACE_WITHOUT_ASKING = CONFIG.get("selection.replace_without_asking") DETECT_INSIDE_EXISTING_BOXES = CONFIG.get("detection.inside_existing_boxes") SENSITIVITY = CONFIG.get("detection.sensitivity") def save_config(): CONFIG.set("detection.box_size", MIN_FACE_SIZE)
#------------------------------------------------------------------------ dbfavailable = False direct_tmg_pjc_ver_support = False grampsversion = "5.1" try: # External Library: dbf.pypi # https://pypi.python.org/pypi/dbf import dbf dbfavailable = True except (ImportError, ValueError): dbfavailable = False if not dbfavailable: from gramps.gen.config import config inifile = config.register_manager("tmgimporterwarn") inifile.load() sects = inifile.get_sections() # Don't register if not runnable, but have to 'Make build' anyway if(dbfavailable or locals().get('build_script')): register(IMPORT, id = 'im_sqz', name = _('TMG Project Backup'), description = _('Import TMG project files'), version = '0.0.73', gramps_target_version = grampsversion, include_in_listing = False, status = STABLE, fname = 'importtmg.py', import_function = 'importSqzData',
'sk': 'Slovak', 'es': 'Spanish', 'sv': 'Swedish', 'ru': 'Russian', } QUALITY_MAP = { Citation.CONF_VERY_HIGH: "3", Citation.CONF_HIGH: "2", Citation.CONF_NORMAL: "1", Citation.CONF_LOW: "0", Citation.CONF_VERY_LOW: "0", } GRAMPLET_CONFIG_NAME = "gedcomforgeneanet" CONFIG = config.register_manager("gedcomforgeneanet") CONFIG.register("preferences.include_witnesses", True) CONFIG.register("preferences.include_media", False) CONFIG.register("preferences.include_depot", True) CONFIG.register("preferences.extended_role", False) CONFIG.register("preferences.relativepath", True) CONFIG.register("preferences.quaynote", True) CONFIG.register("preferences.zip", False) CONFIG.register("preferences.namegen", True) CONFIG.register("preferences.nameus", False) CONFIG.register("preferences.anychar", True) CONFIG.register("preferences.citattr", True) CONFIG.load()
description=_('PostgreSQL Database'), version='1.0.6', gramps_target_version='5.1', status=STABLE, fname='postgresql.py', databaseclass='PostgreSQL', authors=['Doug Blank'], authors_email=['*****@*****.**']) elif locals().get('uistate'): # don't start GUI if in CLI mode, just ignore from gramps.gen.config import config from gramps.gui.dialog import QuestionDialog2 from gramps.gen.config import logging if not module1: warn_msg = _("PostgreSQL Warning: Python psycopg2 module not found.") logging.log(logging.WARNING, warn_msg) inifile = config.register_manager("postgresqlwarn") inifile.load() sects = inifile.get_sections() if 'postgresqlwarn' not in sects: yes_no = QuestionDialog2( _("PostgreSQL Failed to Load"), _("\n\nPostgreSQL is missing the psycopg2 python module.\n" "For now, it may be possible to install the files manually. See\n\n" "https://gramps-project.org/wiki/index.php?title=PostgreSQL \n\n" "To dismiss all future PostgreSQL warnings click Dismiss."), _(" Dismiss "), _("Continue"), parent=uistate.window) prompt = yes_no.run() if prompt is True: inifile.register('postgresqlwarn.MissingModules', "")
# # Geography view # #------------------------------------------------------------------------ import os import sys import importlib import traceback from gi import Repository from gramps.gen.const import USER_PLUGINS from gramps.gen.config import logging from gramps.gen.config import config from gramps.gen.plug.utils import Zipfile inifile = config.register_manager("placecoordinategramplet_warn") inifile.load() sects = inifile.get_sections() from gramps.gen.const import GRAMPS_LOCALE as glocale try: _trans = glocale.get_addon_translator( os.path.join(USER_PLUGINS, 'PlaceCoordinateGramplet', 'PlaceCoordinateGramplet.gpr.py')) except ValueError: _trans = glocale.translation _ = _trans.gettext #------------------------------------------------------------------------- # # set up logging
gramps_target_version = '5.1', include_in_listing = True, ) elif locals().get('uistate'): # don't start GUI if in CLI mode, just ignore from gramps.gen.config import config from gramps.gui.dialog import QuestionDialog2 from gramps.gen.config import logging if not module1: warn_msg = _("NetworkChart Warning: Python networkx module not found.") logging.log(logging.WARNING, warn_msg) if not (module2 or module3): warn_msg = _("NetworkChart Warning: NetworkChart needs one of the following to work: \n" " Python module pydotplus OR\n" " Python module pygraphviz OR\n") logging.log(logging.WARNING, warn_msg) inifile = config.register_manager("networkchartwarn") inifile.load() sects = inifile.get_sections() if 'networkchartwarn' not in sects: yes_no = QuestionDialog2(_("NetworkChart Failed to Load"), _("\n\nNetworkChart is missing python modules or programs. Networkx AND at\n" "least one of (pydotplus OR pygraphviz) must be\n" "installed. For now, it may be possible to install the files manually. See\n\n" "https://gramps-project.org/wiki/index.php?title=NetworkChart \n\n" "To dismiss all future NetworkChart warnings click Dismiss."), _(" Dismiss "), _("Continue"), parent=uistate.window) prompt = yes_no.run() if prompt is True: inifile.register('networkchartwarn.MissingModules', "") inifile.set('networkchartwarn.MissingModules', "True")
from gramps.plugins.export.exportxml import GrampsXmlWriter from gramps.plugins.export.exportpkg import PackageWriter, fix_mtime from gramps.version import VERSION from gramps.gen.db.exceptions import DbWriteFailure from gramps.gen.constfunc import win from gramps.gen.utils.file import media_path_full from gramps.gen.const import GRAMPS_LOCALE as glocale try: _trans = glocale.get_addon_translator(__file__) except ValueError: _trans = glocale.translation _ = _trans.gettext from gramps.gen.config import config as configman config = configman.register_manager("isotammiexport") config.register("defaults.include_media", False) config.register("defaults.material_type", "Family Tree") config.register("defaults.description", "") import logging log = logging.getLogger(".isotammiexportxml") #------------------------------------------------------------------------- # # export_data # #------------------------------------------------------------------------- def export_data(database, filename, user, option_box=None): """
def importPlaceHierarchies(db, filename, user): all_countries = [] # Countries in the database municipalities_of_current_country = [] # Municipalities in the current state villages_of_current_municipality = [] # Villages in the current municipality farms_of_current_village = [] buildings_of_current_farm = [] h_count = 0 # Header line count country_count = 0 # Country count (valtio) municipality_count = 0 # Municipality count (kunta) village_count = 0 # Village count (kylä) farm_count = 0 # farm count (tila) building_count = 0 unknown_count = 0 # Unknown row count def get_level0(db): for handle in db.find_place_child_handles(''): place = db.get_place_from_handle(handle) if int(place.get_type()) == PlaceType.COUNTRY: all_countries.append(place) return all_countries def parseNames(pname, plang='fi'): pnames = pname.split(',') LOG.debug('Place name %s split into %d pieces' % (pname, len(pnames))) priName = (pnames[0].strip(), plang) altNames = [] if len(pnames) > 1: del pnames[0] for aname in pnames: altName = PlaceName() anameparts = aname.split(':') if len(anameparts) == 1: altName.set_value(anameparts[0].strip()) altName.set_language('se') altNames.append(altName) elif len(anameparts) == 2: altName.set_value(anameparts[1].strip()) altName.set_language(anameparts[0].strip()) altNames.append(altName) else: LOG.error('Pieleen meni? %s' % aname) return priName, altNames def findPlace(pid, pname): place = None if pid != '': with DbTxn(_("Read place"), db): place = db.get_place_from_id(pid) if place != None: LOG.info('Place read by id: ' + pid + ' ' + place.get_name().get_value()) else: LOG.error('Place NOT found by id: ' + pid + ' ' + pname) raise GrampsImportError('Place NOT found by id: ', pid + '/' + pname) return place def checkPlaceDuplicate(pname, old_places): if len(old_places) > 0: for old_place in old_places: LOG.debug('Comparing ' + pname + ' with ' + old_place.get_name().get_value()) if old_place.get_name().get_value() == pname: # LOG.debug('Found match ' + pname + ' with ' + place.get_name().get_value() + ' of type ' + place.__class__.__name__ ) return old_place return None def addPlace(priName, altNames, ptype, refPlace=None): place = Place() placeName = PlaceName() placeName.set_value(priName[0]) placeName.set_language(priName[1]) place.set_name(placeName) if len(altNames) > 0: place.set_alternative_names(altNames) # place.set_change_time(chgtime) place.set_type(ptype) # place.add_tag(tags[ptype]) place.add_tag(reftag) if refPlace != None: placeRef = PlaceRef() placeRef.set_reference_handle(refPlace.get_handle()) place.add_placeref(placeRef) # tag.set_color("#EF2929") with DbTxn(_("Add Place"), db) as trans: phandle = db.add_place(place, trans) LOG.debug('Place added: ' + place.get_name().get_value() + ' ' + phandle) return place def checkTagExistence(otext): with DbTxn(_("Read Tag"), db): tag = db.get_tag_from_name(otext) if tag != None: LOG.debug('Tag found by name, no duplicates: ' + otext + ' ' + tag.get_name()) else: tag = Tag() tag.set_name(otext) tag.set_color("#EF2929") with DbTxn(_("Add Tag"), db) as trans: thandle = db.add_tag(tag, trans) LOG.debug('Tag added: ' + tag.get_name() + ' ' + thandle) return tag def findNextPidno(pidstrt): with DbTxn(_("Find next pidno"), db): prefix_save = db.get_place_prefix() db.set_place_id_prefix(pidstrt + '%05d') next_pidno = db.find_next_place_gramps_id() LOG.debug('Next pidno = ' + next_pidno) db.set_place_id_prefix(prefix_save) return next_pidno chgtime = int(time.time()) LOG.info(" chgtime = " + str(chgtime)) fdir = os.path.dirname(filename) fh = logging.FileHandler(fdir + '\\placeimport.log') formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) LOG.addHandler(fh) LOG.info(" fdir = " + fdir) cout = fdir + "\\presult.csv" LOG.debug('ini file handling') config = configman.register_manager("importplaces") config.register("options.refstring", "r") config.load() config.save() # refstr = config.get('options.refstring') reftag = checkTagExistence('Referenssi').get_handle() ''' tags = {} # Dictionary tagtypes placetype: tag name tagTypes = {PlaceType.COUNTRY: "Referenssivaltio", PlaceType.STATE: "Referenssilääni", PlaceType.MUNICIPALITY: "Referenssikunta", PlaceType.VILLAGE: "Referenssikylä", PlaceType.FARM: "Referenssitila", PlaceType.BUILDING: "Referenssitalo"} for key, value in tagTypes.items(): tags[key] = checkTagExistence(value).get_handle() ''' all_countries = get_level0(db) recno = 0 try: with open(cout, 'w', newline = '\n', encoding="utf-8-sig") as csv_out: r_writer = csv.writer(csv_out, delimiter=';') with open(filename, 'r', encoding="utf-8-sig") as t_in: # rhandle = None phandle = None t_dialect = csv.Sniffer().sniff(t_in.read(1024)) t_in.seek(0) t_reader = csv.reader(t_in, t_dialect) LOG.info('CSV input file delimiter is ' + t_dialect.delimiter) for row in t_reader: recno += 1 rectype = row[5] # Record type = Gramps place type name (fi_FI) # LOG.debug('Row type: -' + row[0] + '-') if recno == 1: LOG.debug('First row: ' + row[0]) h_count += 1 r_writer.writerow([row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7]]) else: idno = row[4] # Possibly previously assigned Gramps object id handle = row[7].strip('"') # Possibly previously assigned Gramps object handle if rectype in ('Valtio', 'Country'): priName, altNames = parseNames(row[0]) country_count += 1 result = None if idno != '': result = findPlace(idno, priName[0]) else: result = checkPlaceDuplicate(priName[0], all_countries) if result != None: LOG.debug('Country row is a duplicate of ' + result.get_name().get_value() + ' and updates the existing one)') country = result country.set_alternative_names(altNames) with DbTxn(_("Update Country"), db) as trans: db.commit_place(country, trans) else: country = addPlace(priName, altNames, PlaceType.COUNTRY) municipalities_of_current_country = [] for cname, handle in db.find_backlink_handles(country.get_handle(), ['Place']): municipalities_of_current_country.append(db.get_place_from_handle(handle)) chandle = country.get_handle() cidno = country.get_gramps_id() try: r_writer.writerow([row[0], row[1], row[2], row[3], cidno, row[5], row[6], chandle]) except IOError: LOG.error('Error writing country-csv ' + IOError.strerror) LOG.debug('Old municipalities ' + str(len(municipalities_of_current_country))) elif rectype in ('Kunta', 'Municipality', 'Kaupunki', 'Town'): priName, altNames = parseNames(row[1]) LOG.debug('Municipality/Town row: ' + priName[0]) municipality_count += 1 result = None if idno != '': result = findPlace(idno, priName[0]) else: result = checkPlaceDuplicate(priName[0], municipalities_of_current_country) if result != None: LOG.debug('Municipality row is a duplicate of ' + result.get_name().get_value() + ' and updates the existing one)') municipality = result municipality.set_alternative_names(altNames) with DbTxn(_("Update Municipality"), db) as trans: db.commit_place(municipality, trans) else: if rectype in ('Kunta', 'Municipality'): municipality = addPlace(priName, altNames, PlaceType.MUNICIPALITY, country) else: municipality = addPlace(priName, altNames, PlaceType.TOWN, country) municipalities_of_current_country.append(municipality) villages_of_current_municipality = [] for vname, handle in db.find_backlink_handles(municipality.get_handle(), ['Place']): villages_of_current_municipality.append(db.get_place_from_handle(handle)) mhandle = municipality.get_handle() midno = municipality.get_gramps_id() try: r_writer.writerow([row[0], row[1], row[2], row[3], midno, row[5], row[6], mhandle]) except IOError: LOG.error('Error writing municipality-csv ' + IOError.strerror) LOG.debug('Old municipalities ' + str(len(municipalities_of_current_country))) elif rectype in ('Kylä', 'Village'): priName, altNames = parseNames(row[2]) LOG.debug('Village row: ' + priName[0]) village_count += 1 if idno != '': result = findPlace(idno, priName[0]) else: result = checkPlaceDuplicate(priName[0], villages_of_current_municipality) if result != None: LOG.debug('Village row is a duplicate of ' + result.get_name().get_value() + ' and updates the existing one)') village = result village.set_alternative_names(altNames) with DbTxn(_("Update Village"), db) as trans: db.commit_place(village, trans) else: village = addPlace(priName, altNames, PlaceType.VILLAGE, municipality) villages_of_current_municipality.append(village) farms_of_current_village = [] for fname, handle in db.find_backlink_handles(village.get_handle(), ['Place']): farms_of_current_village.append(db.get_place_from_handle(handle)) vhandle = village.get_handle() vidno = village.get_gramps_id() try: r_writer.writerow([row[0], row[1], row[2], row[3], vidno, row[5], row[6], vhandle]) except IOError: LOG.error('Error writing village-csv ' + IOError.strerror) LOG.debug('Old villages ' + str(len(villages_of_current_municipality))) elif rectype in ('Tila', 'Farm'): priName, altNames = parseNames(row[3]) LOG.debug('Farme row: ' + priName[0]) result = None farm_count += 1 if handle != '': result = findPlace(idno, priName[0]) else: result = checkPlaceDuplicate(priName[0], farms_of_current_village) if result != None: LOG.debug('Farm row is a duplicate of ' + result.get_name().get_value() + ' and updates the existing one)') farm = result farm.set_alternative_names(altNames) with DbTxn(_("Update Farm"), db) as trans: db.commit_place(farm, trans) else: farm = addPlace(priName, altNames, PlaceType.FARM, village) farms_of_current_village.append(farm) buildings_of_current_farm = [] for bname, handle in db.find_backlink_handles(farm.get_handle(), ['Place']): buildings_of_current_farm.append(db.get_place_from_handle(handle)) fhandle = farm.get_handle() fidno = farm.get_gramps_id() try: r_writer.writerow([row[0], row[1], row[2], row[3], fidno, row[5], row[6], fhandle]) except IOError: LOG.error('Error writing farm-csv ' + IOError.strerror) LOG.debug('Old farmss ' + str(len(farms_of_current_village))) elif rectype in ('Rakennus', 'Building'): priName, altNames = parseNames(row[4]) LOG.debug('Building row: ' + priName[0]) result = None building_count += 1 if handle != '': result = findPlace(idno, priName[0]) else: result = checkPlaceDuplicate(priName[0], buildings_of_current_farm) if result != None: LOG.debug('Building row is a duplicate of ' + result.get_name().get_value() + ' and updates the existing one)') building = result # &TODO: some updating with DbTxn(_("Update Farm"), db) as trans: db.commit_place(building, trans) else: building = addPlace(priName, altNames, PlaceType.BUILDING, farm) buildings_of_current_farm.append(building) bhandle = building.get_handle() bidno = building.get_gramps_id() try: r_writer.writerow([row[0], row[1], row[2], row[3], bidno, row[5], row[6], bhandle]) except IOError: LOG.error('Error writing building-csv ' + IOError.strerror) LOG.debug('Old buildings ' + str(len(buildings_of_current_farm))) else: unknown_count += 1 LOG.error('Unknown rectype on line ' + str(recno) + ': ' + rectype) raise GrampsImportError('Unknown record type ' + rectype) except: exc = sys.exc_info()[0] LOG.error('*** Something went really wrong! ', exc ) return ImportInfo({_('Results'): _('Something went really wrong ')}) results = { _('Results'): _('Input file handled.') , _(' Countries '): str(country_count) , _(' Municipalities '): str(municipality_count) , _(' Villages '): str(village_count) , _(' Farms '): str(farm_count) , _(' Buildings '): str(building_count) , _(' Unknown types '): str(unknown_count) , _(' Total '): str(country_count + municipality_count + village_count + farm_count + building_count + unknown_count) } LOG.info('Input file handled, ' + str(recno) + ' rows') LOG.info(' Countries ' + str(country_count)) LOG.info(' Municipalities ' + str(municipality_count)) LOG.info(' Villages ' + str(village_count)) LOG.info(' Farms ' + str(farm_count)) LOG.info(' Buildings ' + str(building_count)) LOG.info(' Unknown types ' + str(unknown_count)) LOG.info(' Total ' + str(country_count + municipality_count + village_count + farm_count + building_count + unknown_count)) db.enable_signals() db.request_rebuild() return ImportInfo(results)
from gramps.gen.utils.file import search_for try: import gi gi.require_version('GooCanvas', '2.0') from gi.repository import GooCanvas _GOO = True except (ImportError, ValueError): _GOO = False if os.sys.platform == "win32": _DOT = search_for("dot.exe") else: _DOT = search_for("dot") if not (_GOO and _DOT): from gramps.gen.config import config inifile = config.register_manager("graphviewwarn") inifile.load() sects = inifile.get_sections() if(_GOO and _DOT or locals().get('build_script') or 'graphviewwarn' not in sects): if locals().get('uistate'): # don't start GUI if in CLI mode, just ignore from gi.repository import Gtk, GdkPixbuf from gramps.gen.const import USER_PLUGINS fname = os.path.join(USER_PLUGINS, 'GraphView') icons = Gtk.IconTheme().get_default() icons.append_search_path(fname) register(VIEW, id = 'graphview', name = _("Graph View"),
from gramps.gui.editors import EditPerson from gramps.gui.editors import EditPlace from gramps.gui.editors import EditRepository from gramps.gui.editors import EditSource from gramps.gen.config import config as configman # ------------------------------------------------------------------------- # # Local modules # # ------------------------------------------------------------------------- import supertool_engine as engine import supertool_genfilter as genfilter config = configman.register_manager("supertool") config.register("defaults.include_location","") CATEGORIES = [ "People", "Families", "Events", "Places", "Citations", "Sources", "Repositories", "Media", "Notes", ] def gentolist(orig):
#--------------------------------------------------------------- from gramps.gui.display import display_url from gramps.gen.const import GRAMPS_LOCALE as glocale try: _trans = glocale.get_addon_translator(__file__) except ValueError: _trans = glocale.translation _ = _trans.gettext from gramps.gen.config import config as configman #--------------------------------------------------------------- # # Local config and functions # #--------------------------------------------------------------- config = configman.register_manager("libwebconnect") # "leave alone", "separate", or "remove": config.register("behavior.middle-name", "remove") config.load() config.save() def escape(text): """ Turn spaces into + symbols. """ text = str(text).replace(" ", "+") return text def make_callback(key, name): """ Decorator for web connect callbacks. Adds the key and name for the
def importSourceHierarchies(db, filename, user): def findNextRidno(ridstrt): with DbTxn(_("Find next ridno"), db): prefix_save = db.get_repository_prefix() db.set_repository_id_prefix(ridstrt + '%05d') next_ridno = db.find_next_repository_gramps_id() LOG.debug('Next ridno = ' + next_ridno) db.set_repository_id_prefix(prefix_save) return next_ridno def findNextSidno(ridno): with DbTxn(_("Find next sidno"), db): prefix_save = db.get_source_prefix() db.set_source_id_prefix(ridno + '%05d') next_sidno = db.find_next_source_gramps_id() LOG.debug('Next sidno = ' + next_sidno) db.set_source_id_prefix(prefix_save) return next_sidno def checkTagExistence(otext): with DbTxn(_("Read Tag"), db): tag = db.get_tag_from_name(otext) if tag != None: LOG.debug('Tag found by name, no duplicates: ' + otext + ' ' + tag.get_name()) else: tag = Tag() tag.set_name(otext) tag.set_color("#EF2929") with DbTxn(_("Add Tag"), db) as trans: thandle = db.add_tag(tag, trans) LOG.debug('Tag added: ' + tag.get_name() + ' ' + thandle) return tag fdir = os.path.dirname(filename) fh = logging.FileHandler(fdir + '\\sourceimport.log') formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) LOG.addHandler(fh) LOG.info(" fdir = " + fdir) cout = fdir + "\\sresult.csv" LOG.debug('ini file handling') config = configman.register_manager("importsources") ''' config.register("options.repositoryidrng", "1000") config.register("options.repositoryincr", "1") config.register("options.sourceidrng", "1000") config.register("options.sourceidincr", "1") ''' config.register("options.refstring", "r") config.load() config.save() ''' repository_idrange = int(config.get('options.repositoryidrng')) repository_incr = int(config.get('options.repositoryincr')) source_idrange = int(config.get('options.sourceidrng')) source_idincr = int(config.get('options.sourceidincr')) ''' refstr = config.get('options.refstring') ''' repository_idno = 0 source_idno = 0 ''' t_count = 0 r_count = 0 s_count = 0 c_count = 0 u_count = 0 ridno = None sidno = None reftext = 'Referenssi' reftag = checkTagExistence(reftext) chgtime = int(time.time()) LOG.info(" chgtime = " + str(chgtime)) try: with open(cout, 'w', newline='\n', encoding="utf-8-sig") as csv_out: # csv_out.write(u'\uFEFF') # utf-8-bom r_writer = csv.writer(csv_out, delimiter=';') with open(filename, 'r', encoding="utf-8-sig") as t_in: rhandle = None t_dialect = csv.Sniffer().sniff(t_in.read(1024)) t_in.seek(0) t_reader = csv.reader(t_in, t_dialect) LOG.info('CSV input file delimiter is ' + t_dialect.delimiter) for row in t_reader: rectype = row[ 0] # Record type = Gramps object id prefix character # LOG.debug('Row type: -' + row[0] + '-') if rectype == '#': LOG.debug('Comment row: ' + row[0]) c_count += 1 r_writer.writerow([ row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7] ]) else: idno = row[ 2] # Possibly previously assigned Gramps object id handle = row[3].strip( '"' ) # Possibly previously assigned Gramps object handle otext = row[4].strip() LOG.debug('Handle = ' + handle) ''' if rectype == 'T': LOG.debug('Tag row: ' + row[0]) thandle = '' t_count += 1 recobj = row[1] # Tag related to repositories or sources tag = None with DbTxn(_("Read Tag"), db): tag = db.get_tag_from_name(otext) if tag != None: LOG.info('Tag found by name, no duplicates: ' + otext + ' ' + tag.get_name()) thandle = tag.get_handle() else: tag = Tag() tag.set_name(otext) tag.set_change_time(chgtime) tag.set_color("#EF2929") with DbTxn(_("Add Tag"), db) as trans: thandle = db.add_tag(tag, trans) LOG.info('Tag added: ' + tag.get_name() + ' ' + thandle) tags[recobj] = tag try: r_writer.writerow([rectype, recobj, '', '"' + thandle + '"', otext, '', '', '', '']) except IOError: LOG.error('Error writing T-csv ' + IOError.strerror) ''' if rectype == 'R': LOG.debug('Repository row: ' + row[0]) rhandle = '' # source_idno = 0 r_count += 1 repotype = row[1] # repository type number if idno == '': if refstr == 'r': # repository type based numbering should be applied but not supplied by Gramps ridno = findNextRidno(rectype + refstr + '9') # repository_idno = repository_idno + repository_incr # ridno = rectype + refstr + str(int(repotype) * repository_idrange + repository_idno) else: ridno = db.find_next_repository_gramps_id() else: ridno = idno LOG.debug('Ridno = ' + str(ridno)) repository = Repository() if handle != '': with DbTxn(_("Read Repository"), db) as trans: repository = db.get_repository_from_handle( handle) if repository == None: LOG.error( 'Repository NOT found by handle: ' + handle + ' ' + otext) raise GrampsImportError( 'Repository NOT found by handle: ', handle + '/' + otext) repositoryType = RepositoryType() repositoryType.set(int(repotype)) repository.set_type(repositoryType) repository.set_gramps_id(ridno) repository.set_name(otext) repository.set_change_time(chgtime) if reftag != None: repository.add_tag(reftag.get_handle()) if handle == '': with DbTxn(_("Add Repository"), db) as trans: rhandle = db.add_repository( repository, trans) else: with DbTxn(_("Update Repository"), db) as trans: db.commit_repository(repository, trans) rhandle = handle try: r_writer.writerow([ rectype, repotype, ridno, '"' + rhandle + '"', otext, '', '', '', '' ]) except IOError: LOG.error('Error writing R-csv ' + IOError.strerror) elif rectype == 'S': LOG.debug('Source row: ' + row[0]) shandle = '' sidno = '' s_count += 1 attribs = (row[5], row[6], row[7]) if idno == '': LOG.debug('Ridno for sidno = ' + str(ridno)) if refstr == 'r': # repository type based numbering should be applied but not supplied by Gramps sidno = findNextSidno(rectype + refstr + '9') # source_idno = source_idno + source_idincr # sidno = rectype + refstr + str((int(repotype) * repository_idrange + repository_idno) * source_idrange + source_idno) else: sidno = db.find_next_source_gramps_id() else: sidno = idno LOG.debug('Sidno = ' + str(sidno)) source = Source() if handle != '': with DbTxn(_("Read Source"), db) as trans: source = db.get_source_from_handle(handle) if source == None: LOG.error( 'Source NOT found by handle: ' + handle + ' ' + otext) raise GrampsImportError( 'Source NOT found by handle: ', handle + '/' + otext) source.set_gramps_id(sidno) source.set_title(otext) source.set_author(attribs[0]) source.set_publication_info(attribs[1]) source.set_abbreviation(attribs[2]) if reftag != None: source.add_tag(reftag.get_handle()) repoRef = RepoRef() repoRef.set_reference_handle(rhandle) source.add_repo_reference(repoRef) source.set_change_time(chgtime) if handle == '': with DbTxn(_("Add Source"), db) as trans: shandle = db.add_source(source, trans) else: with DbTxn(_("Update Source"), db) as trans: db.commit_source(source, trans) shandle = handle try: r_writer.writerow([ rectype, '', sidno, '"' + shandle + '"', otext, attribs[0], attribs[1], attribs[2], '' ]) except IOError: LOG.error('Error writing S-csv ' + IOError.strerror) else: u_count += 1 LOG.debug('Unknown rectype: ' + rectype) raise GrampsImportError('Unknown record type ' + rectype) except: exc = sys.exc_info()[0] LOG.error('*** Something went really wrong! ', exc) return ImportInfo({_('Results'): _('Something went really wrong ')}) results = { _('Results'): _('Input file handled.'), _(' Repositories '): str(r_count), _(' Sources '): str(s_count), _(' Comments '): str(c_count), _(' Unknown types '): str(u_count), _(' Total '): str(t_count + r_count + s_count + c_count + u_count) } LOG.info('Input file handled.') LOG.info(' Repositories ' + str(r_count)) LOG.info(' Sources ' + str(s_count)) LOG.info(' Comments ' + str(c_count)) LOG.info(' Unknown types ' + str(u_count)) LOG.info(' Total ' + str(t_count + r_count + s_count + c_count + u_count)) db.enable_signals() db.request_rebuild() return ImportInfo(results)
# Prefixes for family attributes. GROOM = _('Groom') BRIDE = _('Bride') # Files which may contain form definitions definition_files = [ 'form_be.xml', 'form_ca.xml', 'form_dk.xml', 'form_fr.xml', 'form_gb.xml', 'form_pl.xml', 'form_us.xml', 'test.xml', 'custom.xml' ] #------------------------------------------------------------------------ # # Configuration file # #------------------------------------------------------------------------ CONFIG = config.register_manager('form') CONFIG.register('interface.form-width', 600) CONFIG.register('interface.form-height', 400) CONFIG.register('interface.form-horiz-position', -1) CONFIG.register('interface.form-vert-position', -1) CONFIG.init() #------------------------------------------------------------------------ # # From class # #------------------------------------------------------------------------ class Form(): """
#------------------------------------------------------------------------- # # face detection module # #------------------------------------------------------------------------- sys.path.append(os.path.abspath(os.path.dirname(__file__))) import facedetection #------------------------------------------------------------------------- # # configuration # #------------------------------------------------------------------------- GRAMPLET_CONFIG_NAME = "phototagginggramplet" CONFIG = config.register_manager(GRAMPLET_CONFIG_NAME) CONFIG.register("detection.box_size", (50,50)) CONFIG.register("detection.inside_existing_boxes", False) CONFIG.register("selection.replace_without_asking", False) CONFIG.load() CONFIG.save() MIN_FACE_SIZE = CONFIG.get("detection.box_size") REPLACE_WITHOUT_ASKING = CONFIG.get("selection.replace_without_asking") DETECT_INSIDE_EXISTING_BOXES = CONFIG.get("detection.inside_existing_boxes") def save_config(): CONFIG.set("detection.box_size", MIN_FACE_SIZE) CONFIG.set("detection.inside_existing_boxes", DETECT_INSIDE_EXISTING_BOXES) CONFIG.set("selection.replace_without_asking", REPLACE_WITHOUT_ASKING) CONFIG.save()
# #--------------------------------------------------------------- from gramps.gen.const import GRAMPS_LOCALE as glocale try: _trans = glocale.get_addon_translator(__file__) except ValueError: _trans = glocale.translation _ = _trans.gettext from gramps.gen.config import config as configman #--------------------------------------------------------------- # # Local config and functions # #--------------------------------------------------------------- config = configman.register_manager("libwebconnect") # "leave alone", "separate", or "remove": config.register("behavior.middle-name", "remove") config.load() config.save() def escape(text): """ Turn spaces into + symbols. """ text = str(text).replace(" ", "+") return text def make_callback(key, name):
version = '1.0.5', gramps_target_version='5.0', status=STABLE, fname='postgresql.py', databaseclass='PostgreSQL', authors=['Doug Blank'], authors_email=['*****@*****.**'] ) elif locals().get('uistate'): # don't start GUI if in CLI mode, just ignore from gramps.gen.config import config from gramps.gui.dialog import QuestionDialog2 from gramps.gen.config import logging if not module1: warn_msg = _("PostgreSQL Warning: Python psycopg2 module not found.") logging.log(logging.WARNING, warn_msg) inifile = config.register_manager("postgresqlwarn") inifile.load() sects = inifile.get_sections() if 'postgresqlwarn' not in sects: yes_no = QuestionDialog2(_("PostgreSQL Failed to Load"), _("\n\nPostgreSQL is missing the psycopg2 python module.\n" "For now, it may be possible to install the files manually. See\n\n" "https://gramps-project.org/wiki/index.php?title=PostgreSQL \n\n" "To dismiss all future PostgreSQL warnings click Dismiss."), _(" Dismiss "), _("Continue"), parent=uistate.window) prompt = yes_no.run() if prompt is True: inifile.register('postgresqlwarn.MissingModules', "") inifile.set('postgresqlwarn.MissingModules', "True") inifile.save()
# The attribute used to store the order of people on the census. ORDER_ATTR = _("Order") # The key of the data item in a source to define it as a census source. CENSUS_TAG = _("Census") # Files which may contain census definitions definition_files = ["census.xml", "test.xml", "custom.xml"] # ------------------------------------------------------------------------ # # Configuration file # # ------------------------------------------------------------------------ CONFIG = config.register_manager("census") CONFIG.register("interface.census-width", 600) CONFIG.register("interface.census-height", 400) CONFIG.init() # ------------------------------------------------------------------------ # # Census class # # ------------------------------------------------------------------------ class Census: """ A class to read census definitions from an XML file. """ def __init__(self):