forked from datalogics-dans/server_core
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclassifier.py
More file actions
3932 lines (3529 loc) · 132 KB
/
classifier.py
File metadata and controls
3932 lines (3529 loc) · 132 KB
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
# encoding: utf-8
# If the genre classification does not match the fiction classification, throw
# away the genre classifications.
#
# E.g. "Investigations -- nonfiction" maps to Mystery, but Mystery
# conflicts with Nonfiction.
# SQL to find commonly used DDC classifications
# select count(editions.id) as c, subjects.identifier from editions join identifiers on workrecords.primary_identifier_id=workidentifiers.id join classifications on workidentifiers.id=classifications.work_identifier_id join subjects on classifications.subject_id=subjects.id where subjects.type = 'DDC' and not subjects.identifier like '8%' group by subjects.identifier order by c desc;
# SQL to find commonly used classifications not assigned to a genre
# select count(identifiers.id) as c, subjects.type, substr(subjects.identifier, 0, 20) as i, substr(subjects.name, 0, 20) as n from workidentifiers join classifications on workidentifiers.id=classifications.work_identifier_id join subjects on classifications.subject_id=subjects.id where subjects.genre_id is null and subjects.fiction is null group by subjects.type, i, n order by c desc;
import logging
import json
import os
import pkgutil
import re
import urllib
from collections import (
Counter,
defaultdict,
)
from nose.tools import set_trace
from sqlalchemy.orm.session import Session
from sqlalchemy.sql.expression import and_
from psycopg2.extras import NumericRange
base_dir = os.path.split(__file__)[0]
resource_dir = os.path.join(base_dir, "resources")
NO_VALUE = "NONE"
NO_NUMBER = -1
class Classifier(object):
"""Turn an external classification into an internal genre, an
audience, an age level, and a fiction status.
"""
DDC = "DDC"
LCC = "LCC"
LCSH = "LCSH"
FAST = "FAST"
OVERDRIVE = "Overdrive"
THREEM = "3M"
BISAC = "BISAC"
TAG = "tag" # Folksonomic tags.
# Appeal controlled vocabulary developed by NYPL
NYPL_APPEAL = "NYPL Appeal"
GRADE_LEVEL = "Grade level" # "1-2", "Grade 4", "Kindergarten", etc.
AGE_RANGE = "schema:typicalAgeRange" # "0-2", etc.
THETA_AUDIENCE = "Theta Audience"
AXIS_360_AUDIENCE = "Axis 360 Audience"
# We know this says something about the audience but we're not sure what.
# Could be any of the values from GRADE_LEVEL or AGE_RANGE, plus
# "YA", "Adult", etc.
FREEFORM_AUDIENCE = "schema:audience"
GUTENBERG_BOOKSHELF = "gutenberg:bookshelf"
TOPIC = "schema:Topic"
PLACE = "schema:Place"
PERSON = "schema:Person"
ORGANIZATION = "schema:Organization"
LEXILE_SCORE = "Lexile"
ATOS_SCORE = "ATOS"
INTEREST_LEVEL = "Interest Level"
AUDIENCE_ADULT = "Adult"
AUDIENCE_ADULTS_ONLY = "Adults Only"
AUDIENCE_YOUNG_ADULT = "Young Adult"
AUDIENCE_CHILDREN = "Children"
# A book for a child younger than 14 is a children's book.
# A book for a child 14 or older is a young adult book.
YOUNG_ADULT_AGE_CUTOFF = 14
AUDIENCES_JUVENILE = [AUDIENCE_CHILDREN, AUDIENCE_YOUNG_ADULT]
AUDIENCES_ADULT = [AUDIENCE_ADULT, AUDIENCE_ADULTS_ONLY]
AUDIENCES = set([AUDIENCE_ADULT, AUDIENCE_ADULTS_ONLY, AUDIENCE_YOUNG_ADULT,
AUDIENCE_CHILDREN])
SIMPLIFIED_GENRE = "http://librarysimplified.org/terms/genres/Simplified/"
SIMPLIFIED_FICTION_STATUS = "http://librarysimplified.org/terms/fiction/"
# TODO: This is currently set in model.py in the Subject class.
classifiers = dict()
@classmethod
def nr(cls, lower, upper):
"""Turn a 2-tuple into an inclusive NumericRange."""
# Just in case the upper and lower ranges are mixed up,
# and no prior code caught this, un-mix them.
if lower and upper and lower > upper:
lower, upper = upper, lower
return NumericRange(lower, upper, '[]')
@classmethod
def lookup(cls, scheme):
"""Look up a classifier for a classification scheme."""
return cls.classifiers.get(scheme, None)
@classmethod
def name_for(cls, identifier):
"""Look up a human-readable name for the given identifier."""
return None
@classmethod
def classify(cls, subject):
"""Try to determine genre, audience, target age, and fiction status
for the given Subject.
"""
identifier = cls.scrub_identifier(subject.identifier)
if subject.name:
name = cls.scrub_name(subject.name)
else:
name = identifier
fiction = cls.is_fiction(identifier, name)
audience = cls.audience(identifier, name)
target_age = cls.target_age(identifier, name)
if target_age == cls.nr(None, None):
target_age = cls.default_target_age_for_audience(audience)
return (cls.genre(identifier, name, fiction, audience),
audience,
target_age,
fiction,
)
@classmethod
def scrub_identifier(cls, identifier):
"""Prepare an identifier from within a call to classify().
This may involve data normalization, conversion to lowercase,
etc.
"""
return Lowercased(identifier)
@classmethod
def scrub_name(cls, name):
"""Prepare a name from within a call to classify()."""
return Lowercased(name)
@classmethod
def genre(cls, identifier, name, fiction=None, audience=None):
"""Is this identifier associated with a particular Genre?"""
return None
@classmethod
def genre_match(cls, query):
"""Does this query string match a particular Genre, and which part
of the query matches?"""
return None, None
@classmethod
def is_fiction(cls, identifier, name):
"""Is this identifier+name particularly indicative of fiction?
How about nonfiction?
"""
if "nonfiction" in name:
return False
if "fiction" in name:
return True
return None
@classmethod
def audience(cls, identifier, name):
"""What does this identifier+name say about the audience for
this book?
"""
if 'juvenile' in name:
return cls.AUDIENCE_CHILDREN
elif 'young adult' in name or "YA" in name.original:
return cls.AUDIENCE_YOUNG_ADULT
return None
@classmethod
def audience_match(cls, query):
"""Does this query string match a particular Audience, and which
part of the query matches?"""
return (None, None)
@classmethod
def target_age(cls, identifier, name):
"""For children's books, what does this identifier+name say
about the target age for this book?
"""
return cls.nr(None, None)
@classmethod
def default_target_age_for_audience(cls, audience):
"""The default target age for a given audience.
We don't know what age range a children's book is appropriate
for, but we can make a decent guess for a YA book, for an
'Adult' book it's pretty clear, and for an 'Adults Only' book
it's very clear.
"""
if audience == Classifier.AUDIENCE_YOUNG_ADULT:
return cls.nr(14, 17)
elif audience in (
Classifier.AUDIENCE_ADULT, Classifier.AUDIENCE_ADULTS_ONLY
):
return cls.nr(18, None)
return cls.nr(None, None)
@classmethod
def default_audience_for_target_age(cls, nr):
if nr is None:
return None
lower = nr.lower
upper = nr.upper
if not lower and not upper:
return None
if lower and not nr.lower_inc:
lower += 1
if upper and not nr.upper_inc:
upper += 1
if not lower:
if upper > 18:
# e.g. "up to 20 years", though that doesn't
# make much sense.
return cls.AUDIENCE_ADULT
elif upper > cls.YOUNG_ADULT_AGE_CUTOFF:
# e.g. "up to 15 years"
return cls.AUDIENCE_YOUNG_ADULT
else:
# e.g. "up to 14 years"
return cls.AUDIENCE_CHILDREN
# At this point we can assume that lower is not None.
if lower >= 18:
return cls.AUDIENCE_ADULT
elif lower >= cls.YOUNG_ADULT_AGE_CUTOFF:
return cls.AUDIENCE_YOUNG_ADULT
elif lower >= 12 and (not upper or upper >= cls.YOUNG_ADULT_AGE_CUTOFF):
# Although we treat "Young Adult" as starting at 14, many
# outside sources treat it as starting at 12. As such we
# treat "12 and up" or "12-14" as an indicator of a Young
# Adult audience, with a target age that overlaps what we
# consider a Children audience.
return cls.AUDIENCE_YOUNG_ADULT
else:
return cls.AUDIENCE_CHILDREN
@classmethod
def and_up(cls, young, keyword):
"""Encapsulates the logic of what "[x] and up" actually means.
Given the lower end of an age range, tries to determine the
upper end of the range.
"""
if young is None:
return None
if not any(
[keyword.endswith(x) for x in
("and up", "and up.", "+", "+.")
]
):
return None
if young >= 18:
old = young
elif young >= 12:
# "12 and up", "14 and up", etc. are
# generally intended to cover the entire
# YA span.
old = 17
elif young >= 8:
# "8 and up" means something like "8-12"
old = young + 4
else:
# Whereas "3 and up" really means more
# like "3 to 5".
old = young + 2
return old
class GradeLevelClassifier(Classifier):
# How old a kid is when they start grade N in the US.
american_grade_to_age = {
# Preschool: 3-4 years
'preschool' : 3,
'pre-school' : 3,
'p' : 3,
'pk' : 4,
# Easy readers
'kindergarten' : 5,
'k' : 5,
'0' : 5,
'first' : 6,
'1' : 6,
'second' : 7,
'2' : 7,
# Chapter Books
'third' : 8,
'3' : 8,
'fourth' : 9,
'4' : 9,
'fifth' : 10,
'5' : 10,
'sixth' : 11,
'6' : 11,
'7' : 12,
'8' : 13,
# YA
'9' : 14,
'10' : 15,
'11' : 16,
'12': 17,
}
# Regular expressions that match common ways of expressing grade
# levels.
grade_res = [
re.compile(x, re.I) for x in [
"grades? ([kp0-9]+) to ([kp0-9]+)?",
"grades? ([kp0-9]+) ?-? ?([kp0-9]+)?",
"gr\.? ([kp0-9]+) ?-? ?([kp0-9]+)?",
"grades?: ([kp0-9]+) to ([kp0-9]+)",
"grades?: ([kp0-9]+) ?-? ?([kp0-9]+)?",
"gr\.? ([kp0-9]+)",
"([0-9]+)[tnsr][hdt] grade",
"([a-z]+) grade",
r'\b(kindergarten|preschool)\b',
]
]
generic_grade_res = [
re.compile(r"([kp0-9]+) ?- ?([0-9]+)", re.I),
re.compile(r"([kp0-9]+) ?to ?([0-9]+)", re.I),
re.compile(r"^([0-9]+)\b", re.I),
re.compile(r"^([kp])\b", re.I),
]
@classmethod
def audience(cls, identifier, name, require_explicit_age_marker=False):
target_age = cls.target_age(identifier, name, require_explicit_age_marker)
return cls.default_audience_for_target_age(target_age)
@classmethod
def target_age(cls, identifier, name, require_explicit_grade_marker=False):
if (identifier and "education" in identifier) or (name and 'education' in name):
# This is a book about teaching, e.g. fifth grade.
return cls.nr(None, None)
if (identifier and 'grader' in identifier) or (name and 'grader' in name):
# This is a book about, e.g. fifth graders.
return cls.nr(None, None)
if require_explicit_grade_marker:
res = cls.grade_res
else:
res = cls.grade_res + cls.generic_grade_res
for r in res:
for k in identifier, name:
if not k:
continue
m = r.search(k)
if m:
gr = m.groups()
if len(gr) == 1:
young = gr[0]
old = None
else:
young, old = gr
# Strip leading zeros
if young and young.lstrip('0'):
young = young.lstrip("0")
if old and old.lstrip('0'):
old = old.lstrip("0")
young = cls.american_grade_to_age.get(young)
old = cls.american_grade_to_age.get(old)
if not young and not old:
return cls.nr(None, None)
if young:
young = int(young)
if old:
old = int(old)
if old is None:
old = cls.and_up(young, k)
if old is None and young is not None:
old = young
if young is None and old is not None:
young = old
if old and young and old < young:
young, old = old, young
return cls.nr(young, old)
return cls.nr(None, None)
@classmethod
def target_age_match(cls, query):
target_age = None
grade_words = None
target_age = cls.target_age(None, query, require_explicit_grade_marker=True)
if target_age:
for r in cls.grade_res:
match = r.search(query)
if match:
grade_words = match.group()
break
return (target_age, grade_words)
class InterestLevelClassifier(Classifier):
@classmethod
def audience(cls, identifier, name):
if identifier in ('lg', 'mg+', 'mg'):
return cls.AUDIENCE_CHILDREN
elif identifier == 'ug':
return cls.AUDIENCE_YOUNG_ADULT
else:
return None
@classmethod
def target_age(cls, identifier, name):
if identifier == 'lg':
return cls.nr(5,8)
if identifier in ('mg+', 'mg'):
return cls.nr(9,13)
if identifier == 'ug':
return cls.nr(14,17)
return None
class AgeClassifier(Classifier):
# Regular expressions that match common ways of expressing ages.
age_res = [
re.compile(x, re.I) for x in [
"age ([0-9]+) ?-? ?([0-9]+)?",
"age: ([0-9]+) ?-? ?([0-9]+)?",
"age: ([0-9]+) to ([0-9]+)",
"ages ([0-9]+) ?- ?([0-9]+)",
"([0-9]+) ?- ?([0-9]+) years?",
"([0-9]+) years?",
"ages ([0-9]+)+",
"([0-9]+) and up",
"([0-9]+) years? and up",
]
]
generic_age_res = [
re.compile("([0-9]+) ?- ?([0-9]+)", re.I),
re.compile(r"^([0-9]+)\b", re.I),
]
baby_re = re.compile("^baby ?- ?([0-9]+) year", re.I)
@classmethod
def audience(cls, identifier, name, require_explicit_age_marker=False):
target_age = cls.target_age(identifier, name, require_explicit_age_marker)
return cls.default_audience_for_target_age(target_age)
@classmethod
def target_age(cls, identifier, name, require_explicit_age_marker=False):
if require_explicit_age_marker:
res = cls.age_res
else:
res = cls.age_res + cls.generic_age_res
if identifier:
match = cls.baby_re.search(identifier)
if match:
# This is for babies.
upper_bound = int(match.groups()[0])
return cls.nr(0, upper_bound)
for r in res:
for k in identifier, name:
if not k:
continue
m = r.search(k)
if m:
groups = m.groups()
young = old = None
if groups:
young = int(groups[0])
if len(groups) > 1 and groups[1] != None:
old = int(groups[1])
if old is None:
old = cls.and_up(young, k)
if old is None and young is not None:
old = young
if young is None and old is not None:
young = old
if old > 99:
# This is not an age at all.
old = None
if young > 99:
# This is not an age at all.
young = None
if young > old:
young, old = old, young
return cls.nr(young, old)
return cls.nr(None, None)
@classmethod
def target_age_match(cls, query):
target_age = None
age_words = None
target_age = cls.target_age(None, query, require_explicit_age_marker=True)
if target_age:
for r in cls.age_res:
match = r.search(query)
if match:
age_words = match.group()
break
return (target_age, age_words)
class Axis360AudienceClassifier(Classifier):
TEEN_PREFIX = "Teen -"
CHILDRENS_PREFIX = "Children's -"
age_re = re.compile("Age ([0-9]+)-([0-9]+)$")
@classmethod
def audience(cls, identifier, name, require_explicit_age_marker=False):
if not identifier:
return None
if identifier == 'General Adult':
return Classifier.AUDIENCE_ADULT
elif identifier.startswith(cls.TEEN_PREFIX):
return Classifier.AUDIENCE_YOUNG_ADULT
elif identifier.startswith(cls.CHILDRENS_PREFIX):
return Classifier.AUDIENCE_CHILDREN
return None
@classmethod
def target_age(cls, identifier, name, require_explicit_age_marker=False):
if (not identifier.startswith(cls.TEEN_PREFIX)
and not identifier.startswith(cls.CHILDRENS_PREFIX)):
return cls.nr(None, None)
m = cls.age_re.search(identifier)
if not m:
return cls.nr(None, None)
young, old = map(int, m.groups())
if young > old:
young, old = old, young
return cls.nr(young, old)
# This is the large-scale structure of our classification system.
#
# If the name of a genre is a 2-tuple, the second item in the tuple is
# a list of names of subgenres.
#
# If the name of a genre is a 3-tuple, the genre is restricted to a
# specific audience (e.g. erotica is adults-only), and the third item
# in the tuple describes that audience.
COMICS_AND_GRAPHIC_NOVELS = u"Comics & Graphic Novels"
fiction_genres = [
u"Adventure",
u"Classics",
COMICS_AND_GRAPHIC_NOVELS,
u"Drama",
dict(name=u"Erotica", audiences=Classifier.AUDIENCE_ADULTS_ONLY),
dict(name=u"Fantasy", subgenres=[
u"Epic Fantasy",
u"Historical Fantasy",
u"Urban Fantasy",
]),
u"Folklore",
u"Historical Fiction",
dict(name=u"Horror", subgenres=[
u"Gothic Horror",
u"Ghost Stories",
u"Vampires",
u"Werewolves",
u"Occult Horror",
]),
u"Humorous Fiction",
u"Literary Fiction",
dict(name=u"LGBTQ Fiction", audiences=Classifier.AUDIENCE_ADULTS_ONLY),
dict(name=u"Mystery", subgenres=[
u"Crime & Detective Stories",
u"Hard-Boiled Mystery",
u"Police Procedural",
u"Cozy Mystery",
u"Historical Mystery",
u"Paranormal Mystery",
u"Women Detectives",
]),
u"Poetry",
u"Religious Fiction",
dict(name=u"Romance", subgenres=[
u"Contemporary Romance",
u"Gothic Romance",
u"Historical Romance",
u"Paranormal Romance",
u"Western Romance",
u"Romantic Suspense",
]),
dict(name=u"Science Fiction", subgenres=[
u"Dystopian SF",
u"Space Opera",
u"Cyberpunk",
u"Military SF",
u"Alternative History",
u"Steampunk",
u"Romantic SF",
u"Media Tie-in SF",
]),
u"Short Stories",
dict(name=u"Suspense/Thriller",
subgenres=[
u"Historical Thriller",
u"Espionage",
u"Supernatural Thriller",
u"Medical Thriller",
u"Political Thriller",
u"Psychological Thriller",
u"Technothriller",
u"Legal Thriller",
u"Military Thriller",
],
),
u"Urban Fiction",
u"Westerns",
u"Women's Fiction",
]
nonfiction_genres = [
dict(name=u"Art & Design", subgenres=[
u"Architecture",
u"Art",
u"Art Criticism & Theory",
u"Art History",
u"Design",
u"Fashion",
u"Photography",
]),
u"Biography & Memoir",
u"Education",
dict(name=u"Personal Finance & Business", subgenres=[
u"Business",
u"Economics",
u"Management & Leadership",
u"Personal Finance & Investing",
u"Real Estate",
]),
dict(name=u"Parenting & Family", subgenres=[
u"Family & Relationships",
u"Parenting",
]),
dict(name=u"Food & Health", subgenres=[
u"Bartending & Cocktails",
u"Cooking",
u"Health & Diet",
u"Vegetarian & Vegan",
]),
dict(name=u"History", subgenres=[
u"African History",
u"Ancient History",
u"Asian History",
u"Civil War History",
u"European History",
u"Latin American History",
u"Medieval History",
u"Middle East History",
u"Military History",
u"Modern History",
u"Renaissance & Early Modern History",
u"United States History",
u"World History",
]),
dict(name=u"Hobbies & Home", subgenres=[
u"Antiques & Collectibles",
u"Crafts & Hobbies",
u"Gardening",
u"Games",
u"House & Home",
u"Pets",
]),
u"Humorous Nonfiction",
dict(name=u"Entertainment", subgenres=[
u"Film & TV",
u"Music",
u"Performing Arts",
]),
u"Life Strategies",
u"Literary Criticism",
u"Periodicals",
u"Philosophy",
u"Political Science",
dict(name=u"Reference & Study Aids", subgenres=[
u"Dictionaries",
u"Foreign Language Study",
u"Law",
u"Study Aids",
]),
dict(name=u"Religion & Spirituality", subgenres=[
u"Body, Mind & Spirit",
u"Buddhism",
u"Christianity",
u"Hinduism",
u"Islam",
u"Judaism",
]),
dict(name=u"Science & Technology", subgenres=[
u"Computers",
u"Mathematics",
u"Medical",
u"Nature",
u"Psychology",
u"Science",
u"Social Sciences",
u"Technology",
]),
u"Self-Help",
u"Sports",
u"Travel",
u"True Crime",
]
class GenreData(object):
def __init__(self, name, is_fiction, parent=None, audience_restriction=None):
self.name = name
self.parent = parent
self.is_fiction = is_fiction
self.subgenres = []
if isinstance(audience_restriction, basestring):
audience_restriction = [audience_restriction]
self.audience_restriction = audience_restriction
def __repr__(self):
return "<GenreData: %s>" % self.name
@property
def self_and_subgenres(self):
yield self
for child in self.all_subgenres:
yield child
@property
def all_subgenres(self):
for child in self.subgenres:
for subgenre in child.self_and_subgenres:
yield subgenre
@property
def parents(self):
parents = []
p = self.parent
while p:
parents.append(p)
p = p.parent
return reversed(parents)
def has_subgenre(self, subgenre):
for s in self.subgenres:
if s == subgenre or s.has_subgenre(subgenre):
return True
return False
@property
def variable_name(self):
return self.name.replace("-", "_").replace(", & ", "_").replace(", ", "_").replace(" & ", "_").replace(" ", "_").replace("/", "_").replace("'", "")
@classmethod
def populate(cls, namespace, genres, fiction_source, nonfiction_source):
"""Create a GenreData object for every genre and subgenre in the given
list of fiction and nonfiction genres.
"""
for source, fiction in (
(fiction_source, True),
(nonfiction_source, False)):
for item in source:
subgenres = []
audience_restriction = None
name = item
if isinstance(item, dict):
name = item['name']
subgenres = item.get('subgenres', [])
audience_restriction = item.get('audience_restriction')
cls.add_genre(
namespace, genres, name, subgenres, fiction,
None, audience_restriction)
@classmethod
def add_genre(cls, namespace, genres, name, subgenres, fiction,
parent, audience_restriction):
"""Create a GenreData object. Add it to a dictionary and a namespace.
"""
if isinstance(name, tuple):
name, default_fiction = name
default_fiction = None
default_audience = None
if parent:
default_fiction = parent.is_fiction
default_audience = parent.audience_restriction
if isinstance(name, dict):
data = name
subgenres = data.get('subgenres', [])
name = data['name']
fiction = data.get('fiction', default_fiction)
audience_restriction = data.get('audience', default_audience)
if name in genres:
raise ValueError("Duplicate genre name! %s" % name)
# Create the GenreData object.
genre_data = GenreData(name, fiction, parent, audience_restriction)
if parent:
parent.subgenres.append(genre_data)
# Add the genre to the given dictionary, keyed on name.
genres[genre_data.name] = genre_data
# Convert the name to a Python-safe variable name,
# and add it to the given namespace.
namespace[genre_data.variable_name] = genre_data
# Do the same for subgenres.
for sub in subgenres:
cls.add_genre(namespace, genres, sub, [], fiction,
genre_data, audience_restriction)
def to_lane(self, _db, **args):
"""Turn this GenreData object into a Lane that matches
every book in the genre.
"""
from lane import Lane
if self.name and not 'full_name' in args:
args['full_name'] = self.name
if self.is_fiction:
args['fiction'] = self.is_fiction
if self.audience_restriction:
args['audiences'] = self.audience_restriction
if not 'subgenre_behavior' in args:
args['subgenre_behavior'] = Lane.IN_SUBLANES
args['genres'] = self
return Lane(_db, **args)
genres = dict()
GenreData.populate(globals(), genres, fiction_genres, nonfiction_genres)
class Lowercased(unicode):
"""A lowercased string that remembers its original value."""
def __new__(cls, value):
new_value = value.lower()
if new_value.endswith('.'):
new_value = new_value[:-1]
o = super(Lowercased, cls).__new__(cls, new_value)
o.original = value
return o
class ThreeMClassifier(Classifier):
# TODO:
# Readers / Beginner
# Readers / Chapter Books
# Any classification that starts with "FICTION" or "JUVENILE
# FICTION" will be counted as fiction. This is just the leftovers.
FICTION = set([
"Magic",
"Fables",
"Unicorns & Mythical",
])
# These are the most general categories, used if nothing more specific matches.
CATCHALL_PREFIXES = {
Adventure : [
"Action & Adventure/",
"FICTION/Adventure/",
"FICTION/War/",
"Men's Adventure/",
"Sea Stories",
],
Architecture : "ARCHITECTURE/",
Art : "ART/",
Antiques_Collectibles : "ANTIQUES & COLLECTIBLES/",
Biography_Memoir : [
"BIOGRAPHY & AUTOBIOGRAPHY/",
"Biography & Autobiography/",
],
Body_Mind_Spirit: [
"BODY MIND & SPIRIT/",
"MIND & SPIRIT/",
],
Personal_Finance_Business : "BUSINESS & ECONOMICS/",
Classics : [
"Classics/",
],
Cooking: [
"COOKING/",
"Cooking & Food",
"Cooking/",
],
Comics_Graphic_Novels : "COMICS & GRAPHIC NOVELS/",
Computers: [
"COMPUTERS/",
"Computers/",
],
Crafts_Hobbies : [
"CRAFTS & HOBBIES/",
],
Dystopian_SF : [
"Dystopian"
],
Games : [
"GAMES/",
],
Design: "DESIGN/",
Drama: "DRAMA/",
Education : "EDUCATION/",
Erotica: "Erotica/",
Espionage : "Espionage/",
Fantasy : [
"Fantasy/",
"Magic/",
"Unicorns & Mythical/"
],
Folklore : [
"Fables",
"Legends, Myths, Fables",
"Fairy Tales & Folklore",
],
Foreign_Language_Study : "FOREIGN LANGUAGE STUDY/",
Gardening : "GARDENING/",
Comics_Graphic_Novels : "Comics & Graphic Novels/",
Health_Diet : [
"HEALTH & FITNESS/",
"Health/",
],
Historical_Fiction : [
"FICTION/Historical/",
"JUVENILE FICTION/Historical/",
],
History : "HISTORY/",
Humorous_Fiction : [
"FICTION/Humorous",
"FICTION/Satire",
"Humorous Stories/",
],
Humorous_Nonfiction : [
"HUMOR/",
"Humor/",
],
Horror : [
"Horror/",
"Horror & Ghost Stories/",
"Occult/",
],
Life_Strategies : [
"JUVENILE NONFICTION/Social Issues"
],
Literary_Fiction : [
"FICTION/Literary",
"FICTION/Psychological",
"FICTION/Coming of Age",
"FICTION/Family Saga",
],
Law : "LAW/",
Mathematics : "MATHEMATICS/",
Medical : "MEDICAL/",
Music : "MUSIC/",
Mystery : [
"Mystery & Detective/",
"FICTION/Crime/",
"Mysteries & Detective Stories/"
],
Nature : "NATURE/",
Parenting_Family: "FAMILY & RELATIONSHIPS/",
Performing_Arts : "PERFORMING ARTS/",
Pets : [
"PETS/",
],
Philosophy : "PHILOSOPHY/",
Photography : "PHOTOGRAPHY/",
Poetry : [
"POETRY/",
"Poetry",
"Stories in Verse",
],
Political_Science: "POLITICAL SCIENCE/",
Psychology : "PSYCHOLOGY & PSYCHIATRY/",
Reference_Study_Aids: "REFERENCE/",
Religion_Spirituality : [
"RELIGION/",