-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
2031 lines (1879 loc) · 86.6 KB
/
app.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
import itertools as it
import functools
import pprint
import warnings
from collections import Counter
import cmd2 #let's import it so we can pass the cmd interface as an object
import newspaper as np
from dateutil.parser import parse
from sqlalchemy import func
from sqlalchemy.orm.exc import MultipleResultsFound
import docx
from docx.enum.dml import MSO_THEME_COLOR_INDEX
import BTCInput3 as btc
from roundup_db1 import Entry, Category, Keyword, Publication, Author, Section, Introduction
from roundup_db1 import DataAccessLayer
class Roundup(object):
'''NOTE: do not try to use the roundup class for anything except exporting roundups'''
@classmethod
def prep_export(cls, title, start_date, end_date,
filename, min_category, max_category, intro=None):
new_sections = get_sections()
new_sections = [RoundupSection.from_normal_section(i) for i in new_sections]
result= cls(title=title, start_date=start_date, end_date=end_date,
filename=filename, min_category=min_category, max_category=max_category,
sections=new_sections, intro=intro)
result.make_roundup()
return result
def __init__(self, title, start_date, end_date,
filename, min_category=1,
max_category=21, sections=[], intro=None):#app.get_sections()):
self.title = title
self.start_date = start_date
self.end_date = end_date
self.filename = filename
self.min_category = min_category
self.max_category = max_category
self.sections = [RoundupSection.from_normal_section(i) for i in sections]
self.categories = self.get_category_articles()
self.intro=intro
def make_roundup(self):
'''Takes the sections and gets and organizes the categories. These data structures are used ONLY
when we export the final roundup to docx or html. There is NO other use for them in the program logic.'''
for section in self.sections:
for category in self.categories:
if category.section_id == section.section_id:
section.categories.append(category)
#for i in section.categories:
# print(len(i.entries))
#section.categories = list(it.dropwhile(len(category.entries==0), section.categories))
@staticmethod
def add_hyperlink(paragraph, text, url):
# This gets access to the document.xml.rels file and gets a new relation id value
try:
part = paragraph.part
r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)
# Create the w:hyperlink tag and add needed values
hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )
# Create a w:r element and a new w:rPr element
new_run = docx.oxml.shared.OxmlElement('w:r')
rPr = docx.oxml.shared.OxmlElement('w:rPr')
# Join all the xml elements together add add the required text to the w:r element
new_run.append(rPr)
new_run.text = text
hyperlink.append(new_run)
# Create a new Run object and add the hyperlink into it
r = paragraph.add_run ()
r._r.append (hyperlink)
# A workaround for the lack of a hyperlink style (doesn't go purple after using the link)
# Delete this if using a template that has the hyperlink style in it
r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
r.font.underline = True
return hyperlink
except Exception as e:
print(e)
@staticmethod
def add_article(document, article):
#print(article)
try:
new_paragraph = document.add_paragraph('') #add blank paragraph that we append the text to
Roundup.add_hyperlink(paragraph=new_paragraph, text=article.entry_name, url=article.entry_url)
#print(Article.get_date_formatted(article))
#new_paragraph.add_run(' ({0}) '.format(Entry.get_date_formatted(article)))
new_paragraph.add_run(f' ({article.get_date_formatted}) ')#.format(article.get_date_formatted))
#blank space between the link and the description
new_paragraph.add_run(article.description)
except Exception as e:
print(e)
@staticmethod
def add_section(document, section):
document.add_paragraph(section.name)
section.categories.sort(key=lambda x: x.name, reverse=True)
section.categories.reverse()
for category in section.categories:
#if len(section)
Roundup.add_category(document, category)
@staticmethod
def add_category(document, category):
document.add_paragraph(category.name)
category.entries.sort(key=lambda x: x.entry_name, reverse=True)
category.entries.reverse()
for article in category.entries:
Roundup.add_article(document, article)
def create_roundup(self, document, roundup_title, sections,
intro=None):
document.add_paragraph(roundup_title)
if intro != None:
document.add_paragraph(intro)
for section in self.sections:
Roundup.add_section(document, section)
def get_category_articles(self):
current_category = 1
max_category = 30
article_categories = []
while current_category <= max_category:
#for category in range(min_category, max_category+1):
cat = get(session=dal.session, model=Category, category_id=current_category)
#new_cat = RoundupCategory()
print(cat)
try:
article_categories.append(RoundupCategory(category_id=cat.category_id,
name=cat.name,
entries = [i for i in cat.entries if i.date >=self.start_date and i.date <=self.end_date],
section_id=cat.section_id))
except AttributeError:
print('category not found')
current_category += 1
return article_categories
def export_docx(self):
#def complete_roundup2(filename, roundup_title, sections):
new_document = docx.Document()
Roundup.create_roundup(self=self, document=new_document,
roundup_title=self.title,
sections=self.sections,
intro =self.intro)
new_document.save(f'{self.filename}.docx')#.format(self.filename))
class RoundupSection(object):
'''Replicates the section class when we create roundups. DO NOT use this class
for anything except roundup generation.'''
@classmethod
def from_normal_section(cls, section: Section):
return cls(section_id = section.section_id,
name=section.name,
categories=[])
def __init__(self, section_id, name, categories=[]):
self.section_id = section_id
self.name = name
self.categories=categories
def __repr__(self):
return f'Sec(section_id={self.section_id}, name={self.name})'#.format(self.section_id, self.name)
class RoundupCategory(object):
'''Replicates the category class when we create roundups. Sqlalchemy methods
cannot be called on this class. If we did not create a new class type like this,
then we could not mess with the entries in that category without causing problems
in the database as a whole. DO NOT use this class for anything except creating
roundups.'''
@classmethod
def from_normal_category(cls, category: Category):
return cls(category_id = category.category_id,
name=category.name, section_id = category.section_id, entries = [])
def __init__(self, category_id, name, section_id, entries=[]):
self.category_id = category_id
self.name = name
self.entries = entries
self.section_id = section_id
def __repr__(self):
return f'ArtCat(category_id={self.category_id}, name={self.name})'#.format(self.category_id, self.name)
def export_roundup(title, start_date, end_date, filename, intro=None, min_category=1, max_category=21):
'''Exports a docx roundup'''
new_roundup = Roundup.prep_export(title=title,
start_date=start_date, end_date=end_date,
filename=filename,
min_category=min_category,
max_category=max_category,
intro=intro)
try:
new_roundup.export_docx()
print('Export successful')
except Exception as e:
print(e)
def create_docx_roundup(args, session=None):
#we only need a session if we are looking up the introduction
line=''
if not args.title:
title = btc.read_text('Enter title or "." to return to main menu: ')
if title == '.': return
else:
title=' '.join(args.title)
if not args.introduction:
if args.introduction_id:
intro = session.query(Introduction).filter(Introduction.introduction_id==args.introduction_id).first()
#print(args.introduction_id)
#print(intro)
args.introduction = intro.text
#print(args.introduction)
else:
args.introduction=None
if not args.date_range:
start_date = btc.read_date('Enter start date "(MM/DD/YYYY)": ')
end_date = btc.read_date('Enter end_date "MM/DD/YYYY": ')
else:
start_date = parse(args.date_range[0]).date()
end_date = parse(args.date_range[1]).date()
if not args.filename:
args.filename = btc.read_text('Enter filename or "." to return to main menu: ')
#call the export_roundup function to export a docx roundup
export_roundup(title=title, start_date=start_date,#parse(args.date_range[0]).date(),
end_date=end_date, filename=args.filename,
intro=args.introduction)
#create section
def add_category(session, category_name):
result = get(session=session, model=Category, name=category_name)
if result != None:
print('Category exists')
return
else:
new_category = Category.from_input(category_name=category_name, session=session)
confirm_choice = btc.read_int_ranged(f'Add {new_category.name}? 1 to add, 2 to cancel: ', 1, 2)
if confirm_choice == 1:
session.add(new_category)
session.commit()
print(f'{new_category.name} added to database')#.format(new_category.name))
elif confirm_choice == 2:
print('Category add cancelled')
return
def new_cat_with_entry(session, cmdobj, category_name, section_id):
'''Creates a new category when we're in the process of making an entry'''
make_cat = lambda x, y: Category(name=x, section_id=y)
new_category = make_cat(x=category_name, y=section_id)
try:
session.add(new_category)
session.commit()
#new_cat_style = cmd2.style(text=new_category, bg=cmd2.bg.blue,
# fg=cmd2.fg.white, bold=True)
#cmdobj.poutput(new_cat_style)
return None
#return new_category
except Exception as e:
cmdobj.poutput(e)
warning_msg = cmd2.style(text=f'Category creation failed for {category_name}')
cmdobj.poutput(warning_msg)
return None
def add_item(session, search_type, new_name):
"""session is the current active session, search_type is the type of item, while
new_name is the current type of item to add"""
new_name=new_name.lower()
search_types = {'author': Author, 'keyword': Keyword,
'section': Section}
result = get(session=session, model=search_types[search_type], name=new_name)
if result != None:
print('Item exists')
else:
confirm_choice = btc.read_int_ranged(f'Add {new_name}? 1 to add, 2 to cancel', 1, 2)
if confirm_choice == 1:
new_item=get_or_create(session=session, model=search_types[search_type], name=new_name)
#session.add(new_keyword)
#session.commit()
print(f'{new_item} added to database')#.format(new_item))
elif confirm_choice == 2:
print('add cancelled')
return
def add_pub_or_cat(session, add_type, new_name, second_item):
'''use this one for the CLI'''
add_type = add_type.lower()
add_types = {'publication': Publication, 'category': Category}
#item_twos = {'publication': 'url', 'category': 'section_id'}
result = get(session=session, model=add_types.get(add_type), name=new_name, second_item=second_item)
if result != None:
print(f'{add_type} exists')#.format(add_type))
print(result)
return
else:
confirm_choice = btc.read_int_ranged(f'Add {new_name}? 1 to add, 2 to cancel', 1, 2)
if confirm_choice == 1:
get_or_create(session, model=add_types.get(add_type), name=new_name,
second_item=second_item)
elif confirm_choice == 2:
print(f'{add_type} add cancelled')#.format(add_type))
return
def add_cat(session, line):
'''Takes input from the CLI and passes it to the add_pub_or_cat function'''
try:
new_name, second_item = line.split()
add_pub_or_cat(session=session, add_type='category',
new_name=new_name, second_item=second_item)
return True
except IndexError as e:
print(e)
return False
def add_pub(session, line):
'''Takes input from the CLI and passes it to the add_pub_or_cat function'''
try:
new_name, second_item = line.split('|')
add_pub_or_cat(session=session, add_type='publication',
new_name=new_name, second_item=second_item)
return True
except IndexError as e:
print(e)
return False
def add_publication(session, keyword_text):
result = get(session=session, model=Keyword, word=keyword_text)
if result != None:
print('Publication exists')
return
else:
new_keyword = Publication(pub_name=keyword_text)
confirm_choice = btc.read_int_ranged(f'Add {new_keyword.pub_name}? 1 to add, 2 to cancel', 1, 2)
if confirm_choice == 1:
session.add(new_keyword)
session.commit()
print(f'{new_keyword.word} added to database')#.format(new_keyword.word))
elif confirm_choice == 2:
print('Keyword add cancelled')
return
#modify articles
def add_keyword_to_article(session, new_keyword, entry_id=None):##model=Keyword):
"""Add a keyword to an existing article, the keyword is appended to the article's
keywords attribute"""
#new_keyword = btc.read_text('Enter new keyword: ')
#make sure the keyword doesn't already exist
if entry_id == None:
entry_id = btc.read_int(prompt='Find an entry by ID: ')
entry_result = session.query(Entry).filter(Entry.entry_id==entry_id).scalar()
if entry_result != None:
print('Entry found: ')
print(entry_result)
#new_keyword=btc.read_text('Enter new keyword: ')
edit_choice = btc.read_int_ranged(f'Add {new_keyword} to this article? (1 for yes, 2 for no): ', 1, 2)
if edit_choice == 1:
keyword_result = session.query(Keyword).filter(Keyword.word.like(f'%{new_keyword}%')).all()#.format(new_keyword))).all()
if len(keyword_result) >= 1:
print('Keyword exists')
print(keyword_result)
print('Entry found:')
print(entry_result)
keywords = it.chain(keyword_result)
while True:
#we do this loop if the keyword exists
try:
item = next(keywords)
print(item)
except StopIteration:
print('No more keywords left')
item_choice = btc.read_int_ranged('Is this the keyword you want? (1-yes, 2-continue, 3-quit)',
1, 3)
#1 select
if item_choice == 1:
try:
assert item not in entry_result.keywords
except AssertionError:
print('Keyword already attached to article')
print('Returning to main menu')
return
entry_result.keywords.append(item)
session.commit()
print('Keyword added successfully')
break
elif item_choice == 2:
#continue
continue
elif item_choice == 3:
print('Keyword add cancelled, return to main menu')
return
elif len(keyword_result) ==0:
print('Keyword does not exist')
kw = Keyword(word=new_keyword)
make_keyword_choice = btc.read_int_ranged(f'Create {kw} as a new keyword for ? {entry_result.entry_name} (1 yes, 2 no)',1, 2)
if make_keyword_choice == 1:
entry_result.keywords.append(kw)
session.commit()
print('Keyword add completed')
elif make_keyword_choice == 2:
print('Add keyword cancelled')
return
elif edit_choice == 2:
print('Keyword edit cancelled, returning to main menu')
return
elif entry_result == None:
print('Entry not found, returning to main menu')
return
def delete_entry_keyword(session, entry_id):
'''Delete a keyword from an existing article by popping it from the keyword list'''
entry_result = session.query(Entry).filter(Entry.entry_id==entry_id).scalar()
if entry_result != None:
article_keywords = it.cycle(entry_result.keywords)
while True:
pprint.pprint(entry_result.keywords)
activeItem = next(article_keywords)
print('Enter 1 to delete keyword, 2 to continue, 3 to exit to main menu')
delete_choice = btc.read_int_ranged(f'Delete {activeItem} from the keywords?', 1, 3)
if delete_choice == 1:
entry_result.keywords.remove(activeItem)
session.commit()
elif delete_choice == 2:
continue
elif delete_choice == 3:
print('Returning to main menu')
break
else:
print('Not found, return to main menu')
return
def make_article(article: str) -> np.Article:
article = np.Article(article)
article.build()
return article
def get_or_create(session, model, **kwargs):
'''If an object is present in the database, it returns the object.
Otherwise, it creates a new instance of that object'''
instance = session.query(model).filter_by(**kwargs).first()
if instance:
return instance
else:
instance = model(**kwargs)
session.add(instance)
session.commit()
return instance
#read section - functions associated with reading items]
def get(session, model, **kwargs):
'''If an object is present in the database, it returns the object.
Otherwise, it creates a new instance of that object'''
instance = session.query(model).filter_by(**kwargs).scalar()
return instance
def check_date(article):
'''Check to see if the date is there in the article'''
try:
assert article.publish_date, 'No publish date found'
return article.publish_date
except AssertionError:
return None
def create_date(article):
'''Checks to see if the date is there by calling new_date,
then if there is no date, it asks the user for input'''
new_date = check_date(article)
if new_date == None:
dateObj = input('Enter the date mm/dd/yyyy: ')
new_date = parse(dateObj)
#return new_date
else:
new_date = input('Enter date (mm/dd/yyyy): ')
new_date = parse(new_date)
return new_date
def display_categories(section_id=None):
query = dal.session.query(Category)
if section_id != None:
query = query.filter(Category.section_id == section_id)
query = query.all()
print('Categories: ')
cat_map = map(str, query)
print('\n'.join(cat_map))
def display_sections(cmdobj=None):
query = dal.session.query(Section).all()
section_map = map(str, query)
if cmdobj==None:
print('Sections: ')
print('\n'.join(section_map))
else:
section_heading = cmd2.style('Sections:', fg=cmd2.fg.white, bg=cmd2.bg.black, bold=True)
cmdobj.poutput(section_heading)
section_str = cmd2.style('\n'.join(section_map), fg=cmd2.fg.white, bg=cmd2.bg.black)
cmdobj.poutput(section_str)
def get_description():
description = input('Enter article description (max 500 characters): ')
return description
def get_sections():
'''Return a list of all the sections in the program'''
query = dal.session.query(Section).all()
return query
def get_categories(session, section_id=None):
'''Return a list of all the categories in the program'''
query = session.query(Category)
if section_id == None:
query = session.query(Category).all()
else:
query = query.filter(Category.section_id == section_id).all()
return query
def count_articles(line, session):
'''Takes the input from article_count in cmd_roundup.ipynb and determines
if there is more than one article.'''
try:
start_date, end_date = line.split() #tuple unpacking means the first and last elements are taken
date_range_count(start_date=start_date, end_date=end_date,
session=session)
except ValueError:
article_count(session=session)
def article_count(session):
query = session.query(Category.name, func.count(Entry.entry_id))
query= query.outerjoin(Entry).group_by(Category.name)
query = query.order_by(func.count(Entry.entry_id))
query = query.all()
for row in query[::-1]:
print(row)
undescribed_articles=session.query(Entry).filter(Entry.description.like('%not specified%')).all()
print('Undescribed articles', len(undescribed_articles))
def date_range_count(start_date, end_date, session):
'''Combine date_range_count and article_count'''
#print(line)
try:
#line = line.split(' ')
start_date, end_date = parse(start_date), parse(end_date)
start_date = start_date.date()
end_date = end_date.date()
print('start date:', start_date)
print('end date:', end_date)
except IndexError as e:
print(e)
return
query = session.query(Category.name, func.count(Entry.entry_id))
query= query.outerjoin(Entry).group_by(Category.name)
query = query.filter(Entry.date >= start_date, end_date <= end_date)
#query = query.filter(Entry.date <= end_date)
query = query.order_by(func.count(Entry.entry_id))
query = query.all()
undesc = session.query(Entry).filter(Entry.date >= start_date) #get number of undescribed articles
undesc = undesc.filter(Entry.date <= end_date)
undesc = undesc.filter(Entry.description.like('%not specified%')).all()
undesc_num = len(undesc)
total = functools.reduce(lambda x, y: x+y,[row[1] for row in query])
for row in query[::-1]:
print(row)
print(total, f'articles total from {start_date} to {end_date}')
print(f'Undescribed articles: {undesc_num}')
def date_range_count2(start_date, end_date, session, cmdobj):
'''Combine date_range_count and article_count'''
#print(line)
try:
#line = line.split(' ')
start_date, end_date = parse(start_date), parse(end_date)
start_date = start_date.date()
end_date = end_date.date()
intro=cmd2.style('Entry Count', fg=cmd2.fg.black, bg=cmd2.bg.white, bold=True)
sdate = cmd2.style(text=f'Start date: {start_date}',fg=cmd2.fg.green, bg=cmd2.bg.white, bold=True)
edate = cmd2.style(text=f'End date: {end_date}', fg=cmd2.fg.red, bg=cmd2.bg.white, bold=True)
cmdobj.poutput(intro)
cmdobj.poutput(sdate)
cmdobj.poutput(edate)
#print('start date:', start_date)
#print('end date:', end_date)
except IndexError as e:
print(e)
return
ent_query = session.query(Entry)
ent_query = ent_query.filter(Entry.date >= start_date)
ent_query = ent_query.filter(Entry.date <= end_date)
result = ent_query.all()
mycount = Counter([i.category_name for i in result])
pprint.pprint(mycount)
def articles_needed(start_date, end_date, session):
min_articles_cat = 5
'''Combine date_range_count and article_count'''
#print(line)
try:
#line = line.split(' ')
start_date, end_date = parse(start_date), parse(end_date)
start_date = start_date.date()
end_date = end_date.date()
print('start date:', start_date)
print('end date:', end_date)
except IndexError as e:
print(e)
return
query = session.query(Category.name, func.count(Entry.entry_id))
query= query.outerjoin(Entry).group_by(Category.name)
query = query.filter(Entry.date >= start_date, end_date <= end_date)
#query = query.filter(Entry.date <= end_date)
query = query.order_by(func.count(Entry.entry_id))
query = query.all()
#total = functools.reduce(lambda x, y: x+y,[row[1] for row in query])
articles_needed = {}
for row in query[::-1]:
#print(row)
if row[1] < 5:
#print(row, '')
articles_needed[row[0]] = (min_articles_cat - row[1])
pprint.pprint(articles_needed)
#print(articles_needed)
#for k, v in articles_needed:
#print('{0}: {1} articles, {2} more articles needed'.format(k, v[0], v[1]))
#print(total, 'articles total from {0} to {1}'.format(start_date, end_date))
def find_introduction(args, session, cmdobj):
'''Takes arguments from the ui.py module
args includes args.introduction_id, args.name, and args.text
only args.introduction_id will be implemented at this present stage'''
if not args.introduction_id:
no_intro_id = cmd2.style('No introduction ID found', bg=cmd2.bg.red,
fg=cmd2.fg.white, bold=True)
raise Exception(no_intro_id)
else:
get_intro = lambda x: session.query(Introduction).filter(Introduction.introduction_id==x).one()
intro_result = get_intro(args.introduction_id)
result_style = lambda x: cmd2.style(text=x, bg=cmd2.bg.white,
fg=cmd2.fg.black, bold=False)
cmdobj.poutput(result_style(intro_result))
def find_entry(args, session, cmdobj):
if args.entry_id and args.id_range:
raise Exception('Must be either id or id range')
elif args.date and args.date_range:
raise Exception('Must be either date or date range')
else:
query = session.query(Entry)
if args.category_id:
query = query.filter(Entry.category_id == args.category_id)
if args.category_name:
print(args.category_name)
cat_name = ' '.join(args.category_name)
cat_query = session.query(Category)
cat_query = cat_query.filter(Category.name.like(f'%{cat_name}%')).first()
print(cat_query)
cat_id = cat_query.id_value
query = query.filter(Entry.category_id == cat_id)
if args.id_range:
query = query.filter(Entry.entry_id >= args.id_range[0],
Entry.entry_id <= args.id_range[1])
if args.entry_id:
query = query.filter(Entry.entry_id == args.entry_id)
if args.date:
date = parse(args.date).date()
query = query.filter(Entry.date == date)
if args.date_range:
query = query.filter(Entry.date >= parse(args.date_range[0]).date(),
Entry.date <= parse(args.date_range[1]).date())
if args.url:
query = query.filter(Entry.url.like(f'%{args.url}%'))
if args.title:
print('args.title', args.title)
query = query.filter(Entry.entry_name.like(f'%{args.title}%'))
if args.publication_id:
query = query.filter(Entry.publication_id==args.publication_id)
if args.publication_title:
pub_query = session.query(Publication).filter(Publication.title.like(f'%{args.publication_title}%')).first()
pub_id = pub_query.publication_id
query=query.filter(Entry.publication_id == pub_id)
#query=query.filter(Entry.publication.title.like(f'%{args.publication_title}%'))
result = query.all()
result_total = len(result)
if result_total == 0:
print('no entries found')
return
result_cycle = it.cycle(result)
print(f'{result_total} entries found')
info_choice = btc.read_int_ranged('1 to view results, 2 to cancel: ', 1, 2)
if info_choice == 1:
while True:
next_item = next(result_cycle)
continue_choice = btc.read_int_ranged(f'1 to view {next_item.name}, 2 to continue, 3 to quit: ', 1, 3)
#print(next(result_cycle).name)
if continue_choice == 1:
#print(next(result_cycle))
print(next_item)
edit_choice = btc.read_int_ranged(f'1-edit {next_item.name}, 2-(continue) 3-quit: ', 1, 3)
if edit_choice == 1:
edit_entry2(session=session, entry_id=next_item.entry_id, cmdobj=cmdobj)
elif edit_choice == 2:
continue
elif edit_choice == 3:
print('Edit cancelled, return to main menu')
return
elif continue_choice == 2:
continue
elif continue_choice == 3:
print('returning to main menu')
break
def find_section(args, session):
query = session.query(Section)
if args.section_id:
query = query.filter(Section.section_id==args.section_id)
if args.name:
query = query.filter(Section.name.like(f'%{args.name}%'))
result = query.all()
result_total = len(result)
if result_total == 0:
print('no sections found')
return
result_cycle = it.cycle(result)
print(f'{result_total} sections found')
info_choice = btc.read_int_ranged('1 to view results, 2 to cancel: ', 1, 2)
if info_choice == 1:
while True:
continue_choice = btc.read_int_ranged('1 to view next, 2 to quit: ', 1, 2)
print(next(result_cycle).name)
if continue_choice == 1:
print(next(result_cycle))
elif continue_choice == 2:
print('returning to main menu')
break
def find_keyword(args, session):
query = session.query(Keyword)
if args.keyword_id:
query = query.filter(Keyword.keyword_id==args.keyword_id)
if args.word:
query = query.filter(Keyword.word.like(f'%{args.word}%'))
result = query.all()
result_total = len(result)
if result_total == 0:
print('no keywords found')
return
result_cycle = it.cycle(result)
print(f'{result_total} keywords found')
info_choice = btc.read_int_ranged('1 to view results, 2 to cancel: ', 1, 2)
if info_choice == 1:
while True:
continue_choice = btc.read_int_ranged('1 to view next, 2 to quit: ', 1, 2)
print(next(result_cycle).name)
if continue_choice == 1:
print(next(result_cycle))
elif continue_choice == 2:
print('returning to main menu')
break
def get_category(category_name, session):
'''Gets the category for the create article function'''
category_name = ' '.join(category_name)
query = session.query(Category).filter(Category.name.like(f'%{category_name}%')).first()
print(query)
return query
def get_category_name(category_name, session):
'''Gets the category for the create article function'''
#category_name = ' '.join(category_name)
query = session.query(Category).filter(Category.name.like(f'%{category_name}%')).first()
#print(query)
return query
def find_category(args, session):
query = session.query(Category)
if args.category_id:
query = query.filter(Category.category_id == args.category_id)
if args.category_name:
print(args.category_name)
category_name = ' '.join(args.category_name)
print(category_name)
query = query.filter(Category.name.like(f"%{category_name}%"))
if args.section_id:
query = query.filter(Category.section_id == args.section_id)
result = query.all()
result_total = len(result)
if result_total == 0:
print('no categories found')
return
result_cycle = it.cycle(result)
print(f'{result_total} categories found')
info_choice = btc.read_int_ranged('1 to view results, 2 to cancel: ', 1, 2)
if info_choice == 1:
while True:
continue_choice = btc.read_int_ranged('1 to view next, 2 to quit: ', 1, 2)
print(next(result_cycle).name)
if continue_choice == 1:
print(next(result_cycle))
elif continue_choice == 2:
print('returning to main menu')
break
def find_publication(args, session):
#add publication search
query = session.query(Publication)
if args.publication_id:
query = query.filter(Publication.id_value == args.publication_id)
if args.title:
query = query.filter(Publication.title == args.title)
if args.url:
query = query.filter(Publication.url.like(f'%{args.url}%'))
result = query.all()
print(result)
results = it.cycle(result)
active_item = next(results)
edit_choice = btc.read_int_ranged(prompt=f'Edit publication {active_item.title} (1-y, 2-n)? ',
min_value=1,max_value=2)
if edit_choice == 1:
warnings.warn('Edit publication under development')
edit_single_pub(session=session, active_item=active_item)
#pass
def edit_single_pub(session, active_item):
'''Edit a single publication'''
while True:
print(f'''\n
Publication ID: {active_item.id_value}
Title: {active_item.name_value}
Link: {active_item.url}''')
edit_choice = btc.read_int_ranged('Edit title - 1, Edit link - 2, 3-next_publication: ', 1, 3)
if edit_choice == 1:
view_articles_choice = btc.read_int_ranged('Type 1 to view entries for this publication, 2 to skip', 1, 2)
if view_articles_choice == 1:
for i in active_item.entries:
print(i)
# print(f'Entries:\n{active_item.entries}')
else:
print('Entries display not needed')
new_title = btc.read_text('Enter new title or "." to cancel: ')
print(new_title)
if new_title != '.':
active_item.title = new_title
session.commit()
#else:
#new_desc = 'Not specified' #if the user doens't edit it
elif edit_choice == 2:
new_url = btc.read_text('Enter new url or "." to cancel: ')
if new_url == ".":
print('Edit cancelled')
break
else:
edit_second_item(session=session, model='publication',
id_value=active_item.id_value,
new_second_value=new_url)
elif edit_choice == 3:
break
# def search_exact_name(line, session):
# search_types = {'entry': Entry, 'category': Category, 'publication': Publication,
# 'section': Section, 'keyword':Keyword}
# #app.search_exact_name(line=line)
# line = line.split(' ')
# search_type = line[0].lower() #make it lowercase to fit in the dictionary
# value= ' '.join(line[1:]) #The first word is the search type, so we want the remainder of the words
# #to be the title
# if search_type in search_types:
# #print(True)
# result = get(session=session, model=search_types[search_type], name_value=value)
# print(result)
# else:
# print('Invalid search type, return to main menu')
#def search_by_id(search_type, item_id, session):
# '''This will serve as a universal function to get an 1 by its id'''
# search_type = search_type.lower()
# search_types = {'entry': Entry, 'category': Category,
# 'publication': Publication, 'section': Section,
# 'keyword': Keyword, 'author': Author}
# item_types = {'entry': 'keywords and authors', 'category': 'entries',
# 'publication': 'entries', 'section': 'categories',
# 'keyword': 'entries', 'author': 'entries'}
# if search_type in search_types:
# result = get(session=session, model=search_types[search_type], id_value=item_id)
# print(result)
# info_choice = btc.read_int_ranged('View more information? (1-yes, 2-quit) ',1,2)
# if info_choice == 1:
# misc = it.cycle(result.items)
# while True:
# print(f'Cycles through {item_types[search_type]}')#.format(item_types[search_type]))
# continue_choice = btc.read_int_ranged('1 to view next, 2 to quit', 1, 2)
# if continue_choice == 1:
# print(next(misc))
# elif continue_choice == 2:
# print('returning to main menu')
# break
# else:
# print('Invalid search type. Return to main menu.')
#def name_search(session, line):
# category_result = session.query(Category).filter(Category.name.like(f'%{line}%'))#.format(line))).all()
# section_result = session.query(Section).filter(Section.name.like(f'%{line}%'))#.format(line))).all()
# entry_result = session.query(Entry).filter(Entry.entry_name.like(f'%{line}%'))#.format(line))).all()
# keyword_result = session.query(Keyword).filter(Keyword.word.like(f'%{line}%')).all()
# publication_result = session.query(Publication).filter(Publication.title.like(f'%{line}%')).all()
# author_result = session.query(Author).filter(Author.author_name.like(f'%{line}%')).all()
# result = it.cycle(category_result+section_result+entry_result+keyword_result+publication_result+author_result)
# #result2 = it.cycle(result)
# while True:
# try:
# pprint.pprint(next(result))
# except StopIteration:
# print('no more left')
# continue_choice = btc.read_int_ranged('1 to view more results, 2 to return to main menu', 1,2)
# if continue_choice != 1:
# break
#
#def name_search2(session, line):
# category_result = session.query(Category).filter(Category.name.like(f'%{line}%')).all()
# section_result = session.query(Section).filter(Section.name.like(f'%{line}%')).all()#.format(line))).all()
# entry_result = session.query(Entry).filter(Entry.entry_name.like(f'%{line}%')).all()#.format(line))).all()
# keyword_result = session.query(Keyword).filter(Keyword.word.like(f'%{line}%')).all()#.format(line))).all()
# publication_result = session.query(Publication).filter(Publication.title.like(f'%{line}%')).all()#like('%{0}%'.format(line))).all()
# author_result = session.query(Author).filter(Author.author_name.like(f'%{line}%')).all()
# result = it.cycle(category_result+section_result+entry_result+keyword_result+publication_result+author_result)
# #result2 = it.cycle(result)
# while True:
# try:
# pprint.pprint(next(result))
# except StopIteration:
# print('no more left')
# continue_choice = btc.read_int_ranged('1 to view more results, 2 to return to main menu', 1,2)
# if continue_choice != 1:
# break
def get_articles_for_roundup(start_date, end_date, category_id):
'''
Do not mess with this function without absolute certainty that you will
not break the roundup generation process.
'''
query = dal.session.query(Category)
query = query.filter(Category.category_id == category_id)
query = query.first()
return query
def get_entries_by_category(session, line):
result = session.query(Category)
result = result.filter(Category.name.like(f'%{line}%'))
try:
result = result.one()
except MultipleResultsFound:
print('Multiple results found')
potentials = it.cycle(result)
while True:
potential_result = next(potentials)
print(potential_result)
result_choice = btc.read_bool(decision='is this the category? (y-yes, n-no): ',
yes='y', no='n',
yes_option='select', no_option='continue')
if result_choice == True:
result = potential_result
break
else:
continue
print(result)
review_choice = btc.read_bool(decision=f'View articles from {result}',
yes='y', no='n',
yes_option='continue', no_option='cancel')
print(review_choice)
if review_choice == True:
entries_by_cat = it.cycle(result.entries)
while True:
continue_choice = btc.read_bool(decision=f'View next article from {result}',
yes='y', no='n',
yes_option='continue', no_option='cancel')
if continue_choice == True:
print(next(entries_by_cat))
elif continue_choice == False:
print('Returning to main menu')
break
#EDIT Publication
def edit_pub(publication_id, session, new_title):
query=session.query(Publication)
query=query.filter(Publication.id_value == publication_id)
result=query.one()
edit_choice = btc.read_int_ranged(f'Replace title {result.name} with {new_title}: ', 1, 2)
if edit_choice == 1: