Class: Ocrb::Extractors::OpenAi
- Inherits:
-
Object
- Object
- Ocrb::Extractors::OpenAi
- Defined in:
- lib/ocrb.rb
Instance Method Summary collapse
- #extract(image_path, prompt) ⇒ Object
-
#initialize(url: 'http://127.0.0.1:1234/v1', model: 'zai-org/glm-4.6v-flash', api_key: 'asdf', json: false) ⇒ OpenAi
constructor
A new instance of OpenAi.
Constructor Details
#initialize(url: 'http://127.0.0.1:1234/v1', model: 'zai-org/glm-4.6v-flash', api_key: 'asdf', json: false) ⇒ OpenAi
Returns a new instance of OpenAi.
23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/ocrb.rb', line 23 def initialize( # url: 'http://localhost:11434/v1', # model: 'glm-ocr:bf16', url: 'http://127.0.0.1:1234/v1', model: 'zai-org/glm-4.6v-flash', api_key: 'asdf', json: false ) @uri = URI(File.join(url, 'chat/completions')) @api_key = api_key @model = model @json = json end |
Instance Method Details
#extract(image_path, prompt) ⇒ Object
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 |
# File 'lib/ocrb.rb', line 37 def extract(image_path, prompt) req_body = { model: @model, messages: [ { role: 'user', content: [ { type: 'text', text: prompt }, { type: 'image_url', image_url: { url: image_data_url(image_path) } } ] } ] } req_body.merge!(response_format) request = Net::HTTP::Post.new(@uri) request['Authorization'] = "Bearer #{@api_key}" request['Content-Type'] = 'application/json' request.body = JSON.generate(req_body) response = Net::HTTP.start(@uri.host, @uri.port, use_ssl: false) do |http| http.request(request) end payload = JSON.parse(response.body) unless response.is_a?(Net::HTTPSuccess) = response.body raise "OpenAI OCR failed: #{}" end payload.dig('choices', 0, 'message', 'content').to_s end |