sema-unstructured 0.1.0

Extract structured document elements from PDFs, images, and Office files via the Unstructured.io API

Source

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 client
2;;
3;; A client is a plain map built by (unstructured/client ...) and passed as the
4;; first argument to every call. The core operation, (unstructured/partition ...),
5;; uploads a document (PDF, image, DOCX, HTML, ...) as a multipart form and
6;; 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 error
8;; carrying the method, path, status, and the API's own message.
9;; (unstructured/request ...) is the raw escape hatch every wrapper is built on.
10
11(module sema-unstructured
12  (export unstructured/client
13          unstructured/request
14          unstructured/partition
15          unstructured/text-of)
16
17  ;; -------------------------------------------------------------------------
18  ;; Private: value coercion for multipart form fields
19  ;; -------------------------------------------------------------------------
20
21  (define (key->string k)
22    (cond
23      ((keyword? k) (keyword/to-string k))
24      ((string? k) k)
25      (#t (str k))))
26
27  ;; Form fields are always strings; booleans become "true"/"false" (not "#t").
28  (define (val->form-string v)
29    (cond
30      ((string? v) v)
31      ((equal? v #t) "true")
32      ((equal? v #f) "false")
33      (#t (str v))))
34
35  ;; 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)))
39
40  ;; One string form part: {:name .. :content ..}.
41  (define (string-part name value)
42    {:name name :content (val->form-string value)})
43
44  ;; -------------------------------------------------------------------------
45  ;; Client
46  ;; -------------------------------------------------------------------------
47
48  (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-key
55       :base-url (string/chop-end (get o :base-url "https://api.unstructuredapp.io") "/")
56       :timeout (get o :timeout 120000)}))
57
58  ;; -------------------------------------------------------------------------
59  ;; Private: request plumbing
60  ;; -------------------------------------------------------------------------
61
62  (define (client-headers client)
63    {"unstructured-api-key" (:api-key client)
64     "accept" "application/json"})
65
66  (define (build-url client path)
67    (if (string/starts-with? path "http")
68      path
69      (string-append (:base-url client) (string/ensure-start path "/"))))
70
71  ;; Best error message we can pull from a failed response body. The API returns
72  ;; 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      (cond
76        ((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"))))
82
83  (define (decode-body body)
84    (if (or (nil? body) (string/empty? (string/trim body)))
85      nil
86      (json/decode body)))
87
88  (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"
102                       method path status (api-error-message (:body resp)))))))
103
104  ;; -------------------------------------------------------------------------
105  ;; Partition
106  ;; -------------------------------------------------------------------------
107
108  ;; Resolve a source into {:bytes bv :filename str}. A string is a filesystem
109  ;; path (read now); a map must already carry :bytes and :filename.
110  (define (resolve-source source)
111    (cond
112      ((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      (#t
117       (error "unstructured/partition: source must be a file path string or a {:bytes <bytevector> :filename \"...\"} map — got something else"))))
118
119  ;; 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-strategy
125             (if (nil? (get o :strategy))
126               (list)
127               (list (string-part "strategy" (get o :strategy)))))
128           (with-chunking
129             (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-parts
134             (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)))
137
138  (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})))
144
145  ;; -------------------------------------------------------------------------
146  ;; Helpers over partition results (pure)
147  ;; -------------------------------------------------------------------------
148
149  (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/join
154        (filter (fn (s) (not (string/empty? s)))
155                (map (fn (el) (or (and (map? el) (get el :text)) "")) elements))
156        "\n"))))