-
Notifications
You must be signed in to change notification settings - Fork 9
/
walverine.js
1233 lines (1148 loc) · 46.7 KB
/
walverine.js
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
WalverineCitation = function(volume, reporter, page) {
/*
* Convenience class which represents a single citation found in a document.
*/
// Note: It will be tempting to resolve reporter variations in the __init__ function, but, alas, you cannot,
// because often reporter variations refer to one of several reporters (e.g. P.R. could be a variant of
// either ['Pen. & W.', 'P.R.R.', 'P.']).
this.volume = volume;
this.reporter = reporter;
this.page = page;
this.lookup_index = null;
this.canonical_reporter = null;
this.extra = null;
this.defendant = null;
this.plaintiff = null;
this.court = null;
this.year = null;
this.mlz_jurisdiction = null;
this.match_url = null;
this.end_idx = null;
this.cert_order = null;
this.disposition = null;
this.cite_type;
this.match;
}
WalverineCitation.keys = function(obj) {
if (Object.keys) return Object.keys(obj);
var keys = [];
for (var key in obj) if (obj.hasOwnProperty(key)) keys.push(key);
return keys;
};
WalverineCitation.each = function(obj, iterator, context) {
if (obj == null) return obj;
if (Array.prototype.forEach && obj.forEach === Array.prototype.forEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, length = obj.length; i < length; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
var keys = WalverineCitation.keys(obj);
for (var i = 0, length = keys.length; i < length; i++) {
if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
}
}
return obj;
};
WalverineCitation.map = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (Array.prototype.map && obj.map === Array.prototype.map) return obj.map(iterator, context);
WalverineCitation.each(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
};
WalverineCitation.prototype.base_citation = function () {
// The Commonwealth jurisdictions have cites like "Smith v. Jones [2007] HL 123".
var volume = this.volume ? this.volume + " " : ""
return volume + this.reporter + " " + this.page;
}
WalverineCitation.prototype.as_regex = function () {
// Should include the year, if no volume and year is a prefix
// Form would be something like: "[\[\(]<year>[\]\)]\s+<reporter>\s+<page>"
var volume = this.volume ? this.volume + "(\s+)" : ""
var ret = new RegExp(volume + this.reporter + "(\s+)" + this.page);
}
WalverineCitation.prototype.as_html = function () {
// As above, should include year if it serves as a volume number for this jurisdiction
var volume = this.volume ? '<span class="volume">' + this.volume + '</span>' : ""
var inner_html = volume
+ '<span class="reporter">' + this.reporter + '</span>'
+ '<span class="page">' + this.page + '</span>';
var span_class = "citation";
if (this.match_url) {
inner_html = '<a href="' + this.match_url + '">' + inner_html + '</a>';
} else {
span_class += " no-link";
}
return '<span class="' + span_class + '">' + inner_html + '</span>'
}
var Walverine = {
builders: {},
constants: {},
utils: {},
buffer: 0
};
Walverine.constants.FORWARD_SEEK = 20;
Walverine.constants.BACKWARD_SEEK = 120;
// this could be improved
var reporters = require('./reporters').reporters;
Walverine.constants.REPORTERS = reporters;
Walverine.constants.JURISDICTIONS = {
'us;ct':['Connecticut',"Conn."],
'us;de':['Delaware',"Del."],
'us;dc':['District of Columbia',"D.C.", "DC"],
'us;me':['Maine',"Me."],
'us;nh':['New Hampshire',"N.H."],
'us;nj':['New Jersey',"N.J."],
'us;pa':['Pennsylvania',"Penn."],
'us;ri':['Rhode Island',"R.I."],
'us;vt':['Vermont',"Vt."],
'us;il':['Illinois',"Ill."],
'us;in':['Indiana',"Ind."],
'us;ma':['Massachussetts',"Mass."],
'us;md':['Maryland',"Md."],
'us;ny':['New York',"N.Y."],
'us;oh':['Ohio'],
'us;ia':['Iowa'],
'us;mi':['Michigan',"Mich."],
'us;mn':['Minnisota',"Minn."],
'us;ne':['Nebraska',"Neb."],
'us;nd':['North Dakota'],
'us;sd':['South Dakota'],
'us;wi':['Wisconsin',"Wis.","Wisc."],
'us;ak':['Alaska',"Ala."],
'us;az':['Arizona',"Ariz."],
'us;ca':['California',"Cal."],
'us;co':['Colorado',"Co."],
'us;hi':["Hawai'i","Hawaii"],
'us;id':['Idaho'],
'us;ks':['Kansas',"Kan."],
'us;mt':['Montana',"Mon.","Mont."],
'us;nv':['Nevada',"Nev."],
'us;nm':['New Mexico',"N.M."],
'us;ok':['Oklahoma',"Ok."],
'us;or':['Oregon',"Or."],
'us;ut':['Utah'],
'us;wa':['Washington',"Wa.","Wash."],
'us;wy':['Wyoming',"Wy.","Wyo."],
'us;ga':['Georgia',"Ga."],
'us;nc':['North Carolina',"N.C."],
'us;sc':['South Carolina',"S.C."],
'us;va':['Virginia',"Va."],
'us;wv':['West Virginia',"West Va.","W. Va.", "W.Va."],
'us;ar':['Arkansas',"Ark."],
'us;ky':['Kentucky',"Ken."],
'us;mo':['Missouri',"Mo."],
'us;tn':['Tennessee',"Tenn."],
'us;tx':['Texas',"Tex."],
'us;al':['Alabama',"Ala."],
'us;fl':['Florida',"Fla."],
'us;la':['Louisiana',"La."],
'us;ms':['Mississippi',"Miss."],
'us;federal;1-cir':['First Circuit',"1st Cir.","1st Cir","1 Cir.","CA1"],
'us;federal;2-cir':['Second Circuit',"2nd Cir.","2d Cir","2 Cir.","CA2"],
'us;federal;3-cir':['Third Circuit',"3rd Cir.","3d Cir","3 Cir.","CA3"],
'us;federal;4-cir':['Fourth Circuit',"4th Cir.","4th Cir","4 Cir.","CA4"],
'us;federal;5-cir':['Fifth Circuit',"5th Cir.","5th Cir","5 Cir.","CA5"],
'us;federal;6-cir':['Sixth Circuit',"6th Cir.","6th Cir","6 Cir.","CA6"],
'us;federal;7-cir':['Seventh Circuit',"7th Cir.","7th Cir","7 Cir.","CA7"],
'us;federal;8-cir':['Eighth Circuit',"8th Cir.","8th Cir","8 Cir.","CA8"],
'us;federal;9-cir':['Ninth Circuit',"9th Cir.","9th Cir","9 Cir.","CA9"],
'us;federal;10-cir':['Tenth Circuit',"10th Cir.","10th Cir","10 Cir.","CA10"],
'us;federal;11-cir':['Eleventh Circuit',"11th Cir.","11th Cir","11 Cir.","CA11"]
};
Walverine.constants.ACCEPT_TOKENS = [
'In Re',
'In re',
'Ex parte',
'Ex Parte'
];
Walverine.constants.STRING_TOKENS = [
'certiorari denied',
'cert. denied',
'denied',
"aff'd",
"aff\u2019d",
'affirmed',
'remanded',
'certiorari granted',
'cert. granted',
'granted',
'dismissed',
'opinion',
'dismissed by',
'modified by',
'amended by',
'affirmed by',
"aff'd by",
'aff\u2019d by',
'vacated in',
'vacated by'
];
Walverine.constants.EMBEDDED_TOKENS = [
"of the",
"on the",
"ex rel",
"et al",
"et al.",
"[Nn]o.? +[0-9]+",
"to"
];
Walverine.constants.PREPOSITIONS = [
"citing",
"in",
"for",
"from",
"with",
"over",
"than",
"by",
"Act."
];
Walverine.builders.make_variant_key = function (key) {
key = key.replace(".", " ", "g");
key = key.replace(/\s+/g, " ");
key = " " + key + " ";
key = key.replace(/([^a-zA-Z])([A-Z])\s+([A-Z])([^A-Za-z])/g, "$1$2$3$4");
key = key.replace(/\s+([\]\)])/g, "$1");
key = key.replace(/^\s+/, "").replace(/\s+$/, "");
return key;
};
Walverine.builders.make_variants = function (REPORTERS) {
for (var canonical_key in REPORTERS) {
var canonical_segment = REPORTERS[canonical_key];
for (var i=0,ilen=canonical_segment.length;i<ilen;i+=1) {
var class_entry = canonical_segment[i];
var newvars = {};
for (var key in class_entry.editions) {
var nvk = this.make_variant_key(key);
if (!class_entry.editions[nvk]
&& !class_entry.variations[nvk]
&& !newvars[nvk]) {
newvars[nvk] = key;
}
}
for (var key in class_entry.variations) {
var nvk = this.make_variant_key(key);
if (!class_entry.editions[nvk]
&& !class_entry.variations[nvk]
&& !newvars[nvk]) {
newvars[nvk] = class_entry.variations[key];
}
}
for (var nvk in newvars) {
class_entry.variations[nvk] = newvars[nvk];
}
}
}
};
Walverine.builders.make_variants(Walverine.constants.REPORTERS);
Walverine.builders.suck_out_variations_only = function (REPORTERS) {
/*
* Builds a dictionary of variations to canonical reporters.
*
* The dictionary takes the form of:
* {
* 'A. 2d': ['A.2d'],
* ...
* 'P.R.': ['Pen. & W.', 'P.R.R.', 'P.'],
* }
*
* In other words, it's a dictionary that maps each variation to a list of
* reporters that it could be possibly referring to.
*/
var variations_out = {};
for (var reporter_key in REPORTERS) {
// For each reporter key ...
var data_list = REPORTERS[reporter_key];
for (var i=0,ilen=data_list.length;i<ilen;i+=1) {
data = data_list[i];
// For each book it maps to...
for (var variation_key in data.variations) {
var variation_value = data.variations[variation_key];
if ("undefined" !== typeof variations_out[variation_key]) {
var variations_list = variations_out[variation_key];
if (variations_list.indexOf(variation_value) === -1) {
variations_list.push(variation_value);
}
} else {
// The item wasn't there; add it.
variations_out[variation_key] = [variation_value];
}
}
}
}
return variations_out;
}
Walverine.constants.VARIATIONS_ONLY = Walverine.builders.suck_out_variations_only(Walverine.constants.REPORTERS);
Walverine.builders.suck_out_courts = function(JURISDICTIONS) {
var COURTS = {};
for (var key in JURISDICTIONS) {
for (var i=0,ilen=JURISDICTIONS[key].length;i<ilen;i+=1) {
var court = JURISDICTIONS[key][i];
COURTS[court] = true;
}
}
return COURTS;
}
Walverine.constants.COURTS = Walverine.builders.suck_out_courts(Walverine.constants.JURISDICTIONS);
Walverine.builders.suck_out_neutrals = function (REPORTERS) {
/*
* Builds a small dictionary of neutral reporter keys
*
* The dictionary takes the form of:
* {
* 'AZ': true,
* ...
* 'OK': true
* }
*
*/
var neutrals = {};
for (var reporter_key in REPORTERS) {
// For each reporter key ...
var data_list = REPORTERS[reporter_key];
for (var i=0,ilen=data_list.length;i<ilen;i+=1) {
data = data_list[i];
// For each book it maps to...
if (data.cite_type === "neutral") {
// So far, at least, neutrals and their variations are unambiguous.
for (var key in data.editions) {
neutrals[key] = true;
}
for (var key in data.variations) {
neutrals[key] = true;
}
}
}
}
return neutrals;
}
Walverine.constants.NEUTRALS = Walverine.builders.suck_out_neutrals(Walverine.constants.REPORTERS);
Walverine.builders.suck_out_editions = function(REPORTERS) {
/*
* Builds a dictionary mapping edition keys to their root name.
*
* The dictionary takes the form of:
* {
* 'A.': 'A.',
* 'A.2d': 'A.',
* 'A.3d': 'A.',
* 'A.D.': 'A.D.',
* ...
* }
* In other words, this lets you go from an edition match to its parent key.
*/
var editions_out = {};
for (var reporter_key in REPORTERS) {
// For each reporter key ...
var data_list = REPORTERS[reporter_key];
for (var i=0,ilen=data_list.length;i<ilen;i+=1) {
var data = data_list[i];
for (var edition_key in data.editions) {
// For each book it maps to...
var edition_value = data.editions[edition_value];
if ("undefined" === typeof editions_out[edition_key]) {
editions_out[edition_key] = reporter_key;
}
}
}
}
return editions_out;
}
Walverine.constants.EDITIONS = Walverine.builders.suck_out_editions(Walverine.constants.REPORTERS);
// We need to build a REGEX that has all the variations and the reporters in_ order from longest to shortest.
Walverine.builders.make_regex = function (constants) {
var EDITIONS = constants.EDITIONS;
var VARIATIONS_ONLY = constants.VARIATIONS_ONLY;
var ACCEPT_TOKENS = constants.ACCEPT_TOKENS;
var EMBEDDED_TOKENS = constants.EMBEDDED_TOKENS;
var STRING_TOKENS = constants.STRING_TOKENS;
//var REGEX_LIST = [key for (key in EDITIONS)].concat([key for (key in VARIATIONS_ONLY)]);
var REGEX_LIST = WalverineCitation.keys(EDITIONS).concat(WalverineCitation.keys(VARIATIONS_ONLY));
/*
REGEX_LIST = REGEX_LIST
.concat([ACCEPT_TOKENS[i] for (i in ACCEPT_TOKENS)])
.concat([EMBEDDED_TOKENS[i] for (i in EMBEDDED_TOKENS)])
.concat([STRING_TOKENS[i] for (i in STRING_TOKENS)]);
*/
REGEX_LIST = REGEX_LIST.concat(ACCEPT_TOKENS);
REGEX_LIST = REGEX_LIST.concat(EMBEDDED_TOKENS);
REGEX_LIST = REGEX_LIST.concat(STRING_TOKENS);
for (var i=0,ilen=REGEX_LIST.length;i<ilen;i+=1) {
if (REGEX_LIST[i].slice(-1) !== "." && REGEX_LIST[i].slice(-1) !== " ") {
// Prevent mid-word matches
REGEX_LIST[i] = " " + REGEX_LIST[i] + " ";
}
}
REGEX_LIST.sort(
function (a,b) {
if (a.length < b.length) {
return 1;
} else if (a.length > b.length) {
return -1;
} else {
return 0;
}
}
);
/*
var REGEX_STR = [REGEX_LIST[i].replace(".","\\.","g").replace("(","\\(","g").replace(")","\\)","g").replace("\'", "\\'","g") for (i in REGEX_LIST)].join("|");
var REGEX_STR = [REGEX_LIST[i]
.replace(".","\\.","g")
.replace("(","\\(","g")
.replace(")","\\)","g")
.replace("\'", "\\'","g") for (i in REGEX_LIST)].join("|");
*/
var REGEX_STR = WalverineCitation.map(REGEX_LIST, function(i) {
return i.replace(".","\\.","g").replace("(","\\(","g").replace(")","\\)","g").replace("\'", "\\'","g");
}).join("|");
constants.REPORTER_RE = new RegExp("(" + REGEX_STR + ")");
}
Walverine.builders.make_regex(Walverine.constants);
Walverine.utils.strip_punct = function (text) {
//starting quotes
text = text.replace(/^\"/g, "");
text = text.replace(/(``)/g, "");
text = text.replace(/([ (\[{<])"/g, '')
//punctuation
text = text.replace(/\.\.\./g, '')
text = text.replace(/[,;:@#$%&]/g, '')
text = text.replace(/([^\.])(\.)([\]\)}>"\']*)\s*$/g, '$1')
text = text.replace(/[?!]/g, '')
// XXX What did I add this for? As written, it's only effect will be to break things.
text = text.replace(/([^'])' /g, "")
//parens, brackets, etc.
text = text.replace(/[\]\[\(\)\{\}\<\>]/g, '')
text = text.replace(/--/g, '')
//ending quotes
text = text.replace(/\"/g, "")
text = text.replace(/(\S)(\'\')/g, '')
return text.replace(/^\s+/, "").replace(/\s+$/, "");
};
Walverine.utils.get_visible_text = function (text) {
var text = text.replace(/<(?:style|STYLE)[^>]*>.*?<\/(?:style|STYLE)>/g, " ");
text = text.replace(/<[Aa] [^>]+>[^ ]+<\/[Aa]>/g, " ");
text = text.replace(/<[^>]*>/g, "");
text = text.replace("\n"," ","g");
text = text.replace(" "," ","g");
return text;
};
Walverine.utils.set_jurisdiction = function (citation, jurisdiction) {
if (!citation.mlz_jurisdiction) {
citation.mlz_jurisdiction = jurisdiction;
}
};
Walverine.utils.is_date_in_reporter = function (editions, year) {
/*
* Checks whether a year falls within the range of 1 to n editions of a reporter
*
* Editions will look something like:
* 'editions': {'S.E.': (datetime.date(1887, 1, 1),
* datetime.date(1939, 12, 31)),
* 'S.E.2d': (datetime.date(1939, 1, 1),
* datetime.date.today())},
*/
for (var key in editions) {
var start = editions[key][0];
var end = editions[key][1];
var now = new Date();
var start_year = start.year ? start.year : now.getFullYear();
var end_year = end.year ? end.year : now.getFullYear();
if (start_year <= year && year <= end_year) {
return true;
}
}
return false;
};
Walverine.get_court = function (paren_string, year) {
var court;
if (!year) {
court = paren_string.replace(/(?:,\s*)*,\s*$/,"").replace(/^\s*\(/,"").replace(/\)\s*$/,"");
} else {
var year_index = paren_string.indexOf(("" + year));
court = paren_string.slice(0,year_index);
court = court.replace(/^\s*\(\s*/, "").replace(/,\s*,\s*$/,"");
}
if (court === "") {
court = null;
}
return court;
};
Walverine.get_year = function (token) {
/*
* Given a string token, look for a valid 4-digit number at the start and
* return its value.
*/
var strip_punct = this.utils.strip_punct;
var year;
var token = strip_punct(token);
var m = token.match(/.*?([0-9]{4})/);
if (m) {
year = parseInt(m[1], 10);
if (year < 1754) {
year = null;
}
}
return year;
};
Walverine.get_pre_citation = function (citation, citations, words, reporter_index) {
// There are Federal Circuit decisions that have a form
// like this:
//
// "Smith v. Jones, 2nd Cir., 1955, 123 F.2d 456".
//
var preoffset = 0;
var pos = reporter_index - 2;
var prev_idx = citations.length ? citations[citations.length - 1].end_idx : 0;
if (pos < 3 || pos == prev_idx) {
return preoffset;
}
var m = words[pos].match(/^[(]*([0-9]{4})[,)]+$/);
if (m) {
preoffset = 1;
citation.year = m[1];
if (words[pos].slice(-1) !== ")" && words[pos - 1].slice(-1) !== ",") {
return preoffset;
}
// Try for a court
var newoffset = 0;
var maybecourt = [];
for (var i=pos-1,ilen=pos-4;i>ilen;i+=-1) {
if (i == prev_idx) break;
maybecourt.reverse();
maybecourt.push(words[i]);
maybecourt.reverse();
if (this.match_jurisdiction(citation, maybecourt.join(" "))) {
newoffset = pos-i;
break;
}
}
if (newoffset) {
preoffset = newoffset+1;
}
return preoffset;
}
return preoffset;
};
Walverine.carry_forward = function (citations, pos) {
citations[pos].plaintiff = citations[pos - 1].plaintiff;
citations[pos].defendant = citations[pos - 1].defendant;
this.apply_jurisdiction(citations[pos], citations[pos - 1].mlz_jurisdiction);
this.apply_year(citations[pos], citations[pos - 1].year);
};
Walverine.apply_jurisdiction = function (citation, jurisdiction) {
if (!citation.mlz_jurisdiction) {
citation.mlz_jurisdiction = jurisdiction;
}
};
Walverine.apply_year = function (citation, year) {
if (!citation.year) {
citation.year = year;
}
};
Walverine.match_jurisdiction = function (citation, data_string) {
// A wild guess is the best we can do -- any match clears
var COURTS = this.constants.COURTS;
for (var key in COURTS) {
if (data_string.indexOf(key) > -1) {
citation.court = key;
return true;
}
}
return false;
};
Walverine.tokenize = function (text) {
/*
* Tokenize text using regular expressions in the following steps:
* -Split the text by the occurrences of patterns which match a federal
* reporter, including the reporter strings as part of the resulting list.
* -Perform simple tokenization (whitespace split) on each of the non-reporter
* strings in the list.
*
* Example:
* >>>tokenize('See Roe v. Wade, 410 U. S. 113 (1973)')
* ['See', 'Roe', 'v.', 'Wade,', '410', 'U.S.', '113', '(1973)']
*/
var REPORTER_RE = this.constants.REPORTER_RE;
var strings = text.split(REPORTER_RE);
var words = [];
for (var i=0,ilen=strings.length;i<ilen;i+=1) {
var string = strings[i];
if ((i+1)%2 === 0) {
string = string.replace(/^\s+/, "").replace(/\s+$/, "");
words.push(string);
} else {
// Normalize spaces
words = words.concat(this._tokenize(string));
}
}
return words;
};
Walverine._tokenize = function (text) {
//add extra space to make things easier
text = " " + text + " ";
//get rid of all the annoying underscores in text from pdfs
text = text.replace(/__+/g,"");
// No lone commas
text = text.replace(/\s+,\s+/g," ");
// No star numbers (Google Scholar link text for these is immediately adjacent)
text = text.replace(/([0-9]+)*\*[0-9]+/g," ");
//reduce excess whitespace
text = text.replace(/ +/g, " ");
text = text.replace(/^\s+/, "").replace(/\s+$/, "");
return text.split(" ");
};
Walverine.extract_base_citation = function (words, reporter_index) {
/*
* """Construct and return a citation object from a list of "words"
*
* Given a list of words and the index of a federal reporter, look before and after
* for volume and page number. If found, construct and return a WalverineCitation object.
*/
var NEUTRALS = this.constants.NEUTRALS;
var reporter = words[reporter_index];
var m = words[reporter_index - 1].match(/^\s*([0-9]+)\s*$/);
if (m) {
volume = parseInt(m[1], 10);
} else {
volume = null;
}
var page_str = words[reporter_index + 1];
// Strip off ending comma, which occurs when there is a page range next
// ... and a period, which can occur in neutral and year-first citations.
page_str = page_str.replace(/[;,.]$/, "");
if (page_str.match(/^[0-9]+$/)) {
page = parseInt(page_str, 10);
} else {
// No page, therefore no valid citation
return null;
}
var citation = new WalverineCitation(volume, reporter, page);
if (NEUTRALS[reporter]) {
citation.cite_type = "neutral";
if (volume && (""+volume).match(/[0-9]{4}/)) {
citation.year = volume;
}
}
citation.end_idx = reporter_index + 1;
return citation;
}
Walverine.add_post_citation = function (citation, words, reporter_index) {
var FORWARD_SEEK = this.constants.FORWARD_SEEK;
var find_pinpoints = true;
// Start looking 2 tokens after the reporter (1 after page)
for (var i=(reporter_index+2),ilen=Math.min((reporter_index+FORWARD_SEEK), words.length);i<ilen;i+=1) {
// Check each token going forward as either (a) a parenthetical or (b) a potential pinpoint.
// When the test for (b) fails, peg the ending index of the current cite at two less than the
// failing index (i.e. one before the possible volume number of the following cite).
var start = i;
if (words[start].slice(0,1) === "(" || words[start].slice(0,1) === "[") {
for (var k=start,klen=start+FORWARD_SEEK;k<klen;k+=1) {
var end = k;
var has_ending_paren;
has_ending_paren = (words[end].indexOf(")") > -1 || words[end].indexOf(")") > -1);
if (has_ending_paren) {
// Sometimes the paren gets split from the preceding content
if (words[end].slice(0,1) === ")" || words[end].slice(0,1) === "]") {
citation.year = this.get_year(words[end - 1]);
} else {
citation.year = this.get_year(words[end]);
}
citation.court = this.get_court(words.slice(start, (end+1)).join(" "), citation.year)
break;
}
}
if (start > (reporter_index + 2)) {
// Then there's content between page and (), starting with a comma, which we skip
citation.extra = words.slice(reporter_index+2,start).join(" ");
}
break;
} else {
if (find_pinpoints) {
if (words[i].match(/^(?:n\.|n|nn\.|nn|para|para\.|¶|[-0-9]+)[,;]?\s*$/)) {
citation.end_idx = (i-1);
} else {
find_pinpoints = false;
}
}
}
}
}
Walverine.add_defendant = function (citations, words, reporter_index) {
/*
* Scan backwards from 2 tokens before reporter until you find v., in re, etc.
* If no known stop-token is found, no defendant name is stored. In the future,
* this could be improved.
*/
var pos = citations.length - 1;
var end = (reporter_index - 1);
var idx = (reporter_index - 2);
var prev_idx = citations[pos - 1] ? citations[pos - 1].end_idx : 0;
var _add_defendant = Walverine.addDefendant(citations, words, pos, idx, end, prev_idx);
this.buffer = _add_defendant.backscan();
_add_defendant.finish(citations[pos]);
}
Walverine.addDefendant = function (citations, words, pos, idx, end, prev_idx) {
// Try a sort-of state machine
var STRING_TOKENS = this.constants.STRING_TOKENS;
var ACCEPT_TOKENS = this.constants.ACCEPT_TOKENS;
var EMBEDDED_TOKENS = this.constants.EMBEDDED_TOKENS;
var PREPOSITIONS = this.constants.PREPOSITIONS;
var BACKWARD_SEEK = this.constants.BACKWARD_SEEK;
var strip_punct = this.utils.strip_punct;
var buffer = this.buffer;
return {
idx: idx,
end: end,
buffer: buffer,
backscan: function () {
// Some conditions
if (this.idx < 1) {
return;
}
// Not sure why, but the tokenizer can produce empty elements.
var word = words[this.idx];
if (!word) {
this.idx += -1;
this.backscan();
}
word = word.replace(/^[\(\[]*/g, "");
var capWord = this.isCap(word);
var preword = words[this.idx - 1].replace(/^[\(\[]*/g, "");
var capPreWord = this.isCap(preword);
if (this.idx+1 == this.end && this.is_parallel()) {
// If the name consists entirely of pinpoint-like things, it's a parallel.
citations[pos].CARRY_FORWARD = true;
} else if (citations.length > 1 && this.idx == (this.end-1) && this.idx <= (citations[pos - 1].end_idx)) {
// If there is nothing between it and the previous cite, it's a parallel also
this.idx = this.end;
citations[pos].CARRY_FORWARD = true;
} else if (preword.slice(-2) === '".' || preword.slice(-2) === '."') {
this.cleanup(true);
} else if (STRING_TOKENS.indexOf(strip_punct(word)) > -1 && pos > 0) {
// If it stops at a member of STRING_TOKENS, it pertains to the immediately preceding case
this.idx = this.end;
citations[pos].CARRY_FORWARD = true;
var m = word.match(/cert.*(granted|denied)/);
if (m) {
citations[pos].CERT = m[1];
if (citations[pos].year) {
for (var i=(citations.length-1+this.buffer),ilen=(citations.length-1);i<ilen;i+=1) {
citations[i].year = citations[pos].year;
}
this.buffer = 0;
}
}
} else if (word.slice(-1) === "." && !capWord && word !== "v.") {
// It never includes a non-capitalized word that ends in a period
this.cleanup();
} else if (word.indexOf(":") > -1 || word.indexOf(";") > -1) {
// Colons and semicolons are fatal to the search and should never be included
this.cleanup();
} else if ((this.end - this.idx) > 3 && word.indexOf(")") > -1) {
this.idx += 1;
// It does not run past a close parens after gathering three words
this.cleanup();
} else if (word === "of" || word === "and" || word === "to" || word.match(/^see[,.]?$/i)) {
if (!capPreWord) {
// The preposition "of" or conjunction "and" precede a case name only if it is not themselves preceded by a capitalized word.
this.cleanup();
} else {
this.idx += -1;
this.backscan();
}
} else if (ACCEPT_TOKENS.indexOf(strip_punct(word)) > -1) {
// It never extends beyond "In re"
// It never extends beyond "Ex parte"
this.cleanup();
} else if (PREPOSITIONS.indexOf(strip_punct(preword)) > -1 && capWord) {
// If over an arbitrary length (?), it never extends beyond certain prepositions if they precede a capitalized word
this.cleanup(true);
} else if (!capWord && word !== "v." && word !== "v" && word !== "&" && word !== "&" && EMBEDDED_TOKENS.indexOf(word) === -1) {
// It never includes a non-capitalized word that is not "v." or "&"
this.cleanup();
} else if ((this.end - this.idx) > BACKWARD_SEEK) {
// It never extends beyond an arbitrary length limit
this.cleanup(true);
} else {
this.idx += -1;
this.backscan();
}
return this.buffer;
},
is_parallel: function() {
// "of" is handled by a special condition
var idx = this.idx;
for (var i=this.idx,ilen=Math.max(this.idx-BACKWARD_SEEK, prev_idx+1, -1);i>ilen;i+=-1) {
if (words[i].match(/^(?:n\.|n|para|para\.|¶|[-0-9]+)[,;]?\s*$/)) {
idx = i;
} else {
return false;
}
}
this.end = idx+1;
return true;
},
isCap: function (word) {
return word.slice(0,1) !== word.slice(0,1).toLowerCase();
},
cleanup: function (keepCurrentWord) {
// It always begins with a capitalized word
if (keepCurrentWord) {
this.idx += -1;
}
for (var i=this.idx,ilen=this.end;i<ilen;i+=1) {
var word = words[i].replace(/[\[\(\]\)]*/g, "");
if (this.isCap(word)) {
this.idx = i;
break;
}
}
},
cleanstr: function (str) {
str = str.replace("&", "&", "g");
str = str.replace(/,$/,"");
str = str.replace(/[\[\(\)\]]*/g, "");
return str;
},
finish: function (citation) {
if (this.idx < this.end) {
// It doesn't necessarily exist
var parties = words.slice(this.idx,(this.end)).join(" ");
parties = parties.split(/\s+v\.?\s+/);
if (parties.length > 1) {
// I had some plain text conversion wrappers here, but they're no longer needed
citation.plaintiff = strip_punct(parties[0]) ? this.cleanstr(parties[0]) : "";
citation.defendant = strip_punct(parties[1]) ? this.cleanstr(parties[1]) : "";
} else {
citation.plaintiff = strip_punct(parties[0]) ? this.cleanstr(parties[0]) : "";
}
}
if (citation.plaintiff) {
var m = citation.plaintiff.match(/^(?:See|Cf.)\s+(.*)/);
if (m) {
citation.plaintiff = this.cleanstr(m[1]);
} else if (!citation.plaintiff.match(/^in re/i)) {
citation.plaintiff = citation.plaintiff.replace(/^In\s+/, "");
}
}
citation.match = words.slice(this.idx,this.end_idx).join(" ");
}
}
}
Walverine.infer_jurisdiction = function (citations) {
var REPORTERS = this.constants.REPORTERS;
var JURISDICTIONS = this.constants.JURISDICTIONS;
for (var i=0,ilen=citations.length;i<ilen;i+=1) {
var citation = citations[i];
// Move stray citation data from defendant to extra
if (citation.defendant) {
var extras = [];
while (true) {
var m = citation.defendant.match(/^(.*,)\s([0-9]+\s[A-Z][A-Za-z. 0-9]+\s[0-9]+),\s*$/);
if (m) {
citation.defendant = m[1];
extras.push(m[2]);
} else {
break;
}
}
if (extras.length) {
if (citation.extra) {
extras.push(citation.extra);
}
citation.extra = extras.join(", ");
citation.defendant.replace(/,\s*$/, "");
}
}
var reporters = REPORTERS[citation.canonical_reporter];
var jurisdictions = [];
for (var j=0,jlen=reporters.length;j<jlen;j+=1) {
var reporter = reporters[j];
jurisdictions = jurisdictions.concat(reporter.mlz_jurisdiction);
}
if (jurisdictions.length === 1) {
// If there is only one choice, we're already home
citation.mlz_jurisdiction = jurisdictions[0];
} else if (citation.court || citation.extra) {
// Look for a match of an abbrev of the jurisdiction name in the court field
var done = false;
var data_string = (citation.court ? citation.court : "") + " " + (citation.extra ? citation.extra : "");
for (var j=0,jlen=jurisdictions.length;j<jlen;j+=1) {
var possible_jurisdiction = jurisdictions[j];
for (var k=0,klen=JURISDICTIONS[possible_jurisdiction].length;k<klen;k+=1) {
var match_string = JURISDICTIONS[possible_jurisdiction][k];
if (data_string.indexOf(match_string) > -1) {
citation.mlz_jurisdiction = possible_jurisdiction;
var done = true;
break;
}
}
if (done) break;
}
}
// If we didn't find anything, the jurisdiction field will be empty.
// It's something from the US, but we don't set that until after handling the carry-forwards
//apply_jurisdiction(citation, "us");
}
}
Walverine.disambiguate_reporters = function (citations) {
/*
* A second, from scratch, approach to converting a list of citations to a list of unambiguous ones.
*
* Goal is to figure out:
* - citation.canonical_reporter
* - citation.lookup_index
*
* And there are a few things that can be ambiguous:
* - More than one variation.
* - More than one reporter for the key.
* - Could be an edition (or not)
* - All combinations of the above:
* - More than one variation.
* - More than one variation, with more than one reporter for the key.
* - More than one variation, with more than one reporter for the key, which is an edition.
* - More than one variation, which is an edition
* - ...
* For variants, we just need to sort out the canonical_reporter
*/
var REPORTERS = this.constants.REPORTERS;
var EDITIONS = this.constants.EDITIONS;
var VARIATIONS_ONLY = this.constants.VARIATIONS_ONLY;
var is_date_in_reporter = this.utils.is_date_in_reporter;
var unambiguous_citations = [];
for (var h=0,hlen=citations.length;h<hlen;h+=1) {
var citation = citations[h];
// Non-variant items (P.R.R., A.2d, Wash., etc.)
if (REPORTERS[EDITIONS[citation.reporter]]) {
if (REPORTERS[EDITIONS[citation.reporter]].length === 1) {
// Single reporter, easy-peasy.
citation.canonical_reporter = EDITIONS[citation.reporter];