Class: RDF::Tabular::Reader
- Inherits:
-
Reader
- Object
- Reader
- RDF::Tabular::Reader
- Includes:
- Utils
- Defined in:
- lib/rdf/tabular/reader.rb
Overview
A Tabular Data to RDF parser in Ruby.
Instance Attribute Summary collapse
-
#input ⇒ :read
readonly
Input open to read.
-
#metadata ⇒ Metadata
readonly
Metadata associated with the CSV.
Instance Method Summary collapse
- #each_statement(&block) ⇒ Object
- #each_triple(&block) ⇒ Object
-
#initialize(input = $stdin, options = {}) {|reader| ... } ⇒ Reader
constructor
Initializes the RDF::Tabular Reader instance.
- #minimal? ⇒ Boolean
- #prov? ⇒ Boolean
-
#to_atd(options = {}) ⇒ Hash
Return a hash representation of the annotated tabular data model for JSON serialization.
-
#to_hash(options = {}) ⇒ Hash, Array
Return a hash representation of the data for JSON serialization.
-
#to_json(options = {}) ⇒ String
Transform to JSON.
Methods included from Utils
Constructor Details
#initialize(input = $stdin, options = {}) {|reader| ... } ⇒ Reader
Initializes the RDF::Tabular Reader instance.
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 |
# File 'lib/rdf/tabular/reader.rb', line 37 def initialize(input = $stdin, = {}, &block) super do # Base would be how we are to take this [:base] ||= base_uri.to_s if base_uri [:base] ||= input.base_uri if input.respond_to?(:base_uri) [:base] ||= input.path if input.respond_to?(:path) [:base] ||= input.filename if input.respond_to?(:filename) if RDF::URI([:base]).relative? && File.exist?([:base]) [:base] = "file:/#{File.expand_path(@options[:base])}" end [:depth] ||= 0 debug("Reader#initialize") {"input: #{input.inspect}, base: #{@options[:base]}"} # Minimal implies noProv [:noProv] ||= [:minimal] @input = input.is_a?(String) ? StringIO.new(input) : input depth do # If input is JSON, then the input is the metadata if [:base] =~ /\.json(?:ld)?$/ || @input.respond_to?(:content_type) && @input.content_type =~ %r(application/(?:ld+)json) = Metadata.new(@input, .merge(filenames: [:base])) # If @metadata is for a Table, merge with something empty to create a TableGroup metadata if .is_a?(TableGroup) .normalize! else = .merge(TableGroup.new({})) end @input = elsif [:no_found_metadata] # Extract embedded metadata and merge = [:metadata] = .dialect.(input, ) = .dup.merge!() else # HTTP flags if @input.respond_to?(:headers) && input.headers.fetch(:content_type, '').split(';').include?('header=absent') [:metadata] ||= Table.new(url: [:base]) [:metadata].dialect.header = false end # It's tabluar data. Find metadata and proceed as if it was specified in the first place = Metadata.for_input(@input, ) @input = end debug("Reader#initialize") {"input: #{input}, metadata: #{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
20 21 22 |
# File 'lib/rdf/tabular/reader.rb', line 20 def input @input end |
#metadata ⇒ Metadata (readonly)
Metadata associated with the CSV
15 16 17 |
# File 'lib/rdf/tabular/reader.rb', line 15 def end |
Instance Method Details
#each_statement(&block) ⇒ Object
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 |
# File 'lib/rdf/tabular/reader.rb', line 102 def each_statement(&block) if block_given? @callback = block start_time = Time.now # Construct metadata from that passed from file open, along with information from the file. if input.is_a?(Metadata) debug("each_statement: metadata") {input.inspect} # Validate metadata input.validate! depth do # Get Metadata to invoke and open referenced files case input.type when :TableGroup # Use resolved @id of TableGroup, if available table_group = input.id || RDF::Node.new add_statement(0, table_group, RDF.type, CSVW.TableGroup) unless minimal? # Common Properties input.each do |key, value| next unless key.to_s.include?(':') || key == :notes input.common_properties(table_group, key, value) do |statement| add_statement(0, statement) end end unless minimal? input.each_resource do |table| next if table.suppressOutput table_resource = table.id || RDF::Node.new add_statement(0, table_group, CSVW.table, table_resource) unless minimal? Reader.open(table.url, .merge( format: :tabular, metadata: table, base: table.url, no_found_metadata: true, table_resource: table_resource )) do |r| r.each_statement(&block) end end # Provenance if prov? activity = RDF::Node.new add_statement(0, table_group, RDF::PROV.wasGeneratedBy, activity) add_statement(0, activity, RDF.type, RDF::PROV.Activity) add_statement(0, activity, RDF::PROV.wasAssociatedWith, RDF::URI("http://rubygems.org/gems/rdf-tabular")) add_statement(0, activity, RDF::PROV.startedAtTime, RDF::Literal::DateTime.new(start_time)) add_statement(0, activity, RDF::PROV.endedAtTime, RDF::Literal::DateTime.new(Time.now)) unless (urls = input.resources.map(&:url)).empty? usage = RDF::Node.new add_statement(0, activity, RDF::PROV.qualifiedUsage, usage) add_statement(0, usage, RDF.type, RDF::PROV.Usage) urls.each do |url| add_statement(0, usage, RDF::PROV.entity, RDF::URI(url)) end add_statement(0, usage, RDF::PROV.hadRole, CSVW.csvEncodedTabularData) end unless Array(input.filenames).empty? usage = RDF::Node.new add_statement(0, activity, RDF::PROV.qualifiedUsage, usage) add_statement(0, usage, RDF.type, RDF::PROV.Usage) Array(input.filenames).each do |fn| add_statement(0, usage, RDF::PROV.entity, RDF::URI(fn)) end add_statement(0, usage, RDF::PROV.hadRole, CSVW.tabularMetadata) end end when :Table Reader.open(input.url, .merge(format: :tabular, metadata: input, base: input.url, no_found_metadata: true)) do |r| r.each_statement(&block) end else raise "Opened inappropriate metadata type: #{input.type}" end end return end # Output Table-Level RDF triples table_resource = .fetch(:table_resource, (.id || RDF::Node.new)) unless minimal? add_statement(0, table_resource, RDF.type, CSVW.Table) add_statement(0, table_resource, CSVW.url, RDF::URI(.url)) end # Common Properties .each do |key, value| next unless key.to_s.include?(':') || key == :notes .common_properties(table_resource, key, value) do |statement| add_statement(0, statement) end end unless minimal? # Input is file containing CSV data. # Output ROW-Level statements last_row_num = 0 .each_row(input) do |row| if row.is_a?(RDF::Statement) # May add additional comments row.subject = table_resource add_statement(last_row_num + 1, row) next end last_row_num = row.sourceNumber # Output row-level metadata row_resource = RDF::Node.new default_cell_subject = RDF::Node.new unless minimal? add_statement(row.sourceNumber, table_resource, CSVW.row, row_resource) add_statement(row.sourceNumber, row_resource, CSVW.rownum, row.number) add_statement(row.sourceNumber, row_resource, CSVW.url, row.id) end row.values.each_with_index do |cell, index| next if cell.column.suppressOutput # Skip ignored cells cell_subject = cell.aboutUrl || default_cell_subject propertyUrl = cell.propertyUrl || RDF::URI("#{metadata.url}##{cell.column.name}") add_statement(row.sourceNumber, row_resource, CSVW.describes, cell_subject) unless minimal? if cell.column.valueUrl add_statement(row.sourceNumber, cell_subject, propertyUrl, cell.valueUrl) if cell.valueUrl elsif cell.column.ordered && cell.column.separator list = RDF::List[*Array(cell.value)] add_statement(row.sourceNumber, cell_subject, propertyUrl, list.subject) list.each_statement do |statement| next if statement.predicate == RDF.type && statement.object == RDF.List add_statement(row.sourceNumber, statement.subject, statement.predicate, statement.object) end else Array(cell.value).each do |v| add_statement(row.sourceNumber, cell_subject, propertyUrl, v) end end end end end enum_for(:each_statement) end |
#each_triple(&block) ⇒ Object
250 251 252 253 254 255 256 257 |
# File 'lib/rdf/tabular/reader.rb', line 250 def each_triple(&block) if block_given? each_statement do |statement| block.call(*statement.to_triple) end end enum_for(:each_triple) end |
#minimal? ⇒ Boolean
544 |
# File 'lib/rdf/tabular/reader.rb', line 544 def minimal?; [:minimal]; end |
#prov? ⇒ Boolean
545 |
# File 'lib/rdf/tabular/reader.rb', line 545 def prov?; !([:noProv]); end |
#to_atd(options = {}) ⇒ Hash
Return a hash representation of the annotated tabular data model for JSON serialization
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 |
# File 'lib/rdf/tabular/reader.rb', line 481 def to_atd( = {}) # Construct metadata from that passed from file open, along with information from the file. if input.is_a?(Metadata) debug("each_statement: metadata") {input.inspect} depth do # Get Metadata to invoke and open referenced files case input.type when :TableGroup table_group = input.to_atd input.each_resource do |table| Reader.open(table.url, .merge( format: :tabular, metadata: table, base: table.url, no_found_metadata: true, # FIXME: remove noProv: true )) do |r| table = r.to_atd() # Fill in columns and rows in table_group entry from returned table t = table_group[:resources].detect {|tab| tab["url"] == table["url"]} t["columns"] = table["columns"] t["rows"] = table["rows"] end end # Result is table_group table_group when :Table table = nil Reader.open(input.url, .merge( format: :tabular, metadata: input, base: input.url, no_found_metadata: true, noProv: true )) do |r| table = r.to_atd() end table else raise "Opened inappropriate metadata type: #{input.type}" end end else rows = [] table = .to_atd rows, columns = table["rows"], table["columns"] # Input is file containing CSV data. # Output ROW-Level statements .each_row(input) do |row| rows << row.to_atd row.values.each_with_index do |cell, colndx| columns[colndx]["cells"] << cell.id end end table end end |
#to_hash(options = {}) ⇒ Hash, Array
Return a hash representation of the data for JSON serialization
Produces an array if run in minimal mode.
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 |
# File 'lib/rdf/tabular/reader.rb', line 321 def to_hash( = {}) # Construct metadata from that passed from file open, along with information from the file. if input.is_a?(Metadata) debug("each_statement: metadata") {input.inspect} depth do # Get Metadata to invoke and open referenced files case input.type when :TableGroup # 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['table'] = tables input.each_resource do |table| next if table.suppressOutput Reader.open(table.url, .merge( format: :tabular, metadata: table, base: table.url, minimal: minimal?, no_found_metadata: true )) do |r| case table = r.to_hash() when Array then tables += table when Hash then tables << table end end end # Result is table_group or array minimal? ? tables : table_group when :Table table = nil Reader.open(input.url, .merge( format: :tabular, metadata: input, base: input.url, minimal: minimal?, no_found_metadata: true )) do |r| table = r.to_hash() end table else raise "Opened inappropriate metadata type: #{input.type}" end end else rows = [] table = {} table['@id'] = .id.to_s if .id table['url'] = .url.to_s # 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? table.merge!("row" => rows) # Input is file containing CSV data. # Output ROW-Level statements .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 # Output row-level metadata r, a, values = {}, {}, {} r["url"] = row.id.to_s r["rownum"] = row.number row.values.each_with_index do |cell, index| column = .tableSchema.columns[index] # 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 column.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::Numeric) cell.value.object when cell.value.is_a?(RDF::Literal::Boolean) cell.value.object else cell.value end # Add or merge value merge_compacted_value(co, prop, value) 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 minimal? ? table["row"] : table end end |
#to_json(options = {}) ⇒ String
Transform to JSON. Note that this must be run from within the reader context if the input is an open IO stream.
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 |
# File 'lib/rdf/tabular/reader.rb', line 284 def to_json( = {}) io = case when IO, StringIO then when Hash then [:io] end json_state = case when Hash case when .has_key?(:state) then [:state] when .has_key?(:indent) then else ::JSON::LD::JSON_STATE end when ::JSON::State, ::JSON::Ext::Generator::State, ::JSON::Pure::Generator::State else ::JSON::LD::JSON_STATE end = {} unless .is_a?(Hash) hash_fn = [:atd] ? :to_atd : :to_hash = .merge(noProv: [:noProv]) if io ::JSON:: = json_state ::JSON.dump(self.send(hash_fn, ), io) else hash = self.send(hash_fn, ) ::JSON.generate(hash, json_state) end end |