sema-unstructured 0.1.0
Extract structured document elements from PDFs, images, and Office files via the Unstructured.io API
package.sema
156 lines
a7b629e3555d
File details
Source stored with sema-unstructured 0.1.0. Line links refer to these exact bytes.
SHA-256 a7b629e3555d9739ec99f678d613d8fe7223fc293e30fc61a49f90329b56671a
1;; sema-unstructured — Unstructured.io document partitioning client2;;3;; A client is a plain map built by (unstructured/client ...) and passed as the4;; first argument to every call. The core operation, (unstructured/partition ...),5;; uploads a document (PDF, image, DOCX, HTML, ...) as a multipart form and6;; returns the API's JSON array of element maps — each a paragraph, title, table,7;; or list item with its text and metadata. Non-2xx statuses raise an error8;; carrying the method, path, status, and the API's own message.9;; (unstructured/request ...) is the raw escape hatch every wrapper is built on.1011(module sema-unstructured12(export unstructured/client13unstructured/request14unstructured/partition15unstructured/text-of)1617;; -------------------------------------------------------------------------18;; Private: value coercion for multipart form fields19;; -------------------------------------------------------------------------2021(define (key->string k)22(cond23((keyword? k) (keyword/to-string k))24((string? k) k)25(#t (str k))))2627;; Form fields are always strings; booleans become "true"/"false" (not "#t").28(define (val->form-string v)29(cond30((string? v) v)31((equal? v #t) "true")32((equal? v #f) "false")33(#t (str v))))3435;; Last path segment of a filesystem path ("docs/paper.pdf" → "paper.pdf").36(define (basename path)37(let ((seg (last (string/split path "/"))))38(if (or (nil? seg) (string/empty? seg)) path seg)))3940;; One string form part: {:name .. :content ..}.41(define (string-part name value)42{:name name :content (val->form-string value)})4344;; -------------------------------------------------------------------------45;; Client46;; -------------------------------------------------------------------------4748(define (unstructured/client . opts)49"Build an Unstructured client map. Options: :api-key (default: UNSTRUCTURED_API_KEY env var), :base-url (default \"https://api.unstructuredapp.io\"), :timeout in ms (default 120000). Errors if no API key is found."50(let* ((o (if (null? opts) {} (first opts)))51(api-key (or (get o :api-key) (env "UNSTRUCTURED_API_KEY"))))52(when (nil? api-key)53(error "unstructured: no API key — pass {:api-key \"...\"} or set the UNSTRUCTURED_API_KEY environment variable"))54{:api-key api-key55:base-url (string/chop-end (get o :base-url "https://api.unstructuredapp.io") "/")56:timeout (get o :timeout 120000)}))5758;; -------------------------------------------------------------------------59;; Private: request plumbing60;; -------------------------------------------------------------------------6162(define (client-headers client)63{"unstructured-api-key" (:api-key client)64"accept" "application/json"})6566(define (build-url client path)67(if (string/starts-with? path "http")68path69(string-append (:base-url client) (string/ensure-start path "/"))))7071;; Best error message we can pull from a failed response body. The API returns72;; JSON with a :detail (sometimes :message) field on errors.73(define (api-error-message body)74(let ((decoded (try (json/decode body) (catch e nil))))75(cond76((and (map? decoded) (contains? decoded :detail))77(let ((d (get decoded :detail))) (if (string? d) d (str d))))78((and (map? decoded) (contains? decoded :message)) (get decoded :message))79((and (string? body) (> (string-length (string/trim body)) 0))80(string/take (string/trim body) 200))81(#t "unknown error"))))8283(define (decode-body body)84(if (or (nil? body) (string/empty? (string/trim body)))85nil86(json/decode body)))8788(define (unstructured/request client method path opts)89"Make a raw Unstructured API request; the escape hatch every wrapper uses. method is \"GET\"/\"POST\"/..., path an API path (\"/general/v0/general\") or full URL. opts is a map: :multipart (list of {:name .. :content <string|bytevector> :filename ..?} parts) for form uploads, :body (map → JSON body) otherwise. Returns the decoded JSON body (nil when empty); raises on non-2xx with method, path, status, and the API message."90(let* ((url (build-url client path))91(multipart (get opts :multipart))92(base-opts {:headers (client-headers client) :timeout (:timeout client)})93(req-opts (if (nil? multipart) base-opts (assoc base-opts :multipart multipart)))94(body (get opts :body))95(resp (if (nil? body)96(http/request method url req-opts)97(http/request method url req-opts body)))98(status (:status resp)))99(if (and (>= status 200) (< status 300))100(decode-body (:body resp))101(error (format "unstructured: ~a ~a → ~a: ~a"102method path status (api-error-message (:body resp)))))))103104;; -------------------------------------------------------------------------105;; Partition106;; -------------------------------------------------------------------------107108;; Resolve a source into {:bytes bv :filename str}. A string is a filesystem109;; path (read now); a map must already carry :bytes and :filename.110(define (resolve-source source)111(cond112((string? source)113{:bytes (file/read-bytes source) :filename (basename source)})114((and (map? source) (contains? source :bytes) (contains? source :filename))115{:bytes (get source :bytes) :filename (get source :filename)})116(#t117(error "unstructured/partition: source must be a file path string or a {:bytes <bytevector> :filename \"...\"} map — got something else"))))118119;; Build the multipart part list: the file, then any string form fields.120(define (partition-parts resolved o)121(let* ((file-part {:name "files"122:content (get resolved :bytes)123:filename (get resolved :filename)})124(with-strategy125(if (nil? (get o :strategy))126(list)127(list (string-part "strategy" (get o :strategy)))))128(with-chunking129(if (nil? (get o :chunking-strategy))130(list)131(list (string-part "chunking_strategy" (get o :chunking-strategy)))))132(extra (get o :params {}))133(extra-parts134(map (fn (k) (string-part (key->string k) (get extra k)))135(keys extra))))136(append (list file-part) with-strategy with-chunking extra-parts)))137138(define (unstructured/partition client source . opts)139"Partition a document into element maps via POST /general/v0/general. source is either a file path string or a {:bytes <bytevector> :filename \"name.ext\"} map (bytes are uploaded verbatim). Options map: :strategy (e.g. \"auto\", \"hi_res\", \"fast\", \"ocr_only\", \"vlm\"; omitted → API default), :chunking-strategy (e.g. \"by_title\", \"basic\"; omitted → no chunking), :params (map of any other form fields, keyword or string keys, e.g. {:languages \"eng\" :coordinates #t}). Returns a list of element maps ({:type .. :element_id .. :text .. :metadata ..})."140(let* ((o (if (null? opts) {} (first opts)))141(resolved (resolve-source source))142(parts (partition-parts resolved o)))143(unstructured/request client "POST" "/general/v0/general" {:multipart parts})))144145;; -------------------------------------------------------------------------146;; Helpers over partition results (pure)147;; -------------------------------------------------------------------------148149(define (unstructured/text-of elements)150"Join the :text of a partition element list into a single newline-separated string. Elements missing :text contribute nothing. Accepts nil or an empty list (→ \"\")."151(if (or (nil? elements) (empty? elements))152""153(string/join154(filter (fn (s) (not (string/empty? s)))155(map (fn (el) (or (and (map? el) (get el :text)) "")) elements))156"\n"))))