Class: RDF::Tabular::Reader

Inherits:
Reader
  • Object
show all
Includes:
Util::Logger
Defined in:
lib/rdf/tabular/reader.rb

Overview

A Tabular Data to RDF parser in Ruby.

Author:

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input = $stdin, **options) {|reader| ... } ⇒ Reader

Initializes the RDF::Tabular Reader instance.

Parameters:

  • input (Util::File::RemoteDoc, IO, StringIO, Array<Array<String>>, String) (defaults to: $stdin)

    An opened file possibly JSON Metadata, or an Array used as an internalized array of arrays

  • options (Hash{Symbol => Object})

    any additional options (see RDF::Reader#initialize)

Options Hash (**options):

  • :decode_uri (Boolean)

    Decode %-encodings in the result of a URI Template operation.

  • :fks_referencing_table (Array<Hash>)

    When called with Table metadata, a list of the foreign keys referencing this table

  • :metadata (Metadata, Hash, String, RDF::URI)

    user supplied metadata, merged on top of extracted metadata. If provided as a URL, Metadata is loade from that location

  • :minimal (Boolean)

    includes only the information gleaned from the cells of the tabular data

  • :noProv (Boolean)

    do not output optional provenance information

Yields:

  • (reader)

    self

Yield Parameters:

  • reader (RDF::Reader)

Yield Returns:

  • (void)

    ignored

Raises:

  • (RDF::ReaderError)

    if the CSV document cannot be loaded



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
# File 'lib/rdf/tabular/reader.rb', line 75

def initialize(input = $stdin, **options, &block)
  super do
    # Base would be how we are to take this
    @options[:base] ||= base_uri.to_s if base_uri
    @options[:base] ||= input.base_uri if input.respond_to?(:base_uri)
    @options[:base] ||= input.path if input.respond_to?(:path)
    @options[:base] ||= input.filename if input.respond_to?(:filename)
    if RDF::URI(@options[:base]).relative? && File.exist?(@options[:base].to_s)
      file_uri = "file:" + File.expand_path(@options[:base])
      @options[:base] = RDF::URI(file_uri.to_s).normalize
    end

    log_debug("Reader#initialize") {"input: #{input.inspect}, base: #{@options[:base]}"}

    # Minimal implies noProv
    @options[:noProv] ||= @options[:minimal]

    @input = case input
    when String then StringIO.new(input)
    when Array then StringIO.new(input.map {|r| r.join(",")}.join("\n"))
    else input
    end

    log_depth do
      # If input is JSON, then the input is the metadata
      content_type = @input.respond_to?(:content_type) ? @input.content_type : ""
      if @options[:base] =~ /\.json(?:ld)?$/ || content_type =~ %r(application/(csvm\+|ld\+)?json)
        @metadata = Metadata.new(@input, filenames: @options[:base], **@options)
        # If @metadata is for a Table, turn it into a TableGroup
        @metadata = @metadata.to_table_group if @metadata.is_a?(Table)
        @metadata.normalize!
        @input = @metadata
      elsif (@options[:base].to_s.end_with?(".html") || %w(text/html application/xhtml+html).include?(content_type)) &&
            !RDF::URI(@options[:base].to_s).fragment
        require 'nokogiri' unless defined?(:Nokogiri)
        doc = Nokogiri::HTML.parse(input)
        doc.xpath("//script[@type='application/csvm+json']/text()").each do |script|
          def script.content_type; "application/csvm+json"; end
          log_debug("Reader#initialize") {"Process HTML script block"}
          @input = script
          @metadata = Metadata.new(@input, filenames: @options[:base], **@options)
          # If @metadata is for a Table, turn it into a TableGroup
          @metadata = @metadata.to_table_group if @metadata.is_a?(Table)
          @metadata.normalize!
          @input = @metadata
        end
      elsif @options[:no_found_metadata]
        # Extract embedded metadata and merge
         = @options[:metadata] || Table.new({}, context: "http://www.w3.org/ns/csvw")
        dialect = .dialect.dup

        # HTTP flags for setting header values
        dialect.header = false if (input.headers.fetch(:content_type, '').split(';').include?('header=absent') rescue false)
        dialect.encoding = input.charset if (input.charset rescue nil)
        dialect.separator = "\t" if (input.content_type == "text/tsv" rescue nil)
        embed_options = @options.dup
        embed_options[:lang] = .lang if .lang
         = dialect.(input, @options[:metadata], **embed_options)

        if (@metadata = @options[:metadata]) && @metadata.tableSchema
          @metadata.verify_compatible!()
        else
          @metadata = .normalize!
        end

        lang = input.headers[:content_language] rescue nil
        lang = nil if lang.to_s.include?(',') # Not for multiple languages
        # Set language, if unset and provided
        @metadata.lang ||= lang if lang 
          
        @metadata.dialect = dialect
      else
        # It's tabluar data. Find metadata and proceed as if it was specified in the first place
        @options[:original_input] = @input unless @options[:metadata]
        @input = @metadata = Metadata.for_input(@input, **@options).normalize!
      end

      log_debug("Reader#initialize") {"input: #{input}, metadata: #{.inspect}"}

      if block_given?
        case block.arity
          when 0 then instance_eval(&block)
          else block.call(self)
        end
      end
    end
  end
end

Instance Attribute Details

#input:read (readonly)

Input open to read

Returns:

  • (:read)


21
22
23
# File 'lib/rdf/tabular/reader.rb', line 21

def input
  @input
end

#metadataMetadata (readonly)

Metadata associated with the CSV

Returns:



16
17
18
# File 'lib/rdf/tabular/reader.rb', line 16

def 
  @metadata
end

Class Method Details

.optionsObject

Writer options



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
# File 'lib/rdf/tabular/reader.rb', line 26

def self.options
  super + [
    RDF::CLI::Option.new(
      symbol: :metadata,
      datatype: RDF::URI,
      control: :url2,
      on: ["--metadata URI"],
      description: "user supplied metadata, merged on top of extracted metadata. If provided as a URL, Metadata is loade from that location.") {|arg| RDF::URI(arg)},
    RDF::CLI::Option.new(
      symbol: :minimal,
      control: :checkbox,
      datatype: TrueClass,
      on: ["--minimal"],
      description: "Includes only the information gleaned from the cells of the tabular data.") {true},
    RDF::CLI::Option.new(
      symbol: :noProv,
      datatype: TrueClass,
      control: :checkbox,
      on: ["--no-prov"],
      description: "do not output optional provenance information.") {true},
    RDF::CLI::Option.new(
      symbol: :decode_uri,
      datatype: TrueClass,
      control: :checkbox,
      on: ["--decode-uri"],
      description: "decode %-encodings in the result of a URI Template operation."
    )
  ]
end

Instance Method Details

#minimal?Boolean

Returns:

  • (Boolean)


639
# File 'lib/rdf/tabular/reader.rb', line 639

def minimal?; @options[:minimal]; end

#prov?Boolean

Returns:

  • (Boolean)


640
# File 'lib/rdf/tabular/reader.rb', line 640

def prov?; !(@options[:noProv]); end

#to_hash(**options) ⇒ Hash, Array

Return a hash representation of the data for JSON serialization

Produces an array if run in minimal mode.

Parameters:

  • options (Hash{Symbol => Object})

Returns:

  • (Hash, Array)


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
# File 'lib/rdf/tabular/reader.rb', line 456

def to_hash(**options)
  # Construct metadata from that passed from file open, along with information from the file.
  if input.is_a?(Metadata)
    log_debug("each_statement: metadata") {input.inspect}
    log_depth do
      # Get Metadata to invoke and open referenced files
      begin
        # Validate metadata
        input.validate!

        tables = []
        table_group = {}
        table_group['@id'] = input.id.to_s if input.id

        # Common Properties
        input.each do |key, value|
          next unless key.to_s.include?(':') || key == :notes
          table_group[key] = input.common_properties(nil, key, value)
          table_group[key] = [table_group[key]] if key == :notes && !table_group[key].is_a?(Array)
        end

        table_group['tables'] = tables

        if options[:original_input] && !input.describes_file?(options[:base_uri])
          Reader.new(options[:original_input], **options.merge(
              metadata:           input.tables.first,
              base:               input.tables.first.url,
              minimal:            minimal?,
              no_found_metadata:  true,
          )) do |r|
            case t = r.to_hash(**options)
            when Array then tables += t unless input.tables.first.suppressOutput
            when Hash  then tables << t unless input.tables.first.suppressOutput
            end
          end
        else
          input.each_table do |table|
            next if table.suppressOutput && !validate?
            Reader.open(table.url, **options.merge(
              metadata:           table,
              base:               table.url,
              minimal:            minimal?,
              no_found_metadata:  true,
            )) do |r|
              case t = r.to_hash(**options)
              when Array then tables += t unless table.suppressOutput
              when Hash  then tables << t unless table.suppressOutput
              end
            end
          end
        end

        # Lastly, if validating, validate foreign key integrity
        validate_foreign_keys(input) if validate?

        # Result is table_group or array
        minimal? ? tables : table_group
      end
    end
  else
    rows = []
    table = {}
    table['@id'] = .id.to_s if .id
    table['url'] = .url.to_s

    table.merge!("row" => rows)

    # Input is file containing CSV data.
    # Output ROW-Level statements
    primary_keys = []
    .each_row(input) do |row|
      if row.is_a?(RDF::Statement)
        # May add additional comments
        table['rdfs:comment'] ||= []
        table['rdfs:comment'] << row.object.to_s
        next
      end

      # Collect primary and foreign keys if validating
      if validate?
        primary_keys << row.primaryKey
        collect_foreign_key_references(, options[:fks_referencing_table], row)
      end

      # Output row-level metadata
      r, a, values = {}, {}, {}
      r["url"] = row.id.to_s
      r["rownum"] = row.number

      # Row titles
      Array(row.titles).each { |t| merge_compacted_value(r, "titles", t.to_s) unless t.nil?}

      row.values.each_with_index do |cell, index|
        column = .tableSchema.columns[index]

        # Collect cell errors
        unless Array(cell.errors).empty?
          self.send(validate? ? :log_error : :log_warn,
            "Table #{.url} row #{row.number}(src #{row.sourceNumber}, col #{cell.column.sourceNumber}): ") do
            cell.errors.join("\n")
          end
        end

        # Ignore suppressed columns
        next if column.suppressOutput

        # Skip valueUrl cells where the valueUrl is null
        next if cell.column.valueUrl && cell.valueUrl.nil?

        # Skip empty sequences
        next if !cell.column.valueUrl && cell.value.is_a?(Array) && cell.value.empty?

        subject = cell.aboutUrl || 'null'
        co = (a[subject.to_s] ||= {})
        co['@id'] = subject.to_s unless subject == 'null'
        prop = case cell.propertyUrl
        when RDF.type then '@type'
        when nil then CGI.unescape(column.name) # Use URI-decoded name
        else
          # Compact the property to a term or prefixed name
          .context.compact_iri(cell.propertyUrl, vocab: true)
        end

        value = case
        when prop == '@type'
          .context.compact_iri(cell.valueUrl || cell.value, vocab: true)
        when cell.valueUrl
          unless subject == cell.valueUrl
            values[cell.valueUrl.to_s] ||= {o: co, prop: prop, count: 0}
            values[cell.valueUrl.to_s][:count] += 1
          end
          cell.valueUrl.to_s
        when cell.value.is_a?(RDF::Literal::Double)
          cell.value.object.nan? || cell.value.object.infinite? ? cell.value : cell.value.object
        when cell.value.is_a?(RDF::Literal::Integer)
          cell.value.object.to_i
        when cell.value.is_a?(RDF::Literal::Numeric)
          cell.value.object.to_f
        when cell.value.is_a?(RDF::Literal::Boolean)
          cell.value.object
        when cell.value
          cell.value
        end

        # Add or merge value
        merge_compacted_value(co, prop, value) unless value.nil?
      end

      # Check for nesting
      values.keys.each do |valueUrl|
        next unless a.has_key?(valueUrl)
        ref = values[valueUrl]
        co = ref[:o]
        prop = ref[:prop]
        next if ref[:count] != 1
        raise "Expected #{ref[o][prop].inspect} to include #{valueUrl.inspect}" unless Array(co[prop]).include?(valueUrl)
        co[prop] = Array(co[prop]).map {|e| e == valueUrl ? a.delete(valueUrl) : e}
        co[prop] = co[prop].first if co[prop].length == 1
      end

      r["describes"] = a.values

      if minimal?
        rows.concat(r["describes"])
      else
        rows << r
      end
    end

    # Validate primary keys
    validate_primary_keys(, primary_keys) if validate?

    # Use string values notes and common properties
    .each do |key, value|
      next unless key.to_s.include?(':') || key == :notes
      table[key] = .common_properties(nil, key, value)
      table[key] = [table[key]] if key == :notes && !table[key].is_a?(Array)
    end unless minimal?

    minimal? ? table["row"] : table
  end
end

#to_json(options = @options) ⇒ String

Transform to JSON. Note that this must be run from within the reader context if the input is an open IO stream.

Examples:

outputing annotated CSV as JSON

result = nil
RDF::Tabular::Reader.open("etc/doap.csv") do |reader|
  result = reader.to_json
end
result #=> {...}

outputing annotated CSV as JSON from an in-memory structure

csv = %(
  GID,On Street,Species,Trim Cycle,Inventory Date
  1,ADDISON AV,Celtis australis,Large Tree Routine Prune,10/18/2010
  2,EMERSON ST,Liquidambar styraciflua,Large Tree Routine Prune,6/2/2010
  3,EMERSON ST,Liquidambar styraciflua,Large Tree Routine Prune,6/2/2010
).gsub(/^\s+/, '')
r = RDF::Tabular::Reader.new(csv)
r.to_json #=> {...}

Parameters:

  • options (Hash{Symbol => Object}) (defaults to: @options)

    may also be a JSON state

Options Hash (options):

  • io (IO, StringIO)

    to output to file

  • :state (::JSON::State)

    used when dumping

  • :atd (Boolean)

    output Abstract Table representation instead

Returns:

  • (String)

Raises:



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
# File 'lib/rdf/tabular/reader.rb', line 411

def to_json(options = @options)
  io = case options
  when IO, StringIO then options
  when Hash then options[:io]
  end
  json_state = case options
  when Hash
    case
    when options.has_key?(:state) then options[:state]
    when options.has_key?(:indent) then options
    else ::JSON::LD::JSON_STATE
    end
  when ::JSON::State, ::JSON::Ext::Generator::State, ::JSON::Pure::Generator::State
    options
  else ::JSON::LD::JSON_STATE
  end
  options = {} unless options.is_a?(Hash)

  hash_fn = :to_hash
  options = options.merge(noProv: @options[:noProv])

  res = if io
    ::JSON::dump_default_options = json_state
    ::JSON.dump(self.send(hash_fn, **options), io)
  else
    hash = self.send(hash_fn, **options)
    ::JSON.generate(hash, json_state)
  end

  if validate? && log_statistics[:error]
    raise RDF::Tabular::Error, "Errors found during processing"
  end

  res
rescue IOError => e
  raise RDF::Tabular::Error, e.message
end

#validate!Object

Do we have valid metadata?

Raises:

  • (RDF::ReaderError)


378
379
380
381
382
383
# File 'lib/rdf/tabular/reader.rb', line 378

def validate!
  @options[:validate] = true
  each_statement {}
rescue RDF::ReaderError => e
  raise Error, e.message
end