-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuwatto.rb
1693 lines (1654 loc) · 67.6 KB
/
fuwatto.rb
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
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
# $Id$
$:.unshift "."
require "net/http"
require "net/https"
#require "pp"
require "digest/md5"
require "tempfile"
require "erb"
require "cgi"
require "nkf"
require "kconv"
require "rubygems"
require "json"
require "libxml"
begin
require "MeCab"
rescue LoadError
begin
require "mecab"
rescue
require "mecab_local.rb"
end
end
begin
require "extractcontent"
rescue LoadError
# require "extractcontent_local.rb"
end
Encoding.default_external = Encoding::UTF_8
module Math
def self::log2( n )
Math.log10( n ) / Math.log10( 2 )
end
end
class String
def shorten( len = 120 )
matched = self.gsub( /\n/, ' ' ).scan( /^.{0,#{len - 2}}/u )[0]
if $'.nil? || $'.empty?
matched
else
matched + '..'
end
end
end
class Array
def uniq_by
result = []
hash = {}
self.each do |e|
next if hash[ yield e ]
hash[ yield e ] = true
result << e
end
result
end
end
class Hash
def make_uri_params
if self.empty?
""
else
self.keys.map do |e|
"#{ e }=#{ URI.encode_www_form_component( self[e].to_s ) }"
end.join( "&" )
end
end
end
module Fuwatto
VERSION = '3.2.0'
BASE_URI = 'https://fuwat.to/'
USER_AGENT = "Fuwatto Search/#{ VERSION }; #{ BASE_URI }"
CACHE_TIME = 60 * 60 * 24 * 5 # 3日経つまで、キャッシュは有効
MAX_PAGE = 19 # ページネイションに表示されるアイテム数
PRF_TOP_K = 10
PRF_ALPHA = 0.5 # 元クエリベクトルに対する相対的な重み
# (元ベクトルの重み最大値に対する比を指定する)
# Bag of Words による文書表現
class Document < Array
include Fuwatto
attr_reader :content
# opts - 特徴語スコアの計算手法切り替え
#
# :term_weight
# - :default (:logcost) => MeCab単語コストの対数値
# - :cost => MeCab単語コスト
# - :tf => TF(出現回数)
def initialize( content, mode = :mecab, opts = {} )
super()
return if content.nil?
@content = NKF.nkf( "-wm0XZ1", content ).gsub( /\s+/, " " ).strip
normalized_content = @content.downcase
opts[ :term_weight ] = :default if not opts[ :term_weight ]
clear
case mode
when "yahoo"
self.push( *extract_keywords_yahooapi( normalized_content ) )
else
self.push( *extract_keywords_mecab( normalized_content, opts ) )
end
#puts self
end
# 類似度計算
def sim( vector )
sum = 0.0
vector.each do |k, v|
term = self.assoc( k )
sum += v * term[1] if term
end
sum / vector.size
end
end
YAHOO_KEYWORD_BASEURI = "http://jlp.yahooapis.jp/KeyphraseService/V1/extract"
YAHOO_APPID = "W11oHSWxg65mAdRwjBT4ylIdfS9PkHPjVvtJzx9Quwy.um8e1LPf_b.4usSBcmI-"
def extract_keywords_yahooapi( str )
#cont = open( "?appid=#{ YAHOO_APPID }&sentence=#{ URI.encode_www_form_component( str ) }&output=xml" ){|io| io.read }
uri = URI.parse( YAHOO_KEYWORD_BASEURI )
#response = http_get( uri )
http = Net::HTTP.new( uri.host, uri.port )
xml = nil
http.start do |conn|
data = "appid=#{ YAHOO_APPID }&sentence=#{ URI.encode_www_form_component( str ) }&output=xml"
# p data
res, = conn.post( uri.path, data )
xml = res.body
end
#p xml
parser = LibXML::XML::Parser.string( xml )
doc = parser.parse
keywords = doc.find( "//y:Keyphrase", "y:urn:yahoo:jp:jlp:KeyphraseService" ).map{|e| e.content }
#keywords.each do |e|
# p e.content
#end
keywords.select{|e| not e.nil? and not e.empty? }
end
def extract_keywords_mecab( str, opts )
return [] if str.strip.empty?
mecab = MeCab::Tagger.new( '--node-format=%m\t%H\t%c\n --unk-format=%m\tUNK\t%c\n' )
lines = mecab.parse( str )
#puts lines
lines = lines.split( /\n/ ).map{|l| l.split(/\t/) }
lines = lines.select{|l| l[2] and l[1] =~ /^名詞|UNK|形容詞/o and l[1] !~ /接[頭尾]|非自立|代名詞/o }
#p lines
if lines.empty?
raise Fuwatto::NoKeywordExtractedError
end
min = lines.map{|e| e[2].to_i }.min
lines = lines.map{|e| [ e[0], e[1], e[2].to_i + min.abs + 1 ] } if min < 0
count = Hash.new( 0 )
score = 0
lines.each_with_index do |line, idx|
# Ignore ASCII and other symbol chars
next if line[0] =~ /\A[\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f、。「『』」・〇〜ー□‰±♪゜]+\Z/o
# Ignore one or two digit numbers
next if line[0] =~ /\A[0-9][0-9]?\Z/o
# Stop words, derived from Lucene
next if line[0] =~ /\A(?:w(?:h(?:e(?:re(?:a(?:[st]|fter)|u(?:nto|pon)|in(?:to)?|o[fn]?|from|with|ver|by)?|n(?:(?:so)?ever|ce)?|ther)|o(?:m(?:(?:so)?ever)?|s(?:oever|e)|ever|le)?|i(?:ch(?:(?:so)?ever)?|l(?:st|e)|ther)|at(?:(?:so)?ever)?|y)|i(?:th(?:out|in)?|ll)|e(?:ll|re)?|ould|as)|a(?:l(?:(?:bei|mos)t|on[eg]|though|ready|ways|so|l)|n(?:y(?:(?:wher|on)e|thing|how)?|other|d)?|fter(?:wards)?|bo(?:ut|ve)|gain(?:st)?|mong(?:st)?|r(?:ound|e)|(?:cros)?s|dj|t)?|t(?:h(?:e(?:re(?:(?:upo|i)n|afte|for|by)?|m(?:selves)?|n(?:ce)?|ir|se|y)?|r(?:ough(?:out)?|u)|o(?:ugh|se)|[iu]s|a[nt])|o(?:gether|wards?|o)?)?|s(?:o(?:me(?:t(?:imes?|hing)|(?:wher|on)e|how)?)?|e(?:em(?:ing|ed|s)?|veral)|(?:inc|am)e|h(?:ould|e)|till|uch)?|b(?:e(?:c(?:om(?:es?|ing)|a(?:us|m)e)|fore(?:hand)?|(?:hi|yo)nd|(?:twe)?en|sides?|ing|low)?|oth|ut|y)|h(?:e(?:r(?:e(?:(?:upo|i)n|by)?|s(?:elf)?)?|eafter|nce)?|i(?:m(?:self)?|s)|a(?:[ds]|ve)|ow(?:ever)?)|o(?:u(?:r(?:(?:selve)?s)?|t)|n(?:ce one|ly|to)?|ther(?:wise|s)?|f(?:ten|f)?|(?:ve)?r|wn)|e(?:ve(?:r(?:y(?:(?:wher|on)e|thing)?)?|n)|ls(?:ewher)?e|(?:noug|ac)h|ither|xcept|tc|g)|n(?:o(?:[rw]|t(?:hing)?|body|o?ne)?|e(?:ver(?:theless)?|ither|xt)|amely|where)|m(?:o(?:re(?:over)?|st(?:ly)?)|(?:eanwhil)?e|u(?:ch|st)|y(?:self)?|an?y|ight)|i(?:[efs]|n(?:deed|to|c)?|t(?:s(?:elf)?)?)?|f(?:or(?:mer(?:ly)?)?|urther|irst|rom|ew)|l(?:a(?:tter(?:ly)?|st)|e(?:ast|ss)|td)|y(?:ou(?:r(?:s(?:el(?:ves|f))?)?)?|et)|x(?:author|other |note|subj|cal)|u(?:n(?:der|til)|p(?:on)?|s)|c(?:an(?:not)?|o(?:uld)?)|d(?:uring|own)|per(?:haps)?|v(?:ery|ia)|rather)\Z/o
#next if line[0].size < 3
#p line[2]
#puts line.join("\t")
case opts[ :term_weight ]
when :tf
score = 1
when :count, :cost
score = line[2].to_i
else # :logcost, :default
score = Math.log2( line[2].to_i + 1 )
end
#p [ line[0], score, idx ]
score /= Math.log2( idx + 2 ) if opts[ :term_weight_position ]
count[ line[0] ] += score
#count[ line[0] ] += 1
end
#p count
ranks = count.keys.sort_by{|e| count[e] }.reverse.map{|e| [e,count[e]] }
#pp ranks
#3.times do |i|
# puts [ i+1, ranks[i], count[ ranks[i] ] ].join( "\t" )
#end
ranks
end
# Supports redirect
def http_get( uri, limit = 10 )
#STDERR.puts uri.to_s
raise "Too many redirects: #{ uri }" if limit < 0
http_proxy = ENV[ "http_proxy" ]
proxy, proxy_port = nil
if http_proxy
proxy_uri = URI.parse( http_proxy )
proxy = proxy_uri.host
proxy_port = proxy_uri.port
end
http = Net::HTTP.Proxy( proxy, proxy_port ).new( uri.host, uri.port )
http.use_ssl = true if uri.scheme == "https"
http.start do |http|
response, = http.get( uri.request_uri, { 'User-Agent'=>USER_AGENT } )
#if response.code !~ /^2/
# response.each do |k,v|
# p [ k, v ]
# end
#end
case response
when Net::HTTPSuccess
response
when Net::HTTPRedirection
redirect_uri = URI.parse( response['Location'] )
STDERR.puts "redirect to #{ redirect_uri } (#{limit})"
http_get( uri + redirect_uri, limit - 1 )
else
response.error!
end
end
end
CACHE_DIR = "cache"
class Cache
CACHE_DIR = "cache"
def initialize( prefix )
@prefix = prefix
@cache_dir = File.join( CACHE_DIR, @prefix )
begin
unless File.exist? @cache_dir
Dir.mkdir @cache_dir
end
end
end
def filename( name, page = 0 )
xml_fname = name.dup
if xml_fname.size > 245
xml_fname = Digest::MD5.hexdigest( xml_fname )
end
xml_fname << ":#{ page }" if not page.nil? and not page == 0
xml_fname << ".xml"
File.join( @cache_dir, xml_fname )
end
def fetch( name, page = 0 )
fname = filename( name, page )
if File.exist?( fname ) and ( Time.now - File.mtime( fname ) ) < CACHE_TIME
cont = open( fname ){|io| io.read }
else
cont = yield
open( fname, "w" ){|io| io.print cont }
end
cont
end
end
def cache_xml( prefix, name, page = 0 )
xml_fname = name.dup
if xml_fname.size > 245
xml_fname = Digest::MD5.hexdigest( xml_fname )
end
xml_fname << ":#{ page }" if not page.nil? and not page == 0
xml_fname << ".xml"
File.join( CACHE_DIR, prefix, xml_fname )
end
PDFTOTEXT = "/usr/bin/pdftotext"
def pdftotext( pdf_str )
pdf_file = Tempfile.new( [ "pdf", ".pdf" ] )
pdf_file.print pdf_str
pdf_file.flush
#p pdf_file.size
IO.popen( "#{ PDFTOTEXT } -raw -enc EUC-JP #{ pdf_file.path } -" ) do |io|
io.read
end
end
CINII_APPID = "CiNii10-281c60b8055e2d850686566dedb7c922"
# CiNii Opensearch API
def cinii_search( keyword, opts = {} )
base_uri = "http://ci.nii.ac.jp/opensearch/search"
q = URI.encode_www_form_component( keyword )
cont = nil
cache_file = cache_xml( "cinii", q, opts[:start] )
#p File.mtime( cache_file )
if File.exist?( cache_file ) and ( Time.now - File.mtime( cache_file ) ) < CACHE_TIME
cont = open( cache_file ){|io| io.read }
else
# TODO: Atom/RSSの双方を対象にできるようにすること(現状は Atom のみ)
opts[ :format ] = "atom"
opts_s = opts.make_uri_params
opensearch_uri = URI.parse( "#{ base_uri }?q=#{ q }&appid=#{ CINII_APPID }&#{ opts_s }" )
response = http_get( opensearch_uri )
cont = response.body
open( cache_file, "w" ){|io| io.print cont }
end
data = {}
parser = LibXML::XML::Parser.string( cont )
doc = parser.parse
# ref. http://ci.nii.ac.jp/info/ja/if_opensearch.html
data[ :q ] = keyword
data[ :link ] = doc.find( "//atom:id", "atom:http://www.w3.org/2005/Atom" )[0].content.gsub( /&(format=atom|appid=#{ CINII_APPID })\b/, "" )
data[ :totalResults ] = doc.find( "//opensearch:totalResults" )[0].content.to_i
if data[ :totalResults ] > 0
data[ :itemsPerPage ] = doc.find( "//opensearch:itemsPerPage" )[0].content.to_i
end
entries = doc.find( "//atom:entry", "atom:http://www.w3.org/2005/Atom" )
data[ :entries ] = []
entries.each do |e|
title = e.find( "./atom:title", "atom:http://www.w3.org/2005/Atom" )[0]
title = title ? title.content : "(No Title)"
url = e.find( "./atom:id", "atom:http://www.w3.org/2005/Atom" )[0].content
author = e.find( ".//atom:author/atom:name", "atom:http://www.w3.org/2005/Atom" ).to_a.map{|name|
a = name.content
/^\s*\W/.match( a ) ? a.gsub( /\s*,\s*/, " " ) : a
}.join( "; " )
pubname = e.find( "./prism:publicationName", "prism:http://prismstandard.org/namespaces/basic/2.0/" )[0]
if pubname.nil?
pubname = e.find( "./dc:publisher", "dc:http://purl.org/dc/elements/1.1/" )[0]
pubname = pubname.content if pubname
else
pubname = pubname.content
end
pubdate = e.find( "./prism:publicationDate", "prism:http://prismstandard.org/namespaces/basic/2.0/" )[0] #.content
pubdate = pubdate.nil? ? "" : pubdate.content
description = e.find( "./atom:content", "atom:http://www.w3.org/2005/Atom" )[0]
description = description.nil? ? "" : description.content
data[ :entries ] << {
:title => title,
:url => url,
:author => author,
:publicationName => pubname,
:publicationDate => pubdate,
:description => description,
}
end
data
end
def cinii_research_search( keyword, opts = {} )
base_uri = "https://cir.nii.ac.jp/opensearch/all"
q = URI.encode_www_form_component( keyword )
cont = nil
cache_file = cache_xml( "cinii_r", q, opts[:start] )
#p File.mtime( cache_file )
if File.exist?( cache_file ) and ( Time.now - File.mtime( cache_file ) ) < CACHE_TIME
cont = open( cache_file ){|io| io.read }
else
# TODO: Atom/RSSの双方を対象にできるようにすること(現状は Atom のみ)
opts[ :format ] = "atom"
opts_s = opts.make_uri_params
opensearch_uri = URI.parse( "#{ base_uri }?q=#{ q }&appid=#{ CINII_APPID }&#{ opts_s }" )
response = http_get( opensearch_uri )
cont = response.body
open( cache_file, "w" ){|io| io.print cont }
end
data = {}
parser = LibXML::XML::Parser.string( cont )
doc = parser.parse
# ref. https://support.nii.ac.jp/ja/cir/r_opensearch, (old) http://ci.nii.ac.jp/info/ja/if_opensearch.html
data[ :q ] = keyword
data[ :link ] = doc.find( "//atom:id", "atom:http://www.w3.org/2005/Atom" )[0].content.gsub( /&(format=atom|appid=#{ CINII_APPID })\b/, "" )
data[ :totalResults ] = doc.find( "//opensearch:totalResults" )[0].content.to_i
if data[ :totalResults ] > 0
data[ :itemsPerPage ] = doc.find( "//opensearch:itemsPerPage" )[0].content.to_i
end
entries = doc.find( "//atom:entry", "atom:http://www.w3.org/2005/Atom" )
data[ :entries ] = []
entries.each do |e|
title = e.find( "./atom:title", "atom:http://www.w3.org/2005/Atom" )[0]
title = title ? title.content : "(No Title)"
url = e.find( "./atom:id", "atom:http://www.w3.org/2005/Atom" )[0].content
author = e.find( ".//atom:author/atom:name", "atom:http://www.w3.org/2005/Atom" ).to_a.map{|name|
a = name.content
/^\s*\W/.match( a ) ? a.gsub( /\s*,\s*/, " " ) : a
}.join( "; " )
pubname = e.find( "./prism:publicationName", "prism:http://prismstandard.org/namespaces/basic/2.0/" )[0]
if pubname.nil?
pubname = e.find( "./dc:publisher", "dc:http://purl.org/dc/elements/1.1/" )[0]
pubname = pubname.content if pubname
else
pubname = pubname.content
end
pubdate = e.find( "./prism:publicationDate", "prism:http://prismstandard.org/namespaces/basic/2.0/" )[0] #.content
pubdate = pubdate.nil? ? "" : pubdate.content
description = e.find( "./atom:content", "atom:http://www.w3.org/2005/Atom" )[0]
description = description.nil? ? "" : description.content
data[ :entries ] << {
:title => title,
:url => url,
:author => author,
:publicationName => pubname,
:publicationDate => pubdate,
:description => description,
}
end
data
end
# CiNii (Author) Opensearch API
def cinii_author_search( keyword, opts = {} )
base_uri = "http://ci.nii.ac.jp/opensearch/author"
q = URI.encode_www_form_component( keyword )
cont = nil
cache_file = cache_xml( "cinii_author", q, opts[:start] )
#p File.mtime( cache_file )
if File.exist?( cache_file ) and ( Time.now - File.mtime( cache_file ) ) < CACHE_TIME
cont = open( cache_file ){|io| io.read }
else
opts[ :format ] = "atom"
opts[ :sortorder ] ||= 3
opts_s = opts.make_uri_params
opensearch_uri = URI.parse( "#{ base_uri }?q=#{ q }&appid=#{ CINII_APPID }&#{ opts_s }" )
response = http_get( opensearch_uri )
cont = response.body
open( cache_file, "w" ){|io| io.print cont }
end
data = {}
parser = LibXML::XML::Parser.string( cont )
doc = parser.parse
# ref. http://ci.nii.ac.jp/info/ja/if_opensearch_auth.html
data[ :q ] = keyword
data[ :link ] = doc.find( "//atom:id", "atom:http://www.w3.org/2005/Atom" )[0].content.gsub( /&(format=atom|appid=#{ CINII_APPID })\b/, "" )
data[ :totalResults ] = doc.find( "//opensearch:totalResults" )[0].content.to_i
entries = doc.find( "//atom:entry", "atom:http://www.w3.org/2005/Atom" )
data[ :entries ] = []
entries.each do |e|
title = e.find( "./atom:title", "atom:http://www.w3.org/2005/Atom" )[0].content
url = e.find( "./atom:id", "atom:http://www.w3.org/2005/Atom" )[0].content
affiliation = e.find( "./atom:content", "atom:http://www.w3.org/2005/Atom" )[0]
affiliation = affiliation ? affiliation.content : ""
data[ :entries ] << {
:title => title,
:url => url,
:affiliation => affiliation,
}
end
data
end
# CiNii (Author:NRID) Opensearch API
def cinii_nrid_search( nrid, opts = {} )
q = URI.encode_www_form_component( nrid )
base_uri = "http://ci.nii.ac.jp/opensearch/nrid/"
cont = nil
cache_file = cache_xml( "cinii_nrid", q, opts[:start] )
#p File.mtime( cache_file )
if File.exist?( cache_file ) and ( Time.now - File.mtime( cache_file ) ) < CACHE_TIME
cont = open( cache_file ){|io| io.read }
else
opts[ :format ] = "atom"
# opts[ :sortorder ] ||= 3
opts_s = opts.make_uri_params
opensearch_uri = URI.parse( "#{ base_uri }#{ q }?appid=#{ CINII_APPID }&#{ opts_s }" )
response = http_get( opensearch_uri )
cont = response.body
open( cache_file, "w" ){|io| io.print cont }
end
data = {}
parser = LibXML::XML::Parser.string( cont )
doc = parser.parse
# ref. http://ci.nii.ac.jp/info/ja/if_opensearch_auth.html
data[ :q ] = nrid
data[ :link ] = doc.find( "//atom:id", "atom:http://www.w3.org/2005/Atom" )[0].content.gsub( /&(format=atom|appid=#{ CINII_APPID })\b/, "" )
data[ :totalResults ] = doc.find( "//opensearch:totalResults" )[0].content.to_i
entries = doc.find( "//atom:entry", "atom:http://www.w3.org/2005/Atom" )
data[ :entries ] = []
entries.each do |e|
title = e.find( "./atom:title", "atom:http://www.w3.org/2005/Atom" )[0].content
url = e.find( "./atom:id", "atom:http://www.w3.org/2005/Atom" )[0].content
author = e.find( ".//atom:author/atom:name", "atom:http://www.w3.org/2005/Atom" ).to_a.map{|name| name.content }.join( "; " )
pubname = e.find( "./prism:publicationName", "prism:http://prismstandard.org/namespaces/basic/2.0/" )[0]
if pubname.nil?
pubname = e.find( "./dc:publisher", "dc:http://purl.org/dc/elements/1.1/" )[0]
pubname = pubname.content if pubname
else
pubname = pubname.content
end
pubdate = e.find( "./prism:publicationDate", "prism:http://prismstandard.org/namespaces/basic/2.0/" )[0] #.content
pubdate = pubdate.nil? ? "" : pubdate.content
description = e.find( "./atom:content", "atom:http://www.w3.org/2005/Atom" )[0]
description = description.nil? ? "" : description.content
data[ :entries ] << {
:title => title,
:url => url,
:author => author,
:publicationName => pubname,
:publicationDate => pubdate,
:description => description,
}
end
data
end
def cinii_author_nrid_search( name, naid = [] )
data = cinii_author_search( name )
result = data
if not naid.empty?
entries = []
result[ :entries ].each do |author|
#p author[ :url ]
if /nrid\/(.+)\Z/ =~ author[ :url ]
nrid = $1
if cinii_nrid_search( nrid )[ :entries ].find{|e| naid.include?( e[ :url ] ) }
entries << author
end
end
end
result[ :entries ] = entries
end
result
end
# NDL Porta Opensearch
def ndl_search( keyword, opts = {} )
base_uri = "http://api.porta.ndl.go.jp/servicedp/opensearch"
q = URI.encode_www_form_component( keyword )
cont = nil
cache_file = cache_xml( "ndl", q, opts[:start] )
if File.exist?( cache_file ) and ( Time.now - File.mtime( cache_file ) ) < CACHE_TIME
cont = open( cache_file ){|io| io.read }
else
opts[ :format ] = "atom"
opts[ :dpgroupid ] = "ndl"
if opts[ :start ]
opts[ :idx ] = opts[ :start ].dup
opts.delete( :start )
end
opts_s = opts.make_uri_params
opensearch_uri = URI.parse( "#{ base_uri }?any=#{ q }&#{ opts_s }" )
response = http_get( opensearch_uri )
cont = response.body
open( cache_file, "w" ){|io| io.print cont }
end
data = {}
parser = LibXML::XML::Parser.string( cont )
doc = parser.parse
data[ :q ] = keyword
data[ :link ] = "http://porta.ndl.go.jp/cgi-bin/openurl.cgi"
data[ :totalResults ] = doc.find( "//openSearch:totalResults", "http://a9.com/-/spec/opensearchrss/1.0/" )[0].content.to_i
entries = doc.find( "//item" )
data[ :entries ] = []
entries.each do |e|
dpid = e.find( "./dcndl_porta:dpid", "http://ndl.go.jp/dcndl/dcndl_porta/" )[0].content
title = e.find( "./title" )[0].content
url = e.find( "./link" )[0].content
author = e.find( ".//author" )
if author and author[0]
author = author[0].content
else
author = ""
end
source = e.find( "./source" )
if source and source[0]
source = source[0].content
else
source = ""
end
publicationName = e.find( "dcterms:bibliographicCitation", "http://purl.org/dc/terms/" )
if publicationName and publicationName[0]
publicationName = publicationName[0].content
else
publicationName = nil
end
date = e.find( "./dcterms:issued", "http://purl.org/dc/terms/" )
if date and date[0]
date = date[0].content
else
date = e.find( "./dcterms:modified", "http://purl.org/dc/terms/" )
if date and date[0]
date = date[0].content
else
date = nil
end
end
publisher = e.find( "./dc:publisher", "http://purl.org/dc/elements/1.1/" )
if publisher and publisher[0]
publisher = publisher[0].content
else
publisher = nil
end
description = e.find( "./description" )
if description and description[0] and dpid != "zassaku"
description = description[0].content
else
description = ""
end
if publicationName.nil? or publicationName.empty?
publicationName = [ source, publisher ].select{|type|
not type.nil? and not type.empty?
}.join( "; " )
end
isbn = e.find( "./dc:identifier[@xsi:type='dcndl:ISBN']",
[ "dc:http://purl.org/dc/elements/1.1/",
"xsi:http://www.w3.org/2001/XMLSchema-instance",
"dcndl:http://ndl.go.jp/dcndl/terms/" ] )[0]
isbn = isbn.content if isbn
data[ :entries ] << {
:title => title,
:url => url,
:author => author,
:source => source,
:date => date,
:publicationDate => date,
:publisher => publisher,
:publicationName => publicationName,
:description => description,
:dpid => dpid,
:isbn => isbn,
}
end
data
end
# NDLサーチ版:
def iss_ndl_search( keyword, opts = {} )
base_uri = "http://iss.ndl.go.jp/api/opensearch"
q = URI.encode_www_form_component( keyword )
cont = nil
cache_file = cache_xml( "ndl", q, opts[:start] )
if File.exist?( cache_file ) and ( Time.now - File.mtime( cache_file ) ) < CACHE_TIME
cont = open( cache_file ){|io| io.read }
else
opts[ :dpgroupid ] = "ndl"
if opts[ :start ]
opts[ :idx ] = opts[ :start ]
opts.delete( :start )
end
opts_s = opts.make_uri_params
opensearch_uri = URI.parse( "#{ base_uri }?any=#{ q }&#{ opts_s }" )
response = http_get( opensearch_uri )
cont = response.body
open( cache_file, "w" ){|io| io.print cont }
end
data = {}
#STDERR.puts cont
parser = LibXML::XML::Parser.string( cont )
doc = parser.parse
data[ :q ] = keyword
data[ :link ] = doc.find( "//link" )[0].content.sub( /\/api\/opensearch/, '/books' ).sub( /&dpgroupid=ndl/, "" )
data[ :totalResults ] = doc.find( "//openSearch:totalResults", "http://a9.com/-/spec/opensearchrss/1.0/" )[0].content.to_i
entries = doc.find( "//item" )
data[ :entries ] = []
entries.each do |e|
#dpid = e.find( "./dcndl:dpid", "http://ndl.go.jp/dcndl/dcndl_porta/" )[0].content
title = e.find( "./title" )[0].content
url = e.find( "./link" )[0].content
author = e.find( ".//author" )
if author and author[0]
author = author[0].content
else
author = ""
end
creators = e.find( ".//dc:creator", "http://purl.org/dc/elements/1.1/" )
creator = creators.map{|e| e.content }.join( ", " )
source = e.find( "./source" )
if source and source[0]
source = source[0].content
else
source = ""
end
publicationName = e.find( "./dcndl:publicationName", "dcndl:http://ndl.go.jp/dcndl/terms/" )
if publicationName and publicationName[0]
publicationName = publicationName[0].content
else
publicationName = publicationName[0]
end
volume = e.find( "./dcndl:publicationVolume", "dcndl:http://ndl.go.jp/dcndl/terms/" )
if volume and volume[0]
volume = volume[0].content
end
date = e.find( "./dcterms:issued", "http://purl.org/dc/terms/" )
if date and date[0]
date = date[0].content
else
date = e.find( "./dcterms:modified", "http://purl.org/dc/terms/" )
if date and date[0]
date = date[0].content
else
date = nil
end
end
publisher = e.find( "./dc:publisher", "http://purl.org/dc/elements/1.1/" )
if publisher and publisher[0]
publisher = publisher[0].content
else
publisher = nil
end
description = e.find( "./description" )
if description and description[0] #and dpid != "zassaku"
description = description[0].content
else
description = ""
end
isbn = e.find( "./dc:identifier[@xsi:type='dcndl:ISBN']",
[ "dc:http://purl.org/dc/elements/1.1/",
"xsi:http://www.w3.org/2001/XMLSchema-instance",
"dcndl:http://ndl.go.jp/dcndl/terms/" ] )[0]
isbn = isbn.content if isbn
data[ :entries ] << {
:title => title,
:url => url,
:author => author,
:creator => creator,
:source => source,
:date => date,
:publicationDate => date,
:publisher => publisher,
:publicationName => publicationName,
:description => description,
#:dpid => dpid,
:isbn => isbn,
:volume => volume,
}
end
data
end
# レファ協API via NDL PORTA Opensearch
def crd_search2( keyword, opts = {} )
base_uri = "http://api.porta.ndl.go.jp/servicedp/opensearch"
q = URI.encode_www_form_component( keyword )
cont = nil
cache_file = cache_xml( "crd2", q, opts[:start] )
if File.exist?( cache_file ) and ( Time.now - File.mtime( cache_file ) ) < CACHE_TIME
cont = open( cache_file ){|io| io.read }
else
opts[ :format ] = "atom"
opts[ :dpid ] = "refkyo"
opts_s = opts.make_uri_params
opensearch_uri = URI.parse( "#{ base_uri }?any=#{ q }&#{ opts_s }" )
response = http_get( opensearch_uri )
cont = response.body
open( cache_file, "w" ){|io| io.print cont }
end
data = {}
parser = LibXML::XML::Parser.string( cont )
doc = parser.parse
data[ :q ] = keyword
data[ :link ] = "http://iss.ndl.go.jp/"
data[ :totalResults ] = doc.find( "//openSearch:totalResults", "http://a9.com/-/spec/opensearchrss/1.0/" )[0].content.to_i
entries = doc.find( "//item" )
data[ :entries ] = []
entries.each do |e|
dpid = e.find( "./dcndl_porta:dpid", "http://ndl.go.jp/dcndl/terms/" )[0].content
title = e.find( "./title" )[0].content
url = e.find( "./link" )[0].content
author = e.find( ".//author" )
if author and author[0]
author = author[0].content
else
author = ""
end
source = e.find( "./source" )
if source and source[0]
source = source[0].content
else
source = ""
end
publicationName = e.find( "dcterms:bibliographicCitation", "http://purl.org/dc/terms/" )
if publicationName and publicationName[0]
publicationName = publicationName[0].content
else
publicationName = nil
end
date = e.find( "./dcterms:issued", "http://purl.org/dc/terms/" )
if date and date[0]
date = date[0].content
else
date = e.find( "./dcterms:modified", "http://purl.org/dc/terms/" )
if date and date[0]
date = date[0].content
else
date = nil
end
end
publisher = e.find( "./dc:publisher", "http://purl.org/dc/elements/1.1/" )
if publisher and publisher[0]
publisher = publisher[0].content
else
publisher = nil
end
description = e.find( "./description" )
if description and description[0] and dpid != "zassaku"
description = description[0].content
else
description = ""
end
if publicationName.nil? or publicationName.empty?
publicationName = [ source, publisher ].select{|e|
not e.nil? and not e.empty?
}.join( "; " )
end
data[ :entries ] << {
:title => title,
:url => url,
:author => author,
:source => source,
:date => date,
:publicationDate => date,
:publisher => publisher,
:publicationName => publicationName,
:description => description,
:dpid => dpid,
}
end
data
end
# レファレンス協同データベースAPI
def crd_search( keyword, opts = {} )
require "htmlentities"
base_uri = "http://crd.ndl.go.jp/refapi/servlet/refapi.RSearchAPI"
q = URI.encode_www_form_component( keyword )
opts[ :query_logic ] = "2"
opts_s = opts.make_uri_params
query = "01_" + q + ".02_" + q
opts_s = "&" + opts_s if not opts_s.empty?
uri = URI.parse( "#{ base_uri }?query=#{ query }#{ opts_s }" )
cont = nil
cache_file = cache_xml( "crd", q, opts[:start] )
if File.exist?( cache_file ) and ( Time.now - File.mtime( cache_file ) ) < CACHE_TIME
cont = open( cache_file ){|io| io.read }
else
response = http_get( uri )
cont = response.body
open( cache_file, "w" ){|io| io.print cont }
end
data = {}
parser = LibXML::XML::Parser.string( cont )
doc = nil
begin
doc = parser.parse
rescue LibXML::XML::Error => e
begin
parser = LibXML::XML::Parser.string( NKF.nkf( "-Ww", cont ) )
doc = parser.parse
rescue
File.unlink( cache_file )
raise e
end
end
# ref. http://ci.nii.ac.jp/info/ja/if_opensearch.html
data[ :q ] = keyword
#data[ :link ] = doc.find( "//atom:id", "atom:http://www.w3.org/2005/Atom" )[0].content.sub( /&format=atom\b/, "" )
data[ :link ] = "http://crd.ndl.go.jp/" # TODO: リンク先を適宜補完すること。
data[ :totalResults ] = doc.find( "//crd:hit_num", "crd:http://crd.ndl.go.jp/refapi/servlet/refapi.RSearchAPI" )[0].content.to_i
entries = doc.find( "//crd:result", "crd:http://crd.ndl.go.jp/refapi/servlet/refapi.RSearchAPI" )
data[ :entries ] = []
entries.each do |e|
title = e.find( "./crd:QUESTION", "crd:http://crd.ndl.go.jp/refapi/servlet/refapi.RSearchAPI" )[0].content
url = e.find( "./crd:URL", "crd:http://crd.ndl.go.jp/refapi/servlet/refapi.RSearchAPI" )[0].content
author = e.find( "./crd:LIB-NAME", "crd:http://crd.ndl.go.jp/refapi/servlet/refapi.RSearchAPI" ).to_a.map{|name| name.content }.join( "; " )
description = e.find( "./crd:ANSWER", "crd:http://crd.ndl.go.jp/refapi/servlet/refapi.RSearchAPI" )[0].content
if description.nil? or description.empty?
description = e.find( "./crd:ANS-PROC", "crd:http://crd.ndl.go.jp/refapi/servlet/refapi.RSearchAPI" )[0].content
end
pubdate = e.find( "./crd:CRT-DATE", "crd:http://crd.ndl.go.jp/refapi/servlet/refapi.RSearchAPI" )[0]
pubdate = pubdate ? pubdate.content : e.find( "./crd:REG-DATE", "crd:http://crd.ndl.go.jp/refapi/servlet/refapi.RSearchAPI" )[0].content
solution = e.find( "./crd:SOLUTION", "crd:http://crd.ndl.go.jp/refapi/servlet/refapi.RSearchAPI" )[0]
solution = solution ? solution.content : nil
data[ :entries ] << {
:title => title,
:url => url,
:author => author,
:description => description,
:publicationDate => pubdate,
:solution => solution,
}
end
data
end
# WorldCat Basic API (Opensearch)
WORLDCAT_BASIC_WSKEY = "5lIR8i5bSQQNg4Xb3ro6QbOzXiGSs6PrGGJ02BKolP9qTUQRcui2Ze9AsQIlM8IzV0E9XMcrWWieWvrM"
def worldcat_search( keyword, opts = {} )
base_uri = "http://worldcat.org/webservices/catalog/search/opensearch"
q = URI.encode_www_form_component( keyword )
cont = nil
cache_file = cache_xml( "worldcat", q, opts[:start] )
if File.exist?( cache_file ) and ( Time.now - File.mtime( cache_file ) ) < CACHE_TIME
cont = open( cache_file ){|io| io.read }
else
opts[ :format ] = "atom"
opts[ :wskey ] = WORLDCAT_BASIC_WSKEY
opts_s = opts.make_uri_params
opensearch_uri = URI.parse( "#{ base_uri }?q=#{ q }&#{ opts_s }" )
response = http_get( opensearch_uri )
cont = response.body
open( cache_file, "w" ){|io| io.print cont }
end
data = {}
parser = LibXML::XML::Parser.string( cont )
doc = parser.parse
# ref. http://ci.nii.ac.jp/info/ja/if_opensearch.html
data[ :q ] = keyword
# data[ :link ] = doc.find( "//atom:id", "atom:http://www.w3.org/2005/Atom" )[0].content.sub( /&format=atom\b/, "" ).sub( /&wskey=\w+/, "" )
data[ :link ] = "http://www.worldcat.org/search?q=#{ q }"
#STDERR.puts q.inspect
#STDERR.puts doc.find( "//opensearch:totalResults" )[0].inspect
#STDERR.puts doc.find( "//opensearch:totalResults" )[0].class
totalResults = doc.find( "//opensearch:totalResults" )[0]
if totalResults
data[ :totalResults ] = doc.find( "//opensearch:totalResults" )[0].content.to_i
else
data[ :totalResults ] = 0
end
entries = doc.find( "//atom:entry", "atom:http://www.w3.org/2005/Atom" )
data[ :entries ] = []
entries.each do |e|
title = e.find( "./atom:title", "atom:http://www.w3.org/2005/Atom" )[0].content
url = e.find( "./atom:id", "atom:http://www.w3.org/2005/Atom" )[0].content
author = e.find( ".//atom:author/atom:name", "atom:http://www.w3.org/2005/Atom" ).to_a.map{|name| name.content }.join( "; " )
content = e.find( "./atom:content", "atom:http://www.w3.org/2005/Atom" )[0]
isbn = nil
e.find( "./dc:identifier", "dc:http://purl.org/dc/elements/1.1/" ).each do |identifier|
if identifier.content =~ /\Aurn:ISBN:(\d{9,12}[\dx])\Z/o
isbn = $1
break
end
end
data[ :entries ] << {
:title => title,
:url => url,
:author => author,
:content => content,
:publicationName => content,
:isbn => isbn,
}
end
data
end
# JAWikipedia API
def wikipedia_ja_search( keyword, opts = {} )
base_uri = "http://ja.wikipedia.org/w/api.php"
q = URI.encode_www_form_component( keyword )
cont = nil
cache_file = cache_xml( "jawikipedia", q, opts[:start] )
if File.exist?( cache_file ) and ( Time.now - File.mtime( cache_file ) ) < CACHE_TIME
cont = open( cache_file ){|io| io.read }
else
opts[ :action ] = "query"
opts[ :list ] = "search"
opts[ :format ] = "xml"
opts_s = opts.make_uri_params
search_uri = URI.parse( "#{ base_uri }?srsearch=#{ q }&#{ opts_s }" )
response = http_get( search_uri )
cont = response.body
open( cache_file, "w" ){|io| io.print cont }
end
data = {}
parser = LibXML::XML::Parser.string( cont )
doc = parser.parse
# ref. http://ci.nii.ac.jp/info/ja/if_opensearch.html
data[ :q ] = keyword
# data[ :link ] = doc.find( "//atom:id", "atom:http://www.w3.org/2005/Atom" )[0].content.sub( /&format=atom\b/, "" ).sub( /&wskey=\w+/, "" )
data[ :link ] = "http://ja.wikipedia.org/wiki/Sepecial:Search/#{ q }"
data[ :totalResults ] = doc.find_first( "//searchinfo" ).attributes[ "totalhits" ].to_i
entries = doc.find( "//p" )
data[ :entries ] = []
entries.each do |e|
title = e.attributes[ "title" ]
url = "http://ja.wikipedia.org/wiki/#{ URI.encode_www_form_component( title ) }"
content = e.attributes[ "snippet" ]
timestamp = e.attributes[ "timestamp" ]
data[ :entries ] << {
:title => title,
:url => url,
:content => content,
:publicationName => content,
:publicationDate => timestamp,
}
end
data
end
# EPI SRU API
def epi_search( keyword, opts = {} )
base_uri = "http://dl.nier.go.jp/epi"
client_base_uri = "http://dl.nier.go.jp/epi-search/sru-gw.rb"
q = URI.encode_www_form_component( keyword.split.join( " AND " ) )
cont = nil
cache_file = cache_xml( "epi", q, opts[:start] )
#p File.mtime( cache_file )
if File.exist?( cache_file ) and ( Time.now - File.mtime( cache_file ) ) < CACHE_TIME
cont = open( cache_file ){|io| io.read }
else
opts[ :version ] = "1.1"
opts[ :operation ] = "searchRetrieve"
opts[ :maximumRecords ] ||= 20
opts[ :startRecord ] ||= opts[ :start ] if opts[ :start ]
#p opts
params = [ :operation, :version, :query, :startRecord, :maximumRecords, :recordPacking, :recordSchema, :recordXPath, :resultSetTTL, :sortKeys, :stylesheet, :extraRequestData ].map do |e|
opts[ e ] ? "#{ e }=#{ URI.encode_www_form_component( opts[e].to_s ) }" : nil
end.compact.join( "&" )
#p params