File: gmMatchProvider.py

package info (click to toggle)
gnumed-server 21.11-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 45,408 kB
  • ctags: 3,891
  • sloc: sql: 1,210,640; python: 13,526; sh: 1,476; makefile: 19
file content (577 lines) | stat: -rw-r--r-- 19,142 bytes parent folder | download | duplicates (2)
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

__doc__ = """Base classes for match providers.

They are used by business objects to give
phrasewheels the ability to guess phrases.

Copyright (C) GNUMed developers
license: GPL v2 or later
"""
__author__  = "K.Hilbert <Karsten.Hilbert@gmx.net>, I.Haywood <ihaywood@gnu.org>, S.J.Tan <sjtan@bigpond.com>"

# std lib
import sys
import logging
import re as regex
import datetime as pydt


# GNUmed
if __name__ == "__main__":
	sys.path.insert(0, '../../')
from Gnumed.pycommon import gmPG2


_log = logging.getLogger('gm.ui')


# these are stripped from the fragment passed to the
# match provider before looking for matches:
default_ignored_chars = "[?!.'\\(){}\[\]<>~#*$%^_]+" + '"'

# these are used to detect word boundaries which is,
# in turn, used to normalize word boundaries in the
# input fragment
default_word_separators = '[- \t=+&:@]+'
#============================================================
class cMatchProvider(object):
	"""Base class for match providing objects.

	Match sources might be:
	- database tables
	- flat files
	- previous input
	- config files
	- in-memory list created on the fly
	"""
	print_queries = False
	#--------------------------------------------------------
	def __init__(self):
		self.setThresholds()

		self._context_vals = {}
		self.__ignored_chars = regex.compile(default_ignored_chars)
		# used to normalize word boundaries:
		self.__word_separators = regex.compile(default_word_separators)
	#--------------------------------------------------------
	# actions
	#--------------------------------------------------------
	def getMatches(self, aFragment = None):
		"""Return matches according to aFragment and matching thresholds.

		FIXME: design decision: we dont worry about data source changes
			   during the lifetime of a MatchProvider
		FIXME: append _("*get all items*") on truncation
		"""
		# sanity check
		if aFragment is None:
			raise ValueError, 'Cannot find matches without a fragment.'

		# user explicitly wants all matches
		if aFragment == u'*':
			return self.getAllMatches()

		# case insensitivity
		tmpFragment = aFragment.lower()
		# remove ignored chars
		if self.__ignored_chars is not None:
			tmpFragment = self.__ignored_chars.sub('', tmpFragment)
		# normalize word separators
		if self.__word_separators is not None:
			tmpFragment = u' '.join(self.__word_separators.split(tmpFragment))
		# length in number of significant characters only
		lngFragment = len(tmpFragment)

		# order is important !
		if lngFragment >= self.__threshold_substring:
			return self.getMatchesBySubstr(tmpFragment)
		elif lngFragment >= self.__threshold_word:
			return self.getMatchesByWord(tmpFragment)
		elif lngFragment >= self.__threshold_phrase:
			return self.getMatchesByPhrase(tmpFragment)
		else:
			return (False, [])
	#--------------------------------------------------------
	def getAllMatches(self):
		raise NotImplementedError
	#--------------------------------------------------------
	def getMatchesByPhrase(self, aFragment):
		raise NotImplementedError
	#--------------------------------------------------------
	def getMatchesByWord(self, aFragment):
		raise NotImplementedError
	#--------------------------------------------------------
	def getMatchesBySubstr(self, aFragment):
		raise NotImplementedError
	#--------------------------------------------------------
	def get_match_by_data(self, data=None):
		return None
	#--------------------------------------------------------
	# configuration
	#--------------------------------------------------------
	def setThresholds(self, aPhrase = 1, aWord = 3, aSubstring = 5):
		"""Set match location thresholds.

		- the fragment passed to getMatches() must contain at least this many
		  characters before it triggers a match search at:
		  1) phrase_start - start of phrase (first word)
		  2) word_start - start of any word within phrase
		  3) in_word - _inside_ any word within phrase
		"""
		# sanity checks
		if aSubstring < aWord:
			_log.error('Setting substring threshold (%s) lower than word-start threshold (%s) does not make sense. Retaining original thresholds (%s:%s, respectively).' % (aSubstring, aWord, self.__threshold_substring, self.__threshold_word))
			return False
		if aWord < aPhrase:
			_log.error('Setting word-start threshold (%s) lower than phrase-start threshold (%s) does not make sense. Retaining original thresholds (%s:%s, respectively).' % (aSubstring, aWord, self.__threshold_word, self.__threshold_phrase))
			return False

		# now actually reassign thresholds
		self.__threshold_phrase	= aPhrase
		self.__threshold_word	= aWord
		self.__threshold_substring	= aSubstring

		return True
	#--------------------------------------------------------
	def _set_word_separators(self, word_separators=None):
		if word_separators is None:
			self.__word_separators = None
		else:
			self.__word_separators = regex.compile(word_separators)

	def _get_word_separators(self):
		if self.__word_separators is None:
			return None
		return self.__word_separators.pattern

	word_separators = property(_get_word_separators, _set_word_separators)
	#--------------------------------------------------------
	def _set_ignored_chars(self, ignored_chars=None):
		if ignored_chars is None:
			self.__ignored_chars = None
		else:
			self.__ignored_chars = regex.compile(ignored_chars)

	def _get_ignored_chars(self):
		if self.__ignored_chars is None:
			return None
		return self.__ignored_chars.pattern

	ignored_chars = property(_get_ignored_chars, _set_ignored_chars)
	#--------------------------------------------------------
	def set_context (self, context=None, val=None):
		"""Set value to provide context information	for matches.

		The matching code may ignore it depending on its exact
		implementation. Names and values of the context depend
		on what is being matched.

		<context> -- the *placeholder* key *inside* the context
					 definition, not the context *definition* key
		"""
		if context is None:
			return False
		self._context_vals[context] = val
		return True
	#--------------------------------------------------------
	def unset_context(self, context=None):
		try:
			del self._context_vals[context]
		except KeyError:
			pass
#------------------------------------------------------------
# usable instances
#------------------------------------------------------------
class cMatchProvider_FixedList(cMatchProvider):
	"""Match provider where all possible options can be held
	   in a reasonably sized, pre-allocated list.
	"""
	def __init__(self, aSeq = None):
		"""aSeq must be a list of dicts. Each dict must have the keys (data, label, weight)
		"""
		if not type(aSeq) in [type(None), type([]), type(())]:
			_log.error('fixed list match provider argument must be a list/tuple of dicts/None')
			raise TypeError('fixed list match provider argument must be a list/tuple of dicts/None')

		self.__items = aSeq
		cMatchProvider.__init__(self)
	#--------------------------------------------------------
	# internal matching algorithms
	#
	# if we end up here:
	#	- aFragment will not be "None"
	#   - aFragment will be lower case
	#	- we _do_ deliver matches (whether we find any is a different story)
	#--------------------------------------------------------
	def getMatchesByPhrase(self, aFragment):
		"""Return matches for aFragment at start of phrases."""
		matches = []
		# look for matches
		for item in self.__items:
			# at start of phrase, that is
			if item['list_label'].lower().startswith(aFragment.lower()):
				matches.append(item)
		# no matches found
		if len(matches) == 0:
			return (False, [])

		matches.sort(self.__cmp_items)
		return (True, matches)
	#--------------------------------------------------------
	def getMatchesByWord(self, aFragment):
		"""Return matches for aFragment at start of words inside phrases."""
		matches = []
		# look for matches
		for item in self.__items:
			item_label = item['list_label'].lower()
			fragment_pos = item_label.find(aFragment.lower())
			# found at start of phrase
			if fragment_pos == 0:
				matches.append(item)
			# found as a true substring
			elif fragment_pos > 0:
				# but use only if substring is at start of a word
				if item_label[fragment_pos-1] == u' ':
					matches.append(item)
		# no matches found
		if len(matches) == 0:
			return (False, [])

		matches.sort(self.__cmp_items)
		return (True, matches)
	#--------------------------------------------------------
	def getMatchesBySubstr(self, aFragment):
		"""Return matches for aFragment as a true substring."""
		matches = []
		# look for matches
		for item in self.__items:
			if item['list_label'].lower().find(aFragment.lower()) != -1:
				matches.append(item)
		# no matches found
		if len(matches) == 0:
			return (False, [])

		matches.sort(self.__cmp_items)
		return (True, matches)
	#--------------------------------------------------------
	def getAllMatches(self):
		"""Return all items."""
		matches = self.__items
		# no matches found
		if len(matches) == 0:
			return (False, [])

		matches.sort(self.__cmp_items)
		return (True, matches)
	#--------------------------------------------------------
	def set_items(self, items):
		"""items must be a list of dicts. Each dict must have the keys (data, list_label, weight)"""
		self.__items = items
	#--------------------------------------------------------
	def __cmp_items(self, item1, item2):
		"""Compare items based on weight."""
		if item1['weight'] == item2['weight']:
			return 0

		# do it the wrong way round to do sorting/reversing at once
		if item1['weight'] < item2['weight']:
			return 1
		if item1['weight'] > item2['weight']:
			return -1
# ===========================================================
class cMatchProvider_Func(cMatchProvider):
	"""Match provider which searches matches
	   in the results of a function call.
	"""
	def __init__(self, get_candidates = None):
		"""get_candidates() must return a list of strings."""
		if get_candidates is None:
			_log.error('must define function to retrieve match candidates list')
			raise ValueError('must define function to retrieve match candidates list')

		self._get_candidates = get_candidates
		cMatchProvider.__init__(self)
	#--------------------------------------------------------
	# internal matching algorithms
	#
	# if we end up here:
	#	- aFragment will not be "None"
	#   - aFragment will be lower case
	#	- we _do_ deliver matches (whether we find any is a different story)
	#--------------------------------------------------------
	def getMatchesByPhrase(self, aFragment):
		"""Return matches for aFragment at start of phrases."""
		matches = []
		candidates = self._get_candidates()
		# look for matches
		for candidate in candidates:
			# at start of phrase, that is
			if aFragment.startswith(candidate['list_label'].lower()):
				matches.append(candidate)
		# no matches found
		if len(matches) == 0:
			return (False, [])

		matches.sort(self.__cmp_candidates)
		return (True, matches)
	#--------------------------------------------------------
	def getMatchesByWord(self, aFragment):
		"""Return matches for aFragment at start of words inside phrases."""
		matches = []
		candidates = self._get_candidates()
		# look for matches
		for candidate in candidates:
			pos = candidate['list_label'].lower().find(aFragment)
#			pos = string.find(string.lower(candidate['list_label']), aFragment)
			# found as a true substring
			# but use only if substring is at start of a word
			# FIXME: use word seps
			if (pos == 0) or (candidate['list_label'][pos-1] == u' '):
				matches.append(candidate)
		# no matches found
		if len(matches) == 0:
			return (False, [])

		matches.sort(self.__cmp_candidates)
		return (True, matches)
	#--------------------------------------------------------
	def getMatchesBySubstr(self, aFragment):
		"""Return matches for aFragment as a true substring."""
		matches = []
		candidates = self._get_candidates()
		# look for matches
		for candidate in candidates:
			if candidate['list_label'].lower().find(aFragment) != -1:
#			if string.find(string.lower(candidate['list_label']), aFragment) != -1:
				matches.append(candidate)
		# no matches found
		if len(matches) == 0:
			return (False, [])

		matches.sort(self.__cmp_candidates)
		return (True, matches)
	#--------------------------------------------------------
	def getAllMatches(self):
		"""Return all candidates."""
		return self._get_candidates()
	#--------------------------------------------------------
	def __cmp_candidates(self, candidate1, candidate2):
		"""naive ordering"""
		return 0
		# FIXME: do ordering
#		if candidate1 < candidate2:
#			return -1
#		if candidate1 == candidate2:
#			return 0
#		return 1

# ===========================================================
class cMatchProvider_SQL2(cMatchProvider):
	"""Match provider which searches matches
	   in possibly several database tables.

	queries:
		- a list of unicode strings
		- each string is a query
		- each string must contain: "... WHERE <column> %(fragment_condition)s ..."
		- each string can contain in the where clause: "... %(<ctxt_key1>)s ..."
		- each query must return (data, list_label, field_label)

	context definitions to be used in the queries, example:
		{'ctxt_key1': {'where_part': 'AND country = %(country)s', 'placeholder': 'country'}}

	client code using .set_context() must use the 'placeholder':
		<phrasewheel>/<match provider>.set_context('country', 'Germany')

	full example query:

		query = u" " "
			SELECT DISTINCT ON (list_label)
				pk_encounter
					AS data,
				to_char(started, 'YYYY Mon DD (HH24:MI)') || ': ' || l10n_type || ' [#' || pk_encounter || ']'
					AS list_label,
				to_char(started, 'YYYY Mon DD') || ': ' || l10n_type
					AS field_label
			FROM
				clin.v_pat_encounters
			WHERE
				(
					l10n_type %(fragment_condition)s
						OR
					type %(fragment_condition)s
				)	%(ctxt_patient)s
			ORDER BY
				list_label
			LIMIT
				30
		" " "
		context = {'ctxt_patient': {
			'where_part': u'AND pk_patient = %(PLACEHOLDER)s',
			'placeholder': u'PLACEHOLDER'
		}}
		self.mp = gmMatchProvider.cMatchProvider_SQL2(queries = query, context = context)
		self.set_context(context = 'PLACEHOLDER', val = '<THE VALUE>')

	_SQL_data2match:
		SQL to retrieve a match by, say, primary key
		wherein the only keyword argument is 'pk'
	"""
	def __init__(self, queries = None, context = None):

		cMatchProvider.__init__(self)

		if type(queries) == type([]):
			self._queries = queries
		else:
			self._queries = [queries]

		if context is None:
			self._context = {}
		else:
			self._context = context

		self._args = {}

		self._SQL_data2match = None
	#--------------------------------------------------------
	# internal matching algorithms
	#
	# if we end up here:
	#	- aFragment will not be "None"
	#   - aFragment will be lower case
	#	- we _do_ deliver matches (whether we find any is a different story)
	#--------------------------------------------------------
	def getMatchesByPhrase(self, aFragment):
		"""Return matches for aFragment at start of phrases."""

		fragment_condition = u"ILIKE %(fragment)s"
		self._args['fragment'] = u"%s%%" % aFragment

		return self._find_matches(fragment_condition)
	#--------------------------------------------------------
	def getMatchesByWord(self, aFragment):
		"""Return matches for aFragment at start of words inside phrases."""

		fragment_condition = u"~* %(fragment)s"
		aFragment = gmPG2.sanitize_pg_regex(expression = aFragment, escape_all = False)
		self._args['fragment'] = u"( %s)|(^%s)" % (aFragment, aFragment)

		return self._find_matches(fragment_condition)
	#--------------------------------------------------------
	def getMatchesBySubstr(self, aFragment):
		"""Return matches for aFragment as a true substring."""

		fragment_condition = u"ILIKE %(fragment)s"
		self._args['fragment'] = u"%%%s%%" % aFragment

		return self._find_matches(fragment_condition)
	#--------------------------------------------------------
	def getAllMatches(self):
		"""Return all items."""
		return self.getMatchesBySubstr(u'')
	#--------------------------------------------------------
	def get_match_by_data(self, data=None):
		if self._SQL_data2match is None:
			return None

		query = {'cmd': self._SQL_data2match, 'args': {'pk': data}}
		try:
			rows, idx = gmPG2.run_ro_queries(queries = [query], get_col_idx = False)
		except:
			_log.exception('[%s]: error running _SQL_data2match, dropping query', self.__class__.__name__)
			self._SQL_data2match = None
			return None

		# hopefully the most frequent case:
		if len(rows) == 1:
			return rows[0]

		_log.error('[%s]: 0 or >1 rows found by running _SQL_data2match, ambiguous, ignoring', self.__class__.__name__)
		return None
	#--------------------------------------------------------
	def _find_matches(self, fragment_condition):
		if self.print_queries:
			print "----------------------"
			print pydt.datetime.now()
		matches = []
		for query in self._queries:
			where_fragments = {'fragment_condition': fragment_condition}

			for context_key, context_def in self._context.items():
				try:
					placeholder = context_def['placeholder']
					where_part = context_def['where_part']
					self._args[placeholder] = self._context_vals[placeholder]
					# we do have a context value for this key, so add the where condition
					where_fragments[context_key] = where_part
					if self.print_queries:
						print "ctxt ph:", placeholder
						print "ctxt where:", where_part
						print "ctxt val:", self._context_vals[placeholder]
				except KeyError:
					# we don't have a context value for this key, so skip the where condition
					where_fragments[context_key] = u''
					if self.print_queries:
						print "invalid ctxt key:", context_key

			cmd = query % where_fragments

			if self.print_queries:
				print "class:", self.__class__.__name__
				print "ctxt:", self._context_vals
				print "args:", self._args
				print "query:", cmd

			try:
				rows, idx = gmPG2.run_ro_queries(queries = [{'cmd': cmd, 'args': self._args}], get_col_idx = False)
			except:
				_log.exception('[%s]: error running match provider SQL, dropping query', self.__class__.__name__)
				idx = self._queries.index(query)
				del self._queries[idx]
				break

			# no matches found: try next query
			if len(rows) == 0:
				continue

			for row in rows:
				match = {'weight': 0}

				try:
					match['data'] = row['data']
				except KeyError:
					match['data'] = row[0]

				try:
					match['list_label'] = row['list_label']
				except KeyError:
					match['list_label'] = row[1]

				# explicit "field_label" in result ?
				try:
					match['field_label'] = row['field_label']
				# no
				except KeyError:
					# but does row[2] exist ?
					try:
						match['field_label'] = row[2]
					# no: reuse "list_label"
					except IndexError:
						match['field_label'] = match['list_label']

#				try:
#					match['label'] = row['label']
#				except KeyError:
#					match['label'] = match['list_label']

				matches.append(match)

			return (True, matches)

		# none found whatsoever
		return (False, [])

#================================================================
if __name__ == '__main__':
	pass