Пример #1
0
    def generatehtmlversion(self):
        try:
            zaplunates = session['zaplunates']
        except RuntimeError:
            # accursed Windows10 non-fork() issue
            zaplunates = hipparchia.config['RESTOREMEDIALANDFINALSIGMA']
        except KeyError:
            # you don't have a session at all...
            # you can provoke this by using something like curl on the server
            zaplunates = False

        try:
            zapvees = session['zapvees']
        except RuntimeError:
            # accursed Windows10 non-fork() issue
            zapvees = hipparchia.config['FORCEUFORV']
        except KeyError:
            # you don't have a session at all...
            # you can provoke this by using something like curl on the server
            zapvees = False

        if zaplunates:
            self.markedup = attemptsigmadifferentiation(self.markedup)
        if hipparchia.config['FORCELUNATESIGMANOMATTERWHAT']:
            self.markedup = forcelunates(self.markedup)
        if hipparchia.config['DISTINCTGREEKANDLATINFONTS']:
            self.markedup = self.separategreekandlatinfonts()

        if zapvees:
            self.markedup = uforvoutsideofmarkup(self.markedup)

        # needs to happen after zapvees
        # smallcaps means: "Civitatem peregrinvs vsvrpans veneat" and not "Ciuitatem peregrinus usurpans ueneat"
        if re.search(self.smallcaps, self.markedup):
            vlswaplambda = lambda x: x.group(1) + x.group(2).replace(
                'u', 'v') + x.group(3)
            self.markedup = re.sub(self.smallcaps, vlswaplambda, self.markedup)

        self.fixhmuirrationaloragnization()
        self.hmuspanrewrite()
        self.hmufontshiftsintospans()
Пример #2
0
def dictionaryidsearch(language, entryid) -> JSON_STR:
	"""

	fed by /morphologychart/

	:param language:
	:param entryid:
	:return:
	"""

	knownlanguages = ['greek', 'latin']
	if language not in knownlanguages:
		language = 'greek'

	try:
		entryid = str(float(entryid))
	except ValueError:
		entryid = None

	wordobject = findentrybyid(language, entryid)

	if wordobject:
		oo = lexicalOutputObject(wordobject)
		entry = oo.generatelexicaloutput()

		if session['zaplunates']:
			entry = attemptsigmadifferentiation(entry)
			entry = abbreviatedsigmarestoration(entry)
	else:
		entry = '[nothing found in {lg} lexicon at ID value {x}]'.format(lg=language, x=entryid)

	returndict = dict()
	returndict['newhtml'] = entry
	returndict['newjs'] = '\n'.join([dictionaryentryjs(), insertlexicalbrowserjs()])

	jsondict = json.dumps(returndict)

	return jsondict
    def generatelexicaloutput(self, countervalue=None) -> str:
        divtemplate = '<div id="{wd}_{idx}">\n{entry}\n</div>'
        if countervalue:
            headingstr = '<hr /><p class="dictionaryheading" id={wd}_{wordid}>({cv})&nbsp;{ent}'
        else:
            headingstr = '<hr /><p class="dictionaryheading" id={wd}_{wordid}>{ent}'
        metricsstr = '&nbsp;<span class="metrics">[{me}]</span>'
        codestr = '&nbsp;<code>[ID: {wordid}]</code>'
        xrefstr = '&nbsp;<code>[XREF: {xref}]</code>'

        navtemplate = """
		<table class="navtable">
		<tr>
			<td class="alignleft">
				<span class="label">Previous: </span>
				<dictionaryidsearch entryid="{pid}" language="{lg}">{p}</dictionaryidsearch>
			</td>
			<td>&nbsp;</td>
			<td class="alignright">
				<span class="label">Next: </span>
				<dictionaryidsearch entryid="{nid}" language="{lg}">{n}</dictionaryidsearch>
			</td>
		<tr>
		</table>
		"""

        w = self.thiswordobject
        if w.isgreek():
            language = 'greek'
        else:
            language = 'latin'

        outputlist = list()
        outputlist.append(
            headingstr.format(ent=w.entry,
                              cv=countervalue,
                              wordid=w.id,
                              wd=self.thisheadword))

        if w.metricalentry != w.entry:
            outputlist.append(metricsstr.format(me=w.metricalentry))

        if session['debuglex']:
            outputlist.append(codestr.format(wordid=w.id))
            xref = findparserxref(w)
            outputlist.append(xrefstr.format(xref=xref))
        outputlist.append('</p>')

        outputlist.append(self.entrysprincipleparts)
        outputlist.append(self.entrydistributions)
        outputlist.append(self.entrysummary)
        outputlist.append(self.fullenty)

        outputlist.append(
            navtemplate.format(pid=w.preventryid,
                               p=w.preventry,
                               nid=w.nextentryid,
                               n=w.nextentry,
                               lg=language))

        fullentry = '\n'.join(outputlist)

        if session['zaplunates']:
            fullentry = attemptsigmadifferentiation(fullentry)

        fullentry = divtemplate.format(wd=self.thisheadword,
                                       idx=findparserxref(w),
                                       entry=fullentry)
        return fullentry
Пример #4
0
def dictsearch(searchterm) -> JSON_STR:
	"""
	look up words
	return dictionary entries
	json packing
	:return:
	"""
	returndict = dict()

	searchterm = searchterm[:hipparchia.config['MAXIMUMLEXICALLENGTH']]
	probeforsessionvariables()

	dbconnection = ConnectionObject()
	dbcursor = dbconnection.cursor()

	if hipparchia.config['UNIVERSALASSUMESBETACODE']:
		searchterm = replacegreekbetacode(searchterm.upper())

	allowedpunct = '^$.'
	seeking = depunct(searchterm, allowedpunct)
	seeking = seeking.lower()
	seeking = re.sub('[σς]', 'ϲ', seeking)
	stripped = stripaccents(seeking)

	# don't turn 'injurius' into '[iiII]n[iiII][uuVV]r[iiII][uuVV]s'
	# that will happen if you call stripaccents() prematurely
	stripped = re.sub(r'[uv]', '[uvUV]', stripped)
	stripped = re.sub(r'[ij]', '[ijIJ]', stripped)

	if re.search(r'[a-z]', seeking):
		usedictionary = 'latin'
		usecolumn = 'entry_name'
	else:
		usedictionary = 'greek'
		usecolumn = 'unaccented_entry'

	if not session['available'][usedictionary + '_dictionary']:
		returndict['newhtml'] = 'cannot look up {w}: {d} dictionary is not installed'.format(d=usedictionary, w=seeking)
		return json.dumps(returndict)

	if not session['available'][usedictionary + '_dictionary']:
		returndict['newhtml'] = 'cannot look up {w}: {d} dictionary is not installed'.format(d=usedictionary, w=seeking)
		return json.dumps(returndict)

	limit = hipparchia.config['CAPONDICTIONARYFINDS']

	foundtuples = headwordsearch(stripped, limit, usedictionary, usecolumn)

	# example:
	# results are presorted by ID# via the postgres query
	# foundentries [('scrofa¹', 43118), ('scrofinus', 43120), ('scrofipascus', 43121), ('Scrofa²', 43119), ('scrofulae', 43122)]

	returnlist = list()

	if len(foundtuples) == limit:
		returnlist.append('[stopped searching after {lim} finds]<br>'.format(lim=limit))

	if len(foundtuples) > 0:

		if len(foundtuples) == 1:
			# sending '0' to browserdictionarylookup() will hide the count number
			usecounter = False
		else:
			usecounter = True

		wordobjects = [probedictionary(setdictionarylanguage(f[0]) + '_dictionary', 'entry_name', f[0], '=', dbcursor=dbcursor, trialnumber=0) for f in foundtuples]
		wordobjects = flattenlistoflists(wordobjects)
		outputobjects = [lexicalOutputObject(w) for w in wordobjects]

		# very top: list the finds
		if usecounter:
			findstemplate = '({n})&nbsp;<a class="nounderline" href="#{w}_{wdid}">{w}</a>'
			findslist = [findstemplate.format(n=f[0]+1, w=f[1][0], wdid=f[1][1]) for f in enumerate(foundtuples)]
			returnlist.append('\n<br>\n'.join(findslist))

		# the actual entries
		count = 0
		for oo in outputobjects:
			count += 1
			if usecounter:
				entry = oo.generatelexicaloutput(countervalue=count)
			else:
				entry = oo.generatelexicaloutput()
			returnlist.append(entry)
	else:
		returnlist.append('[nothing found]')

	if session['zaplunates']:
		returnlist = [attemptsigmadifferentiation(x) for x in returnlist]
		returnlist = [abbreviatedsigmarestoration(x) for x in returnlist]

	returndict['newhtml'] = '\n'.join(returnlist)
	returndict['newjs'] = '\n'.join([dictionaryentryjs(), insertlexicalbrowserjs()])

	jsondict = json.dumps(returndict)

	dbconnection.connectioncleanup()

	return jsondict
Пример #5
0
def knownforms(language, lexicalid, xrefid, headword) -> JSON_STR:
	"""

	display all known forms of...

	you are supposed to be sent here via the principle parts click from a lexical entry

	this means you have access to a BaseFormMorphology() object

	that is how/why you know the paramaters already

	:param xrefid:
	:return:
	"""

	# sanitize all input...

	headword = headword[:hipparchia.config['MAXIMUMLEXICALLENGTH']]

	knownlanguages = ['greek', 'latin']
	if language not in knownlanguages:
		language = 'greek'

	try:
		lexicalid = str(float(lexicalid))
	except ValueError:
		lexicalid = 'invalid_user_input'

	try:
		xrefid = str(int(xrefid))
	except ValueError:
		xrefid = 'invalid_user_input'

	headword = depunct(headword)
	headword = re.sub(r'[σς]', 'ϲ', headword)

	try:
		bfo = BaseFormMorphology(headword, xrefid, language, lexicalid, session)
	except:
		consolewarning('could not initialize BaseFormMorphology() object')
		return 'could not initialize BaseFormMorphology() object'

	# if this is active a click on the word will do a lemmatized lookup of it
	# topofoutput = """
	# <div class="center">
	# 	<span class="verylarge">All known forms of <lemmatizable headform="{w}">{w}</lemmatizable></span>
	# </div>
	# """

	# if this is active a clock on the word will return you to the dictionary entry for it
	topofoutput = """
	<div class="center">
		<span class="verylarge">All known forms of <dictionaryidsearch entryid="{eid}" language="{lg}">{w}</dictionaryidsearch></span>
	</div>
	"""

	returnarray = list()

	if bfo.iammostlyconjugated():
		returnarray.append(topofoutput.format(w=bfo.headword, eid=bfo.lexicalid, lg=bfo.language))
		returnarray = returnarray + bfo.buildhtmlverbtablerows(session)

	if bfo.iamdeclined():
		returnarray.append(topofoutput.format(w=bfo.headword, eid=bfo.lexicalid, lg=bfo.language))
		returnarray = returnarray + bfo.buildhtmldeclinedtablerows()

	returndict = dict()
	returndict['newhtml'] = '\n'.join(returnarray)
	returndict['newjs'] = morphologychartjs()

	if session['zaplunates']:
		returndict['newhtml'] = attemptsigmadifferentiation(returndict['newhtml'])
		returndict['newhtml'] = abbreviatedsigmarestoration(returndict['newhtml'])

	jsondict = json.dumps(returndict)

	return jsondict