Spaces:
Running
Running
Download examples/pdf-parser/src/main/java/demo/App.java from dellweb3/VibeCoding: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/spaces/dellweb3/VibeCoding/resolve/5fd201e23196b2a29b0a700894e1f6ea65b69fba/examples/pdf-parser/src/main/java/demo/App.java
- Command line
-
hf download hf://spaces/dellweb3/VibeCoding@5fd201e23196b2a29b0a700894e1f6ea65b69fba/examples/pdf-parser/src/main/java/demo/App.java
-
curl -L -o App.java https://huggingface.co/spaces/dellweb3/VibeCoding/resolve/5fd201e23196b2a29b0a700894e1f6ea65b69fba/examples/pdf-parser/src/main/java/demo/App.java
10.3 kB
| package demo; | |
| import com.sun.net.httpserver.HttpServer; | |
| import com.sun.net.httpserver.HttpExchange; | |
| import org.apache.pdfbox.Loader; | |
| import org.apache.pdfbox.pdmodel.PDDocument; | |
| import org.apache.pdfbox.text.PDFTextStripper; | |
| import java.io.*; | |
| import java.net.InetSocketAddress; | |
| import java.nio.charset.CharsetDecoder; | |
| import java.nio.charset.CodingErrorAction; | |
| import java.nio.charset.StandardCharsets; | |
| import java.nio.ByteBuffer; | |
| import java.util.Base64; | |
| public class App { | |
| public static void main(String[] args) throws Exception { | |
| HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); | |
| server.createContext("/health", App::handleHealth); | |
| server.createContext("/api/pdf/analyze", App::handleAnalyze); | |
| server.createContext("/", App::handleDefault); | |
| server.start(); | |
| } | |
| static void handleDefault(HttpExchange ex) throws IOException { | |
| sendJson(ex, 404, "{\"error\":\"NOT_FOUND\"}"); | |
| } | |
| static void handleHealth(HttpExchange ex) throws IOException { | |
| if (!"GET".equals(ex.getRequestMethod())) { | |
| sendJson(ex, 405, "{\"error\":\"METHOD_NOT_ALLOWED\"}"); | |
| return; | |
| } | |
| sendJson(ex, 200, "{\"status\":\"ok\"}"); | |
| } | |
| static void handleAnalyze(HttpExchange ex) throws IOException { | |
| if (!"POST".equals(ex.getRequestMethod())) { | |
| sendJson(ex, 405, "{\"error\":\"METHOD_NOT_ALLOWED\"}"); | |
| return; | |
| } | |
| String auth = ex.getRequestHeaders().getFirst("Authorization"); | |
| if (auth == null || !auth.equals("Bearer demo-pdf")) { | |
| sendJson(ex, 401, "{\"error\":\"UNAUTHORIZED\"}"); | |
| return; | |
| } | |
| String ct = ex.getRequestHeaders().getFirst("Content-Type"); | |
| if (ct == null || !ct.startsWith("application/json")) { | |
| sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}"); | |
| return; | |
| } | |
| if (ex.getRequestURI().getQuery() != null) { | |
| sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}"); | |
| return; | |
| } | |
| byte[] body; | |
| try (InputStream is = ex.getRequestBody(); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { | |
| byte[] buf = new byte[8192]; | |
| int n, total = 0; | |
| while ((n = is.read(buf)) != -1) { | |
| total += n; | |
| if (total > 180001) break; | |
| baos.write(buf, 0, n); | |
| } | |
| body = baos.toByteArray(); | |
| } | |
| if (body.length > 180000) { | |
| sendJson(ex, 413, "{\"error\":\"PDF_TOO_LARGE\"}"); | |
| return; | |
| } | |
| CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT); | |
| String json; | |
| try { | |
| json = decoder.decode(ByteBuffer.wrap(body)).toString(); | |
| } catch (Exception e) { | |
| sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}"); | |
| return; | |
| } | |
| String b64 = parseBase64Field(json); | |
| if (b64 == null) { | |
| sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}"); | |
| return; | |
| } | |
| if (b64.isEmpty()) { | |
| sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}"); | |
| return; | |
| } | |
| byte[] pdfBytes; | |
| try { | |
| pdfBytes = Base64.getDecoder().decode(b64); | |
| } catch (Exception e) { | |
| sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}"); | |
| return; | |
| } | |
| if (!isCanonicalBase64(b64, pdfBytes)) { | |
| sendJson(ex, 400, "{\"error\":\"INVALID_INPUT\"}"); | |
| return; | |
| } | |
| if (pdfBytes.length > 131072) { | |
| sendJson(ex, 413, "{\"error\":\"PDF_TOO_LARGE\"}"); | |
| return; | |
| } | |
| if (pdfBytes.length < 5 || pdfBytes[0] != '%' || pdfBytes[1] != 'P' || pdfBytes[2] != 'D' || pdfBytes[3] != 'F' || pdfBytes[4] != '-') { | |
| sendJson(ex, 400, "{\"error\":\"INVALID_PDF\"}"); | |
| return; | |
| } | |
| PDDocument doc; | |
| try { | |
| doc = Loader.loadPDF(pdfBytes); | |
| } catch (org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException e) { | |
| sendJson(ex, 422, "{\"error\":\"ENCRYPTED_PDF\"}"); | |
| return; | |
| } catch (Exception e) { | |
| sendJson(ex, 400, "{\"error\":\"INVALID_PDF\"}"); | |
| return; | |
| } | |
| try (doc) { | |
| if (doc.isEncrypted()) { | |
| sendJson(ex, 422, "{\"error\":\"ENCRYPTED_PDF\"}"); | |
| return; | |
| } | |
| int pages = doc.getNumberOfPages(); | |
| if (pages == 0) { | |
| sendJson(ex, 400, "{\"error\":\"INVALID_PDF\"}"); | |
| return; | |
| } | |
| if (pages > 20) { | |
| sendJson(ex, 422, "{\"error\":\"PAGE_LIMIT\"}"); | |
| return; | |
| } | |
| PDFTextStripper stripper = new PDFTextStripper(); | |
| stripper.setSortByPosition(true); | |
| StringBuilder sb = new StringBuilder(); | |
| sb.append("{\"pageCount\":").append(pages).append(",\"pages\":["); | |
| int totalChars = 0; | |
| int utf8Total = 0; | |
| boolean hasText = false; | |
| for (int i = 1; i <= pages; i++) { | |
| stripper.setStartPage(i); | |
| stripper.setEndPage(i); | |
| String text = stripper.getText(doc); | |
| text = text.replace("\r\n", "\n").replace("\r", "\n"); | |
| text = text.strip(); | |
| if (!text.isEmpty()) hasText = true; | |
| totalChars += text.codePointCount(0, text.length()); | |
| utf8Total += text.getBytes(StandardCharsets.UTF_8).length; | |
| if (utf8Total > 24000) { | |
| sendJson(ex, 413, "{\"error\":\"TEXT_LIMIT\"}"); | |
| return; | |
| } | |
| if (i > 1) sb.append(","); | |
| sb.append("{\"page\":").append(i).append(",\"text\":\"").append(escapeJson(text)).append("\"}"); | |
| } | |
| sb.append("],\"totalCharacters\":").append(totalChars); | |
| sb.append(",\"status\":\"").append(hasText ? "TEXT_EXTRACTED" : "NO_TEXT").append("\"}"); | |
| String resp = sb.toString(); | |
| if (resp.getBytes(StandardCharsets.UTF_8).length > 60000) { | |
| sendJson(ex, 413, "{\"error\":\"TEXT_LIMIT\"}"); | |
| return; | |
| } | |
| sendJson(ex, 200, resp); | |
| } | |
| } | |
| static boolean isCanonicalBase64(String b64, byte[] decoded) { | |
| if (b64.isEmpty() && decoded.length == 0) return true; | |
| String reencoded = Base64.getEncoder().encodeToString(decoded); | |
| return reencoded.equals(b64); | |
| } | |
| static String escapeJson(String s) { | |
| StringBuilder sb = new StringBuilder(s.length()); | |
| for (int i = 0; i < s.length(); i++) { | |
| char c = s.charAt(i); | |
| switch (c) { | |
| case '"': sb.append("\\\""); break; | |
| case '\\': sb.append("\\\\"); break; | |
| case '\n': sb.append("\\n"); break; | |
| case '\r': sb.append("\\r"); break; | |
| case '\t': sb.append("\\t"); break; | |
| case '\b': sb.append("\\b"); break; | |
| case '\f': sb.append("\\f"); break; | |
| default: | |
| if (c < 0x20) { | |
| sb.append(String.format("\\u%04x", (int) c)); | |
| } else { | |
| sb.append(c); | |
| } | |
| } | |
| } | |
| return sb.toString(); | |
| } | |
| static String parseBase64Field(String json) { | |
| int idx = 0; | |
| idx = skipWs(json, idx); | |
| if (idx >= json.length() || json.charAt(idx) != '{') return null; | |
| idx++; | |
| idx = skipWs(json, idx); | |
| if (idx >= json.length() || json.charAt(idx) == '}') return null; | |
| int keyCount = 0; | |
| String value = null; | |
| while (idx < json.length()) { | |
| idx = skipWs(json, idx); | |
| if (idx >= json.length() || json.charAt(idx) != '"') return null; | |
| int keyStart = idx + 1; | |
| int keyEnd = findClosingQuote(json, keyStart); | |
| if (keyEnd < 0) return null; | |
| String key = json.substring(keyStart, keyEnd); | |
| idx = keyEnd + 1; | |
| idx = skipWs(json, idx); | |
| if (idx >= json.length() || json.charAt(idx) != ':') return null; | |
| idx++; | |
| idx = skipWs(json, idx); | |
| if (idx >= json.length() || json.charAt(idx) != '"') return null; | |
| int valStart = idx + 1; | |
| int valEnd = findClosingQuote(json, valStart); | |
| if (valEnd < 0) return null; | |
| String val = json.substring(valStart, valEnd); | |
| idx = valEnd + 1; | |
| keyCount++; | |
| if (keyCount > 1) return null; | |
| if (!"base64".equals(key)) return null; | |
| value = val; | |
| idx = skipWs(json, idx); | |
| if (idx < json.length() && json.charAt(idx) == ',') { | |
| idx++; | |
| idx = skipWs(json, idx); | |
| if (idx < json.length() && json.charAt(idx) == '}') return null; | |
| continue; | |
| } | |
| break; | |
| } | |
| idx = skipWs(json, idx); | |
| if (idx >= json.length() || json.charAt(idx) != '}') return null; | |
| idx++; | |
| idx = skipWs(json, idx); | |
| if (idx != json.length()) return null; | |
| return value; | |
| } | |
| static int findClosingQuote(String s, int from) { | |
| for (int i = from; i < s.length(); i++) { | |
| char c = s.charAt(i); | |
| if (c == '\\') { i++; continue; } | |
| if (c == '"') return i; | |
| } | |
| return -1; | |
| } | |
| static int skipWs(String s, int i) { | |
| while (i < s.length() && (s.charAt(i) == ' ' || s.charAt(i) == '\t' || s.charAt(i) == '\n' || s.charAt(i) == '\r')) i++; | |
| return i; | |
| } | |
| static void sendJson(HttpExchange ex, int code, String body) throws IOException { | |
| byte[] bytes = body.getBytes(StandardCharsets.UTF_8); | |
| ex.getResponseHeaders().set("Content-Type", "application/json"); | |
| ex.sendResponseHeaders(code, bytes.length); | |
| try (OutputStream os = ex.getResponseBody()) { | |
| os.write(bytes); | |
| } | |
| } | |
| } |