diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..37a9318 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,27 @@ +name: Ruby + +on: + push: + branches: + - main + + pull_request: + +jobs: + build: + runs-on: ubuntu-latest + name: Ruby ${{ matrix.ruby }} + strategy: + matrix: + ruby: + - '3.3.0' + + steps: + - uses: actions/checkout@v4 + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: Run the default task + run: bundle exec rake diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b04a8c8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +/.bundle/ +/.yardoc +/_yardoc/ +/coverage/ +/doc/ +/pkg/ +/spec/reports/ +/tmp/ + +# rspec failure tracking +.rspec_status diff --git a/.rspec b/.rspec new file mode 100644 index 0000000..34c5164 --- /dev/null +++ b/.rspec @@ -0,0 +1,3 @@ +--format documentation +--color +--require spec_helper diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..e1cff4f --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,15 @@ +AllCops: + TargetRubyVersion: 3.0 + +Style/StringLiterals: + EnforcedStyle: double_quotes + +Style/StringLiteralsInInterpolation: + EnforcedStyle: double_quotes + +Style/Documentation: + Enabled: false +Metrics/BlockLength: + Enabled: false +Metrics/MethodLength: + Enabled: false \ No newline at end of file diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..6d1b5d3 --- /dev/null +++ b/Gemfile @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +# Specify your gem's dependencies in unstructured.gemspec +gemspec + +gem "rake", "~> 13.0" + +gem "rspec", "~> 3.0" + +gem "rubocop", "~> 1.21" diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000..41f7f4c --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,89 @@ +PATH + remote: . + specs: + unstructured (0.1.0) + faraday (~> 2.9.0) + faraday-multipart (~> 1.0.4) + marcel (~> 1.0.4) + webmock (~> 3.23.0) + +GEM + remote: https://rubygems.org/ + specs: + addressable (2.8.6) + public_suffix (>= 2.0.2, < 6.0) + ast (2.4.2) + bigdecimal (3.1.8) + crack (1.0.0) + bigdecimal + rexml + diff-lcs (1.5.1) + faraday (2.9.0) + faraday-net_http (>= 2.0, < 3.2) + faraday-multipart (1.0.4) + multipart-post (~> 2) + faraday-net_http (3.1.0) + net-http + hashdiff (1.1.0) + json (2.7.2) + language_server-protocol (3.17.0.3) + marcel (1.0.4) + multipart-post (2.4.1) + net-http (0.4.1) + uri + parallel (1.24.0) + parser (3.3.1.0) + ast (~> 2.4.1) + racc + public_suffix (5.0.5) + racc (1.7.3) + rainbow (3.1.1) + rake (13.2.1) + regexp_parser (2.9.1) + rexml (3.2.6) + rspec (3.13.0) + rspec-core (~> 3.13.0) + rspec-expectations (~> 3.13.0) + rspec-mocks (~> 3.13.0) + rspec-core (3.13.0) + rspec-support (~> 3.13.0) + rspec-expectations (3.13.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-mocks (3.13.1) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-support (3.13.1) + rubocop (1.63.5) + json (~> 2.3) + language_server-protocol (>= 3.17.0) + parallel (~> 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 1.8, < 3.0) + rexml (>= 3.2.5, < 4.0) + rubocop-ast (>= 1.31.1, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 3.0) + rubocop-ast (1.31.3) + parser (>= 3.3.1.0) + ruby-progressbar (1.13.0) + unicode-display_width (2.5.0) + uri (0.13.0) + webmock (3.23.0) + addressable (>= 2.8.0) + crack (>= 0.3.2) + hashdiff (>= 0.4.0, < 2.0.0) + +PLATFORMS + arm64-darwin-23 + ruby + +DEPENDENCIES + rake (~> 13.0) + rspec (~> 3.0) + rubocop (~> 1.21) + unstructured! + +BUNDLED WITH + 2.5.7 diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..fd2e845 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2024 Jose Fernando Davila + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..f16a344 --- /dev/null +++ b/README.md @@ -0,0 +1,46 @@ +# Unstructured +This is a Ruby client for the [Unstructured API](https://unstructured-io.github.io/unstructured/api.html). + +## Installation + +TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org. + +Install the gem and add to the application's Gemfile by executing: + + $ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG + +If bundler is not being used to manage dependencies, install the gem by executing: + + $ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG + +## Usage +```ruby +server_url = "https://api.unstructured.io" # "http://localhost:8000" if you are running a docker container +client = Unstructured::Client.new(server_url: server_url, api_key: ENV["UNSTRUCTURED_API_KEY"]) + +file_path = "./your_document.pdf" +params = { + strategy: "fast", + hi_res_model_name: "yolox", + pdf_infer_table_structure: true, + chunking_strategy: "by_title", + max_characters: 1000, + new_after_n_chars: 1000 +} +chunks = client.partition(file_path, params) + +``` + +## Development + +After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. + +To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org). + +## Contributing + +Bug reports and pull requests are welcome on GitHub at https://github.com/TelosLabs/unstructured. + +## License + +The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000..cca7175 --- /dev/null +++ b/Rakefile @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +require "bundler/gem_tasks" +require "rspec/core/rake_task" + +RSpec::Core::RakeTask.new(:spec) + +require "rubocop/rake_task" + +RuboCop::RakeTask.new + +task default: %i[spec rubocop] diff --git a/bin/console b/bin/console new file mode 100755 index 0000000..e80b7d3 --- /dev/null +++ b/bin/console @@ -0,0 +1,18 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "bundler/setup" +require "unstructured" + +# You can add fixtures and/or initialization code here to make experimenting +# with your gem easier. You can also use a different console, if you like. + +client = Unstructured::Client.new( + server_url: "http://localhost:8000", + api_key_auth: ENV["UNSTRUCTURED_API_KEY"] +) + +client.partition("./README.md") + +require "irb" +IRB.start(__FILE__) diff --git a/bin/setup b/bin/setup new file mode 100755 index 0000000..dce67d8 --- /dev/null +++ b/bin/setup @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' +set -vx + +bundle install + +# Do any other automated setup that you need to do here diff --git a/lib/unstructured.rb b/lib/unstructured.rb new file mode 100644 index 0000000..16ab7de --- /dev/null +++ b/lib/unstructured.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +require_relative "unstructured/version" + +module Unstructured + autoload :Client, "unstructured/client" + autoload :Collection, "unstructured/collection" + autoload :Error, "unstructured/error" + autoload :Object, "unstructured/object" + + autoload :ChunkCollection, "unstructured/chunk_collection" + autoload :Chunk, "unstructured/objects/chunk" +end diff --git a/lib/unstructured/chunk_collection.rb b/lib/unstructured/chunk_collection.rb new file mode 100644 index 0000000..c3b795b --- /dev/null +++ b/lib/unstructured/chunk_collection.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +module Unstructured + class ChunkCollection < Collection + def self.type + Unstructured::Chunk + end + end +end diff --git a/lib/unstructured/client.rb b/lib/unstructured/client.rb new file mode 100644 index 0000000..30d9f22 --- /dev/null +++ b/lib/unstructured/client.rb @@ -0,0 +1,78 @@ +# frozen_string_literal: true + +require "faraday" +require "faraday/multipart" +require "marcel" + +module Unstructured + class Client + SERVER_URL = "https://api.unstructured.io" + + attr_reader :server_url, :api_key_auth, :adapter + + def initialize(server_url: nil, api_key_auth: nil, adapter: Faraday.default_adapter, stubs: nil) + @server_url = server_url || SERVER_URL + @api_key_auth = api_key_auth + @adapter = adapter + @stubs = stubs + end + + def connection + @connection ||= Faraday.new do |conn| + conn.url_prefix = server_url + conn.request :multipart + conn.response :json, content_type: "application/json" + conn.adapter adapter, @stubs + conn.headers["unstructured-api-key"] = api_key_auth if api_key_auth + end + end + + def partition(file_path, params = {}, headers: {}) + ChunkCollection.from_response handle_response(connection.post( + "/general/v0/general", + default_params.merge(params).merge({ + files: files(file_path) + }), + headers + )) + end + + def inspect + "#<#{self.class.name} server_url=#{server_url.inspect}>" + end + + private + + def files(file_path) + mime_type = Marcel::MimeType.for Pathname.new(file_path) + Faraday::UploadIO.new(file_path, mime_type) + end + + def default_params + { + strategy: "fast", + hi_res_model_name: "yolox", + pdf_infer_table_structure: true, + chunking_strategy: "by_title" + } + end + + def handle_response(response) + message = response + case response.status + when 401 + raise Error, message + when 404 + raise Error, message + when 422 + raise Error, message + when 500 + raise Error, message + when 200..299 + response.body + else + raise Error, message + end + end + end +end diff --git a/lib/unstructured/collection.rb b/lib/unstructured/collection.rb new file mode 100644 index 0000000..c754407 --- /dev/null +++ b/lib/unstructured/collection.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +module Unstructured + class Collection + include Enumerable + + attr_reader :data, :total + + def self.from_response(response) + new( + data: response.map { |attrs| type.new(attrs) }, + raw_data: response, + total: response.length + ) + end + + def initialize(data:, raw_data:, total:) + @data = data + @raw_data = raw_data + @total = total + end + + def to_h + @raw_data + end + + def each(&block) + return to_enum(__method__) { @data.size } unless block_given? + + @data.each(&block) + end + + def self.type + raise NotImplementedError + end + end +end diff --git a/lib/unstructured/error.rb b/lib/unstructured/error.rb new file mode 100644 index 0000000..12292c0 --- /dev/null +++ b/lib/unstructured/error.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module Unstructured + class Error < StandardError; end +end diff --git a/lib/unstructured/object.rb b/lib/unstructured/object.rb new file mode 100644 index 0000000..10ec5dc --- /dev/null +++ b/lib/unstructured/object.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +require "ostruct" +module Unstructured + class Object + def initialize(attributes) + @attributes = OpenStruct.new(attributes) + end + + def method_missing(method, *args, &block) + method = method.to_s + attribute = @attributes.send(method, *args, &block) + attribute.is_a?(Hash) ? Object.new(attribute) : attribute + end + + def respond_to_missing?(_method, _include_private = false) + true + end + end +end diff --git a/lib/unstructured/objects/chunk.rb b/lib/unstructured/objects/chunk.rb new file mode 100644 index 0000000..0cd4e34 --- /dev/null +++ b/lib/unstructured/objects/chunk.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +module Unstructured + class Chunk < Object + def self.from_response(response) + new(response) + end + end +end diff --git a/lib/unstructured/version.rb b/lib/unstructured/version.rb new file mode 100644 index 0000000..97aa3e2 --- /dev/null +++ b/lib/unstructured/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +module Unstructured + VERSION = "0.1.0" +end diff --git a/sig/unstructured.rbs b/sig/unstructured.rbs new file mode 100644 index 0000000..fbca755 --- /dev/null +++ b/sig/unstructured.rbs @@ -0,0 +1,4 @@ +module Unstructured + VERSION: String + # See the writing guide of rbs: https://github.com/ruby/rbs#guides +end diff --git a/spec/client_spec.rb b/spec/client_spec.rb new file mode 100644 index 0000000..8ce6f3c --- /dev/null +++ b/spec/client_spec.rb @@ -0,0 +1,49 @@ +# frozen_string_literal: true + +RSpec.describe Unstructured::Client do + let(:server_url) { "https://api.unstructured.io" } + let(:client) { described_class.new(server_url: server_url, api_key_auth: "1234") } + + describe "#partition document" do + before do + stub_request(:post, "#{server_url}/general/v0/general") + .to_return( + status: 200, + body: [ + { + type: "CompositeElement", + element_id: "5db5a93436150acc50a8f9187f44f32d", + text: stub_text, + metadata: { + languages: [ + "eng" + ], + page_number: stub_page_number, + orig_elements: "5db5a93436150acc50a8f9187f44f32d", + filename: stub_filename, + filetype: stub_filetype + } + } + ], + headers: {} + ) + end + let(:stub_text) { "Text content" } + let(:stub_page_number) { 3 } + let(:stub_element_id) { "5db5a93436150acc50a8f9187f44f32d" } + let(:stub_filetype) { "application/pdf" } + let(:stub_filename) { "test.pdf" } + + it "should partition the document" do + expect(client.partition("spec/fixtures/sample.pdf")).to be_a(Unstructured::ChunkCollection) + end + + it "should have chunk properties" do + expect(client.partition("spec/fixtures/sample.pdf").first.text).to eq(stub_text) + expect(client.partition("spec/fixtures/sample.pdf").first.element_id).to eq(stub_element_id) + expect(client.partition("spec/fixtures/sample.pdf").first.metadata.page_number).to eq(stub_page_number) + expect(client.partition("spec/fixtures/sample.pdf").first.metadata.filetype).to eq(stub_filetype) + expect(client.partition("spec/fixtures/sample.pdf").first.metadata.filename).to eq(stub_filename) + end + end +end diff --git a/spec/fixtures/sample.pdf b/spec/fixtures/sample.pdf new file mode 100644 index 0000000..34f8324 Binary files /dev/null and b/spec/fixtures/sample.pdf differ diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000..7e36e14 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,18 @@ +# frozen_string_literal: true + +require "unstructured" +require "webmock/rspec" + +RSpec.configure do |config| + # Enable flags like --only-failures and --next-failure + config.example_status_persistence_file_path = ".rspec_status" + + # Disable RSpec exposing methods globally on `Module` and `main` + config.disable_monkey_patching! + + config.expect_with :rspec do |c| + c.syntax = :expect + end + + WebMock.disable_net_connect!(allow_localhost: false) +end diff --git a/spec/unstructured_spec.rb b/spec/unstructured_spec.rb new file mode 100644 index 0000000..033a675 --- /dev/null +++ b/spec/unstructured_spec.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +RSpec.describe Unstructured do + it "has a version number" do + expect(Unstructured::VERSION).not_to be nil + end + + it "should have a client" do + client = Unstructured::Client.new(server_url: "http://localhost:8000", api_key_auth: "1234") + expect(client).to be_a(Unstructured::Client) + end +end diff --git a/unstructured.gemspec b/unstructured.gemspec new file mode 100644 index 0000000..1efbc72 --- /dev/null +++ b/unstructured.gemspec @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +require_relative "lib/unstructured/version" + +Gem::Specification.new do |spec| + spec.name = "unstructured" + spec.version = Unstructured::VERSION + spec.authors = ["Jose Fernando Davila"] + spec.email = ["davila.jose23@gmail.com"] + + spec.summary = "Unstructured API wrapper." + spec.description = "Unstructured API wrapper. This gem allows you to interact with the Unstructured API." + spec.homepage = "https://github.com/TelosLabs/unstructured" + spec.license = "MIT" + spec.required_ruby_version = ">= 3.0.0" + + # spec.metadata["allowed_push_host"] = "TODO: Set to your gem server 'https://example.com'" + + spec.metadata["homepage_uri"] = spec.homepage + spec.metadata["source_code_uri"] = spec.homepage + spec.metadata["changelog_uri"] = spec.homepage + + # Specify which files should be added to the gem when it is released. + # The `git ls-files -z` loads the files in the RubyGem that have been added into git. + gemspec = File.basename(__FILE__) + spec.files = IO.popen(%w[git ls-files -z], chdir: __dir__, err: IO::NULL) do |ls| + ls.readlines("\x0", chomp: true).reject do |f| + (f == gemspec) || + f.start_with?(*%w[bin/ test/ spec/ features/ .git .github appveyor Gemfile]) + end + end + spec.bindir = "exe" + spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } + spec.require_paths = ["lib"] + + # Uncomment to register a new dependency of your gem + # spec.add_dependency "example-gem", "~> 1.0" + spec.add_dependency "faraday", "~> 2.9.0" + spec.add_dependency "faraday-multipart", "~> 1.0.4" + spec.add_dependency "marcel", "~> 1.0.4" + spec.add_dependency "webmock", "~> 3.23.0" + # spec.add_dependency "pry", "~> 0.14.2" + + # For more information and examples about making a new gem, check out our + # guide at: https://bundler.io/guides/creating_gem.html +end