-
Notifications
You must be signed in to change notification settings - Fork 6
/
views.py
1412 lines (1287 loc) · 67.1 KB
/
views.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
#!/bin/sh
#encoding: utf-8
"""
Views
"""
from client import client
import traceback
from flask import redirect, current_app, request, abort, render_template
from flask_restful import Resource
from webargs import fields
from webargs.flaskparser import parser
import urllib
from datetime import datetime
from dateutil.relativedelta import relativedelta
import calendar
import re
from collections import OrderedDict
import adsparser
class IndexView(Resource):
"""
Return the index page. This is temporary until the app is deployed on its
own instance.
"""
def get(self):
"""
HTTP GET request
:return: index html page
"""
return current_app.send_static_file('index.html')
class SimpleClassicView(Resource):
"""for testing, show ads page with single input text field"""
def get(self):
return current_app.send_static_file('classic_w_BBB_button.html')
class ComplexClassicView(Resource):
"""for testing, show standard ads search page"""
def get(self):
return current_app.send_static_file('fielded_classic_w_BBB_button.html')
class ComplexClassicArXivView(Resource):
"""for testing, show standard ads search page with arXiv classes visible"""
def get(self):
return current_app.send_static_file('preprint_service_w_BBB_button.html')
class ComplexClassicPhysicsView(Resource):
"""for testing, show standard ads search page with physics classes visible"""
def get(self):
return current_app.send_static_file('physics_service_w_BBB_button.html')
class TranslationValue():
"""simple singleton container class to hold translation components
functions that translation specific parameters typically augment the TranslationValue
"""
# consider adding field for sort order and other args
def __init__(self):
self.search = []
self.filter= []
self.error_message = []
self.warning_message = []
self.unprocessed_fields = []
self.sort = ''
self.facet = []
self.params = ''
class ClassicSearchRedirectView(Resource):
"""
End point converts classic search to bumbblebee, returns an http redirect
Where possible, returned query should be human readable and illustrate what a good query looks like
"""
def __init__(self):
super(ClassicSearchRedirectView, self).__init__()
self.translation = TranslationValue()
# all the parameters from classic
# typically integer fields must be represented by Field to allow None values
# some of these need use type fields.List
self.api = {
# the following we currently translate
'article_sel': fields.Str(required=False),
'aut_logic': fields.Str(required=False),
'aut_xct': fields.Str(required=False),
'author': fields.Str(required=False),
'data_link': fields.Str(required=False),
'db_key': fields.Str(required=False),
'end_entry_day': fields.Field(required=False),
'end_entry_mon': fields.Field(required=False),
'end_entry_year': fields.Field(required=False),
'end_mon': fields.Field(required=False),
'end_year': fields.Field(required=False),
'jou_pick': fields.Str(required=False),
'obj_logic': fields.Str(required=False),
'object': fields.Str(required=False),
'open_link': fields.Str(required=False),
'preprint_link': fields.Str(required=False),
'qsearch': fields.Str(required=False),
'return_req': fields.Str(required=False),
'start_entry_day': fields.Field(required=False),
'start_entry_mon': fields.Field(required=False),
'start_entry_year': fields.Field(required=False),
'start_mon': fields.Field(required=False),
'start_year': fields.Field(required=False),
'text': fields.Str(required=False),
'txt_logic': fields.Str(required=False),
'title': fields.Str(required=False),
'ttl_logic': fields.Str(required=False),
# implementations for the following just create errors
# perhaps because there is no ads/bumbleebee support yet
# 6/11/2019 pass it in for the unclassic functionality
'nr_to_return': fields.Field(required=False),
'start_nr': fields.Field(required=False),
# golnaz - 3/5/2018
'article_link': fields.Str(required=False),
'gif_link': fields.Str(required=False),
'article': fields.Str(required=False),
'simb_obj': fields.Str(required=False),
'ned_obj': fields.Str(required=False),
'data_and': fields.Str(required=False),
'toc_link': fields.Str(required=False),
'pds_link': fields.Str(required=False),
'multimedia_link': fields.Str(required=False),
'ref_link': fields.Str(required=False),
'citation_link': fields.Str(required=False),
'associated_link': fields.Str(required=False),
'lib_link': fields.Str(required=False),
'ar_link': fields.Str(required=False),
'aut_note': fields.Str(required=False),
'spires_link': fields.Str(required=False),
'group_and': fields.Str(required=False),
'group_sel': fields.Str(required=False),
'abstract': fields.Str(required=False),
'sort': fields.Str(required=False),
'aut_wt': fields.Field(required=False),
'obj_wt': fields.Field(required=False),
'ttl_wt': fields.Field(required=False),
'txt_wt': fields.Field(required=False),
'aut_wgt': fields.Str(required=False),
'obj_wgt': fields.Str(required=False),
'ttl_wgt': fields.Str(required=False),
'txt_wgt': fields.Str(required=False),
'aut_syn': fields.Str(required=False),
'ttl_syn': fields.Str(required=False),
'txt_syn': fields.Str(required=False),
'aut_sco': fields.Str(required=False),
'ttl_sco': fields.Str(required=False),
'txt_sco': fields.Str(required=False),
'aut_req': fields.Str(required=False),
'obj_req': fields.Str(required=False),
'ttl_req': fields.Str(required=False),
'txt_req': fields.Str(required=False),
'ref_stems': fields.Str(required=False),
'arxiv_sel': fields.Str(required=False),
# these can be ignored, at least for now
'sim_query': fields.Str(required=False),
'ned_query': fields.Str(required=False),
'mail_link': fields.Str(required=False),
'gpndb_obj': fields.Str(required=False),
'min_score': fields.Str(required=False),
'lpi_query': fields.Str(required=False),
'iau_query': fields.Str(required=False),
'data_type': fields.Str(required=False),
'adsobj_query': fields.Str(required=False),
# and the following are not yet translated
'kwd_wt': fields.Field(required=False),
'full_wt': fields.Field(required=False),
'aff_wt': fields.Field(required=False),
'full_syn': fields.Str(required=False),
'aff_syn': fields.Str(required=False),
'kwd_wgt': fields.Str(required=False),
'full_wgt': fields.Str(required=False),
'aff_wgt': fields.Str(required=False),
'kwd_sco': fields.Str(required=False),
'full_sco': fields.Str(required=False),
'aff_sco': fields.Str(required=False),
'kwd_req': fields.Str(required=False),
'full_req': fields.Str(required=False),
'aff_req': fields.Str(required=False),
'aut_logic': fields.Str(required=False),
'obj_logic': fields.Str(required=False),
'kwd_logic': fields.Str(required=False),
'ttl_logic': fields.Str(required=False),
'txt_logic': fields.Str(required=False),
'full_logic': fields.Str(required=False),
'aff_logic': fields.Str(required=False),
# these are added for myads queryies
'query_type': fields.Str(required=False),
'qform': fields.Str(required=False),
}
def get(self):
"""
return 302 to bumblebee
"""
try:
current_app.logger.info('Classic search redirect received data, headers: {}'.format(request.headers))
bbb_url=current_app.config['BUMBLEBEE_URL']
bbb_query = self.translate(request)
redirect_url = bbb_url + 'search/'+ bbb_query
current_app.logger.info('translated classic {} to bumblebee {}, {}'.format(request, bbb_query, redirect_url))
# golnaz 3/11/2018
# while testing and using curl to see the build url after redirect call, noticed that url gets html encoded,
# and in particular & become & that BBB does not like, hence switched to render_template to tell it that
# the url is safe and not encode it
# but then while testing classic template, realized no encoding was done and so switched back, since
# it felt redirect was faster and unnoticeable compared to render_template
return redirect(redirect_url, code=302)
#return render_template('redirect.html', url=redirect_url), 200
except Exception as e:
current_app.logger.error(e.message)
current_app.logger.error(traceback.format_exc())
return '<html><body><h2>Error translating classic query</h2> ' + e.message + '<p>' + traceback.format_exc() + '<p>' + str(request) + '</body></html>'
def parse(self, request):
"""
Parse the input parameter
"""
args = parser.parse(self.api, request)
# group_sel is a special case since we could have repeated entries, (i.e., &group_sel=ARI&group_sel=ESO%2FLib&group_sel=HST)
# hence need to extract them to a list, and then turn it to a string, since calling parser.parse only parses the first element
group_sel = request.args.getlist('group_sel', type=str)
if len(group_sel) > 0:
args['group_sel'] = ','.join(group_sel)
# similarly db_key
db_key = request.args.getlist('db_key', type=str)
if len(db_key) > 0:
args['db_key'] = ','.join(db_key)
# and arxiv_sel
arxiv_sel = request.args.getlist('arxiv_sel', type=str)
if len(arxiv_sel) > 0:
args['arxiv_sel'] = ','.join(arxiv_sel)
return args
def translate(self, request):
"""
Convert all classic search related parameters to ads/bumblebee
"""
args = self.parse(request)
if args.get('query_type', None):
return self.translate_myads_queries(args)
# functions to translate/process specific parameters
# consider using reflection to obtain this list
funcs = [self.translate_authors,
self.translate_pubdate, self.translate_entry_date,
self.translate_results_subset, self.translate_return_req,
self.translate_article_sel, self.translate_database,
self.translate_jou_pick, self.translate_group_sel,
self.translate_sort, self.translate_to_ignore,
self.translate_weights, self.translate_arxiv_sel,
self.translate_ref_stems]
for f in funcs:
f(args) # each may contribute to self.translation singleton
# functions to deal with the simple cases where only parameter name changes
self.translate_simple(args, 'object', 'object')
self.translate_simple(args, 'title', 'title')
self.translate_simple(args, 'text', 'abs')
# this is a filter on the classic side but in solr search is not treated as such
self.translate_data_entries(args)
# translate qsearch as the last item, which is for unfielded form
# this way qsearch parameter is still in args so that it can be decided which parameters
# make sense to mark as unprocessed
self.translate_qsearch(args)
# combine translation fragments in self.translation to ads/bumblebee parameter string
if len(self.translation.search) == 0:
self.translation.search = ['*:*']
solr_query = ''.join(self.translation.facet) + '&' if len(self.translation.facet) > 0 else ''
solr_query += 'q=' + ' '.join(self.translation.search)
if len(self.translation.filter) > 0:
solr_query += '&fq=' + '&fq='.join(self.translation.filter)
if len(self.translation.sort) > 0:
solr_query += '&sort=' + self.translation.sort
if len(self.translation.params) > 0:
solr_query += self.translation.params
if len(self.translation.error_message) > 0:
solr_query += '&error_message=' + '&error_message='.join(self.translation.error_message)
if len(self.translation.warning_message):
solr_query += '&warning_message=' + '&warning_message='.join(self.translation.warning_message)
if len(self.translation.unprocessed_fields) :
solr_query += '&unprocessed_parameter=' + '&unprocessed_parameter='.join(self.translation.unprocessed_fields)
if len(args.keys()):
# the functions that translate individual parameters use pop to remove parameters from arg list
# here if there are unprocessed parameters
# pass their names out ads/bumblebee
solr_query += '&unprocessed_parameter=' + urllib.quote('Parameters not processed: ' + ' '.join(args.keys()))
# add an extra slash for safari browser
return solr_query + '/'
@staticmethod
def author_exact(args):
"""given an aut_xct value, is it true"""
value = args.pop('aut_xct', None)
if value:
if 'YES' == str(value).upper():
return True
return False
@staticmethod
def get_logic(classic_param, args):
"""given a logic parameter, return its value canonical form"""
classic_param_to_logic = {'author': 'aut_logic', 'title': 'ttl_logic',
'text': 'txt_logic', 'object': 'obj_logic'}
if classic_param in args:
logic_param = classic_param_to_logic[classic_param]
value = args.pop(logic_param, None)
if value:
value = value.upper()
return value
return ''
@staticmethod
def supplied(value):
"""check html parameter to see if it is valid"""
if value is None or (isinstance(value, basestring) and len(value) == 0):
return False
return True
def translate_title_for_myads(self, value):
""" return classic title in the form accept by BBB """
try:
# remove the star if there is one at the beginning and call the special parser
return adsparser.parse_classic_keywords(value.lstrip('*'))
except:
# go with regular tokenizer
return self.classic_field_to_string(value)[0].lstrip('*')
def translate_myads_queries(self, args):
"""return query string for the six different myads queries"""
query_type = args.pop('query_type', None)
if query_type == 'PAPERS':
qform = args.pop('qform', None)
# Daily arXiv query
if qform:
arxiv_sel = args.pop('arxiv_sel', None)
title_str = args.pop('title', None)
date_start = self.translate_entry_date_start(args)
date_end = self.translate_entry_date_end(args)
start_year = args.pop('start_year', None)
if arxiv_sel and self.validate_arxiv_sel(arxiv_sel) and title_str and date_start and date_end and start_year:
# if all entries are valid include them, oring them
arxiv_class = '(' + ' OR '.join(['arxiv_class:' + c + '.*' for c in arxiv_sel.split(',')]) + ')'
title = self.translate_title_for_myads(title_str)
# OR arxiv classes and title if any db_key other than DAILY_PRE,
# otherwise leave empty which is going to be AND
add_or = ' ' if args.get('db_key', 'DAILY_PRE') == 'DAILY_PRE' else ' OR '
daily_arxiv_query = 'bibstem:arxiv ({arxiv_class}{add_or}{title}) entdate:["{date_start}:00:00" TO {date_end}] pubdate:[{start_year}-00 TO *]'
daily_arxiv_query = daily_arxiv_query.format(arxiv_class=arxiv_class, add_or=add_or, title=title,
date_start=date_start, date_end=date_end,
start_year=start_year)
self.translation.search.append(urllib.quote(daily_arxiv_query))
self.translation.sort = urllib.quote('score desc')
else:
self.translation.error_message.append('MISSING_REQUIRED_PARAMETER')
# Weekly authors query or Weekly keyword (recent papers) query
else:
# decide which is which based on author/title parameter
authors_str = args.pop('author', None)
title_str = args.pop('title', None)
date_start = self.translate_entry_date_start(args)
date_end = self.translate_entry_date_end(args)
start_year = args.pop('start_year', None)
# if author is filled and title is empty then it is Weekly authors query
if authors_str and not title_str:
if start_year:
authors = self.classic_field_to_array(authors_str)
author_query = ' OR '.join(['author:' + x for x in authors])
weekly_authors_query = '{author_query} entdate:["{date_start}:00:00" TO {date_end}] pubdate:[{start_year}-00 TO *]'
weekly_authors_query = weekly_authors_query.format(author_query=author_query,
date_start=date_start, date_end=date_end,
start_year=start_year)
self.translation.search.append(urllib.quote(weekly_authors_query))
self.translation.sort = urllib.quote('score desc')
else:
self.translation.error_message.append('MISSING_REQUIRED_PARAMETER')
# if title is filled and author is empty then it is Weekly keyword (recent papers) query
elif title_str and not authors_str:
if start_year:
title = self.translate_title_for_myads(title_str)
weekly_keyword_query = '{title} entdate:["{date_start}:00:00" TO {date_end}] pubdate:[{start_year}-00 TO *]'
weekly_keyword_query = weekly_keyword_query.format(title=title,
date_start=date_start, date_end=date_end,
start_year=start_year)
self.translation.search.append(urllib.quote(weekly_keyword_query))
self.translation.sort = urllib.quote('entry_date desc')
else:
self.translation.error_message.append('MISSING_REQUIRED_PARAMETER')
# if both title and author have have values, cannot decide which query it is
elif authors_str and title_str:
self.translation.error_message.append('UNRECOGNIZABLE_VALUE')
# Weekly citations query
elif query_type == 'CITES':
authors_str = args.pop('author', None)
if authors_str:
authors = self.classic_field_to_array(authors_str)
weekly_citation_query = 'citations(author:{authors})'.format(authors=' '.join(authors))
self.translation.search.append(urllib.quote(weekly_citation_query))
self.translation.sort = urllib.quote('score desc')
else:
self.translation.error_message.append('MISSING_REQUIRED_PARAMETER')
# Weekly keyword (popular papers) query
elif query_type == 'ALSOREADS':
title_str = args.pop('title', None)
if title_str:
title = self.translate_title_for_myads(title_str)
weekly_keyword_query = 'trending({title})'.format(title=title)
self.translation.search.append(urllib.quote(weekly_keyword_query))
self.translation.sort = urllib.quote('score desc')
else:
self.translation.error_message.append('MISSING_REQUIRED_PARAMETER')
# Weekly keyword (most cited) query
elif query_type == 'REFS':
title_str = args.pop('title', None)
if title_str:
title = self.translate_title_for_myads(title_str)
weekly_keyword_query = 'useful({title})'.format(title=title)
self.translation.search.append(urllib.quote(weekly_keyword_query))
self.translation.sort = urllib.quote('score desc')
else:
self.translation.error_message.append('MISSING_REQUIRED_PARAMETER')
# none of the known queries
else:
self.translation.error_message.append('UNRECOGNIZABLE_VALUE')
self.translate_database(args)
# combine translation fragments in self.translation to ads/bumblebee parameter string
if len(self.translation.search) == 0:
self.translation.search = ['*:*']
solr_query = ''.join(self.translation.facet) + '&' if len(self.translation.facet) > 0 else ''
solr_query += 'q=' + ' '.join(self.translation.search)
if len(self.translation.filter) > 0:
solr_query += '&fq=' + '&fq='.join(self.translation.filter)
if len(self.translation.sort) > 0:
solr_query += '&sort=' + self.translation.sort
if len(self.translation.error_message) > 0:
solr_query += '&error_message=' + '&error_message='.join(self.translation.error_message)
# add an extra slash for safari browser
return solr_query + '/'
def translate_authors(self, args):
"""return string with all author search elements
classic ui allows different and/or between authors and objects so we handle
just the author affecting elements here
"""
connector = ' AND '
search = ''
logic = self.get_logic('author', args)
exact = self.author_exact(args)
# 5/21 from Alberto: let's switch the author "OR" to an "AND" by default and issue a warning to the user.
# 10/30/2019 from Alberto: let's recognize the boolean selected by user
if logic == 'OR':
connector = ' OR '
author_field = 'author:'
if exact:
author_field = '=author:'
# one lone parameter should hold all authors from classic
authors_str = args.pop('author', None)
if authors_str:
authors = self.classic_field_to_array(authors_str)
# is it a single author search: ^last, first$
match = re.findall('\^(.*)\$', ' '.join(authors))
# yes
if match:
search = '(author:"' + match[0] + '" and author_count:1)'
self.translation.search.append(search)
else:
search += urllib.quote(author_field) + '('
for author in authors:
search += urllib.quote(author + connector)
search = search[:-len(urllib.quote(connector))] # remove final
search += ')'
# fields in search are ANDed as of 5/9 and issue a warning
if len(self.translation.search) > 0:
self.translation.search.append('AND')
self.translation.search.append(search)
# see the 10/30/2019 comment above
# if len(authors) > 1 and logic == 'OR':
# self.translation.warning_message.append(urllib.quote('AUTHOR_ANDED_WARNING'))
def translate_simple(self, args, classic_param, bbb_param):
"""process easy to translate fields including title, abstract, and object
simply change name of parameter and use boolean connector
"""
connector = ' AND '
search = ''
logic = self.get_logic(classic_param, args)
if logic == 'OR':
connector = ' OR '
# one lone parameter should hold all authors from classic
classic_str = args.pop(classic_param, None)
if classic_str:
# note that only for object we allow multiple tokens and apply connector
# hence for title and abstract no connector is applied
if classic_param == 'object':
terms = self.classic_field_to_array(classic_str)
else:
terms = self.classic_field_to_string(classic_str)
# issue a warning for title and abstract if multiple words are specified and OR is selected
# 10/30/2019 from Alberto: let's recognize the boolean selected by user
# if len(''.join(terms).split(' ')) > 1 and logic == 'OR':
# if classic_param == 'title':
# self.translation.warning_message.append(urllib.quote('TITLE_ANDED_WARNING'))
# elif classic_param == 'text':
# self.translation.warning_message.append(urllib.quote('ABSTRACT_ANDED_WARNING'))
search += urllib.quote(bbb_param + ':') + '('
for term in terms:
search += urllib.quote(term + connector)
search = search[:-len(urllib.quote(connector))] # remove final connector
search += ')'
# multiple fields in search are ANDed as of 5/9/2018
if len(self.translation.search) > 0:
self.translation.search.append('AND')
self.translation.search.append(search)
def convert_year_short_to_long(self, year):
"""convert 2-digit year to 4-digit year"""
# leave these alone, these are indication of min,max years that shall be replaced by *
if year == 0 or year == 2222:
return year
if year > 100:
return year
diff_year = datetime.now().year - (datetime.now().year % 100)
return year + diff_year if year + diff_year <= datetime.now().year + 1 else year + diff_year - 100
def translate_pubdate(self, args):
"""translate string with pubdate element
for pubdate date search, only start or end need be specified
at least one start year or end year must be provided
unlike entry date search, negative offsets are not supported
in classic, 2 digit years were permitted
bumblebee example: pubdate:[1990-01 TO 1990-02]
"""
start_year = args.pop('start_year', None)
end_year = args.pop('end_year', None)
start_month = args.pop('start_mon', None)
end_month = args.pop('end_mon', None)
if self.supplied(start_year) is False and self.supplied(end_year) is False:
return
# if start is not provided, use beginning of time
if not self.supplied(start_year):
start_year = 0
if not self.supplied(start_month):
start_month = 1
# if end is not provided, use end of time
if not self.supplied(end_year):
end_year = 2222
tmp = datetime.now()
if not self.supplied(end_month):
end_month = tmp.month
else:
if not self.supplied(end_month):
end_month = 12
start_year = self.convert_year_short_to_long(int(start_year))
start_month = int(start_month)
end_year = self.convert_year_short_to_long(int(end_year))
end_month = int(end_month)
# we can use * for solr query if either start_year or end_year are not set
# did not change the code above that actually set the values if either is missing
# Y10k problem, but for 2 digit years we want to be clear what years we are searching
if start_year == 0:
search = 'pubdate' + urllib.quote(':[* TO {:04d}-{:02}]'.format(end_year, end_month))
elif end_year == 2222:
search = 'pubdate' + urllib.quote(':[{:04d}-{:02d} TO *]'.format(start_year, start_month))
else:
search = 'pubdate' + urllib.quote(':[{:04d}-{:02d} TO {:04d}-{:02}]'.format(start_year, start_month,
end_year, end_month))
# fields in search are ANDed as of 5/9
if len(self.translation.search) > 0:
self.translation.search.append('AND')
self.translation.search.append(search)
def translate_entry_date_start(self, args):
""" return formatted start date for entry date"""
try:
# get the start dates, if specified turned to int,
# if not init to 0
start_year = args.pop('start_entry_year', None)
if not self.supplied(start_year):
start_year = 0
else:
start_year = self.convert_year_short_to_long(int(start_year))
start_month = args.pop('start_entry_mon', None)
if not self.supplied(start_month):
start_month = 0
else:
start_month = int(start_month)
start_day = args.pop('start_entry_day', None)
if not self.supplied(start_day):
start_day = 0
else:
start_day = int(start_day)
# is it date or offset date
date = sum(d > 0 for d in [start_year,start_month,start_day])
offset = sum(d < 0 for d in [start_year,start_month,start_day])
if date > 0 and offset > 0:
self.translation.error_message.append('ENTRY_DATE_OFFSET_ERROR')
return None
# if offset has been specified, get current date, subtract the offset, turn into string and return
if offset > 0:
today_start = datetime.now()
today_start = today_start - relativedelta(days=-start_day, months=-start_month, years=-start_year)
return today_start.strftime("%Y-%m-%d")
# if any date fields has been specified, turn into string and return
# beginning of the time is 01-01-01
if date >= 0:
start_year = start_year if start_year != 0 else 1
start_month = start_month if start_month != 0 else 1
start_day = start_day if start_day != 0 else 1
return '{:04d}-{:02d}-{:02d}'.format(start_year, start_month, start_day)
except:
self.translation.error_message.append('ENTRY_DATE_NON_NUMERIC_ERROR')
return None
def translate_entry_date_end(self, args):
""" return formatted end date for entry date"""
try:
# get the end dates, if specified turned to int,
# if not init to 0
end_year = args.pop('end_entry_year', None)
if not self.supplied(end_year):
end_year = 0
else:
end_year = self.convert_year_short_to_long(int(end_year))
end_month = args.pop('end_entry_mon', None)
if not self.supplied(end_month):
end_month = 0
else:
end_month = int(end_month)
end_day = args.pop('end_entry_day', None)
if not self.supplied(end_day):
end_day = 0
else:
end_day = int(end_day)
# is it date or offset date
date = sum(d > 0 for d in [end_year,end_month,end_day])
offset = sum(d < 0 for d in [end_year,end_month,end_day])
if date > 0 and offset > 0:
self.translation.error_message.append('ENTRY_DATE_OFFSET_ERROR')
return None
# if offset has been specified, get current date, subtract the offset, turn into string and return
if offset > 0:
today_end = datetime.now()
today_end = today_end - relativedelta(days=-end_day, months=-end_month, years=-end_year)
return today_end.strftime("%Y-%m-%d")
# if no value has been specified for date, get now, turn into string and return
if date == 0:
today_end = datetime.now()
return today_end.strftime("%Y-%m-%d")
# if any date fields has been specified, turn into string and return
if date > 0:
# if year has not been specified get now
end_year = end_year if end_year != 0 else datetime.now().year
# depending on if year is specified init to the end of that year, or if no year init to now
end_month = end_month if end_month != 0 else (datetime.now().month if end_year == datetime.now().year else 12)
end_day = end_day if end_day != 0 else \
(datetime.now().day if end_year == datetime.now().year else calendar.monthrange(end_year, end_month)[1])
return '{:04d}-{:02d}-{:02d}'.format(end_year, end_month, end_day)
except:
self.translation.error_message.append('ENTRY_DATE_NON_NUMERIC_ERROR')
return None
def translate_entry_date(self, args):
""" return string for pubdate element
entry date has a dual functionality, it can be used to enter the date,
or offset and then the date is computed from it.
"""
fields = ['start_entry_day', 'start_entry_mon', 'start_entry_year',\
'end_entry_day', 'end_entry_mon', 'end_entry_year']
# at least one entry date field needs to have been populated to continue
# this is needed for the test side, from the production side this is always false
if sum([1 for f in fields if f in args]) == 0:
return
# if user has set values for any of fields
add = sum([1 for f in fields if len(args[f]) > 0]) > 0
start_date = self.translate_entry_date_start(args)
end_date = self.translate_entry_date_end(args)
if start_date is not None and end_date is not None and add:
search = 'entdate' + urllib.quote(':["{}" TO "{}"]'.format(start_date, end_date))
# fields in search are ANDed as of 5/9
if len(self.translation.search) > 0:
self.translation.search.append('AND')
self.translation.search.append(search)
def validate_db_key(self, db_key):
"""Validate database selections"""
valid_db_key = ['AST', 'PHY', 'PRE', 'DAILY_PRE', 'ALL']
if len(db_key) == 0:
return False
entry = db_key.split(',')
for e in entry:
if e not in valid_db_key:
return False
return True
def translate_database(self, args):
"""translate which database to use
only support for ast and phy, bbb does not support arxiv value, classic does not support general
"""
dict_db = {'AST': 'astronomy',
'PHY': 'physics',
'PRE': 'e-prints',
'DAILY_PRE': 'e-prints',
'ALL' : ''}
value = args.pop('db_key', None)
if value is None:
return
if self.validate_db_key(value):
# if all entries are valid include them by oring them
db_key = ''
# 8/6/2018 -- to view the filters properly in BBB the format for database is as follows
# &filter_database_fq_database=OR
# &filter_database_fq_database=database:"general"
# &filter_database_fq_database=database:"physics"
# &fq={!type=aqp v=$fq_database}&fq_database=(database:"general" OR database:"physics")
if len(self.translation.facet) > 0:
self.translation.facet.append('&')
entry = value.split(',')
for e in entry:
if e != 'PRE' and e != 'DAILY_PRE' and e != 'ALL':
if len(db_key) > 0:
db_key += ' OR '
if len(self.translation.facet) == 0:
self.translation.facet.append('filter_database_fq_database=OR')
db_key += 'database:"' + dict_db[e] + '"'
self.translation.facet.append('&filter_database_fq_database=' + 'database:"' + dict_db[e] + '"')
if len(db_key) > 0:
self.translation.filter.append(urllib.quote('{') + '!' + urllib.quote('type=aqp v=$fq_database}') + \
'&fq_database=(' + urllib.quote(db_key) + ')')
else:
# unrecognizable value
self.translation.error_message.append('UNRECOGNIZABLE_VALUE')
self.translation.unprocessed_fields.append('db_key')
def translate_results_subset(self, args):
"""subset/pagination currently not supported by bumblebee
provide error message if pagination request is present
6/11/2019 in the process of implementing unclassic we are adding these in """
number_to_return = args.pop('nr_to_return', None)
start_nr = args.pop('start_nr', None)
if number_to_return:
self.translation.params += '&rows=%s'%(number_to_return)
if start_nr:
self.translation.params += '&start=%s'%(start_nr)
# golnaz: hold off for now
# if number_to_return or start_nr:
# self.translation.error_message.append(urllib.quote('Result subset/pagination is not supported'))
def translate_jou_pick(self, args):
"""translate for refereed, non-refereed"""
jou_pick = args.pop('jou_pick', None)
if jou_pick is None:
# if not provided, include everything in results, which is default
pass
elif jou_pick == 'ALL':
# include everything in results, which is default
pass
elif jou_pick == 'NO':
# 8/6/2018 -- to view the filters properly in BBB the format for property is as follows
# filter_property_fq_property=AND
# &filter_property_fq_property=property:"refereed"
# &fq={!type=aqp v=$fq_property}&fq_property=(property:"refereed")
if len(self.translation.facet) > 0:
self.translation.facet.append('&')
self.translation.facet.append('filter_property_fq_property=AND')
self.translation.facet.append('&filter_property_fq_property=property:"refereed"')
# only include refereed journals
self.translation.filter.append(urllib.quote('{') + '!' + urllib.quote('type=aqp v=$fq_property}') + \
'&fq_property=(' + urllib.quote('property:("refereed")') + ')')
elif jou_pick == 'EXCL':
if len(self.translation.facet) > 0:
self.translation.facet.append('&')
self.translation.facet.append('filter_property_fq_property=AND')
self.translation.facet.append('&filter_property_fq_property=property:"not refereed"')
# only include non-refereed
self.translation.filter.append(urllib.quote('{') + '!' + urllib.quote('type=aqp v=$fq_property}') + \
'&fq_property=(' + urllib.quote('property:("not refereed")') + ')')
else:
self.translation.error_message.append('UNRECOGNIZABLE_VALUE')
self.translation.unprocessed_fields.append('jou_pick')
def translate_data_entries(self, args):
""" Convert all classic data entries search related parameters to ads/bumblebee """
dict_entries = {'data_link' : 'esources:*',
'article_link' : 'esources:("PUB_PDF" OR "PUB_HTML" OR "AUTHOR_PDF" OR "AUTHOR_HTML" OR "ADS_PDF" OR "ADS_SCAN")',
'gif_link' : 'esources:("ADS_SCAN")',
'article' : 'esources:("PUB_PDF" OR "PUB_HTML")',
'preprint_link' : 'esources:("EPRINT_HTML")',
'toc_link' : 'property:("TOC")',
'ref_link' : 'reference:*',
'citation_link' : 'citation_count:[1 TO *]',
'associated_link' : 'property:("ASSOCIATED")',
'simb_obj' : 'data:("simbad")',
'ned_obj' : 'data:("ned")',
'pds_link' : 'data:("PDS")',
'aut_note' : 'property:("NOTE")', # need to verify this later, it is being implemented 3/12
'lib_link' : 'property:("LIBRARYCATALOG")',
'ar_link' : 'read_count:[1 TO *]',
'multimedia_link' : 'property:("PRESENTATION")',
'spires_link' : 'property:("INSPIRE")',
'abstract' : 'abstract:*',
'open_link' : 'property:("OPENACCESS")'
}
search = []
operator = self.translate_data_and(args)
if operator is not None:
# each may contribute to self.translation singleton
for classic,BBB in dict_entries.iteritems():
value = args.pop(classic, None)
if value is None:
# if not provided, we do not need to include it in the result
pass
elif value == 'YES':
# include entry, first add the operator
# NOT comes first, also add operator if there are multiple selection
if (operator == 'NOT') or len(search) > 0:
search.append(operator)
search.append(urllib.quote(BBB))
else:
# unrecognizable value
self.translation.error_message.append('UNRECOGNIZABLE_VALUE')
self.translation.unprocessed_fields.append(classic)
if len(search) == 1:
self.translation.search.append(''.join(search))
elif len(search) > 1:
self.translation.search.append('(' + ' '.join(search) + ')')
def translate_data_and(self, args):
""" get bibliographic entries operator """
data_and = args.pop('data_and', None)
if data_and is None:
operator = None
elif data_and == 'ALL':
# when 'A bibliographic entry' radio button is selected => include everything in results, which is default
operator = None
elif data_and == 'NO':
# when 'At least one of the following (OR)' radio button is selected
operator = 'OR'
elif data_and == 'YES':
# when 'All of the following (AND)' radio button is selected
operator = 'AND'
elif data_and == 'NOT':
# when 'None of the following (NOT)' radio button is selected
operator = 'NOT'
else:
operator = None
self.translation.error_message.append('UNRECOGNIZABLE_VALUE')
self.translation.unprocessed_fields.append('data_and')
return operator
def validate_group_sel(self, group_sel):
valid_group_sel = ['ARI', 'CfA', 'CFHT', 'Chandra', 'ESO/Lib', 'ESO/Telescopes', 'Gemini', 'Herschel', 'HST',
'ISO', 'IUE', 'JCMT', 'Keck', 'Leiden', 'LPI', 'Magellan', 'NOAO', 'NRAO', 'NRAO/Telescopes',
'ROSAT', 'SDO', 'SMA', 'Spitzer', 'Subaru', 'Swift', 'UKIRT', 'USNO', 'VSGC', 'XMM']
if len(group_sel) == 0:
return False
entry = group_sel.split(',')
for e in entry:
if e not in valid_group_sel:
return False
return True
def translate_group_sel(self, args):
""" Convert all classic group entries search related parameters to ads/bumblebee """
operator = self.translate_group_and(args)
if operator is not None:
value = args.pop('group_sel', None)
if value is None:
return
if self.validate_group_sel(value):
# if all entries are valid include them, adding in the selected operator
# 8/6/2018 -- to view the filters properly in BBB the format for bibgroup is as follows
# filter_bibgroup_facet_fq_bibgroup_facet=AND
# &filter_bibgroup_facet_fq_bibgroup_facet=bibgroup_facet:"CfA"
# &fq={!type=aqp v=$fq_bibgroup_facet}&fq_bibgroup_facet=(bibgroup_facet:"CfA")
if len(self.translation.facet) > 0:
self.translation.facet.append('&')
self.translation.facet.append('filter_bibgroup_facet_fq_bibgroup_facet=' + operator)
group_sel = ''
entry = value.split(',')
for e in entry:
if (operator == 'NOT') or len(group_sel) > 0:
group_sel += ' ' + operator + ' '
group_sel += '"' + e + '"'
self.translation.facet.append('&filter_bibgroup_facet_fq_bibgroup_facet=' + 'bibgroup_facet:"' + e + '"')
if len(group_sel) > 0:
self.translation.filter.append(urllib.quote('{') + '!' + urllib.quote('type=aqp v=$fq_bibgroup_facet}') + \
'&fq_bibgroup_facet=(' + urllib.quote_plus('bibgroup_facet:({})'.format(group_sel)) + ')')
else:
# unrecognizable value
self.translation.error_message.append('UNRECOGNIZABLE_VALUE')
self.translation.unprocessed_fields.append('group_sel')
def translate_group_and(self, args):
""" set group entries operator """
group_and = args.pop('group_and', None)
if group_and is None:
operator = None
elif group_and == 'ALL':
# when 'All Groups' radio button is selected => include everything in results, which is default
operator = None
elif group_and == 'NO':
# when 'At least one of the following groups (OR)' radio button is selected
operator = 'OR'
elif group_and == 'YES':
# when 'All of the following groups (AND)' radio button is selected
operator = 'AND'
else:
operator = None
self.translation.error_message.append('UNRECOGNIZABLE_VALUE')
self.translation.unprocessed_fields.append('group_and')
return operator
def translate_return_req(self, args):
"""if return_req parameter is provided, it must be 'result' or None
return error if any other value is supplied
"""
return_req = args.pop('return_req', None)
if return_req is None:
pass
elif return_req == 'result':
pass
else:
self.translation.error_message.append('UNRECOGNIZABLE_VALUE')
self.translation.unprocessed_fields.append('return_req')
def translate_article_sel(self, args):
article_sel = args.pop('article_sel', None)
if article_sel is None:
pass
elif article_sel == 'YES':
# 8/6/2018 -- to view the filters properly in BBB the format for doctype is as follows
# filter_doctype_facet_hier_fq_doctype=AND
# &filter_doctype_facet_hier_fq_doctype=doctype_facet_hier:"0/Article"
# &fq={!type=aqp v=$fq_doctype}&fq_doctype=(doctype_facet_hier:"0/Article")
if len(self.translation.facet) > 0:
self.translation.facet.append('&')
self.translation.facet.append('filter_doctype_facet_hier_fq_doctype=AND')
self.translation.facet.append('&filter_doctype_facet_hier_fq_doctype=' +
urllib.quote_plus('doctype_facet_hier:"0/Article"'))
# only include article journals
self.translation.filter.append(urllib.quote('{') + '!' + urllib.quote('type=aqp v=$fq_doctype}') + \
'&fq_doctype=(' + urllib.quote_plus('doctype_facet_hier:"0/Article"') + ')')
else:
self.translation.error_message.append('UNRECOGNIZABLE_VALUE')
self.translation.unprocessed_fields.append('article_sel')
def translate_qsearch(self, args):
"""translate qsearch parameter from single input form on classic_w_BBB_button.html