This is an automated email from the ASF dual-hosted git repository. davsclaus pushed a commit to branch CAMEL-27671-huggingface-handler-values in repository https://gitbox.apache.org/repos/asf/camel.git
commit f25db414d17876f628dcff85f500ba82f474316f Author: Claus Ibsen <[email protected]> AuthorDate: Fri Nov 27 16:27:18 2026 +0100 CAMEL-27671: camel-huggingface - the generated Python handler holds the auth token and unescaped option values The modelId, revision and device values are now written into the generated handler as escaped Python string literals, and the script is formatted with Locale.ROOT so the temperature has a dot in every locale. The auth token is no longer written into handler.py: it is given to the Python process as the HF_TOKEN environment variable through the env option of the DJL Python engine. The temporary model directory is also removed when the model fails to load. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Claus Ibsen <[email protected]> --- .../camel/catalog/docs/huggingface-component.adoc | 9 + .../src/main/docs/huggingface-component.adoc | 9 + .../huggingface/tasks/AbstractTaskPredictor.java | 156 +++++++++++++----- .../tasks/AutomaticSpeechRecognitionPredictor.java | 5 +- .../component/huggingface/tasks/ChatPredictor.java | 7 +- .../tasks/QuestionAnsweringPredictor.java | 3 +- .../tasks/SentenceEmbeddingsPredictor.java | 3 +- .../huggingface/tasks/SummarizationPredictor.java | 3 +- .../tasks/TextClassificationPredictor.java | 3 +- .../huggingface/tasks/TextGenerationPredictor.java | 3 +- .../huggingface/tasks/TextToImagePredictor.java | 3 +- .../huggingface/tasks/TextToSpeechPredictor.java | 3 +- .../tasks/ZeroShotClassificationPredictor.java | 5 +- .../tasks/automatic_speech_recognition.py | 6 +- .../camel/component/huggingface/tasks/chat.py | 2 +- .../huggingface/tasks/question_answering.py | 6 +- .../huggingface/tasks/sentence_embeddings.py | 4 +- .../component/huggingface/tasks/summarization.py | 6 +- .../huggingface/tasks/text_classification.py | 6 +- .../component/huggingface/tasks/text_generation.py | 6 +- .../component/huggingface/tasks/text_to_image.py | 6 +- .../component/huggingface/tasks/text_to_speech.py | 6 +- .../huggingface/tasks/zero_shot_classification.py | 6 +- .../huggingface/tasks/AuthTokenInjectionTest.java | 69 ++++++-- .../huggingface/tasks/HandlerValuesTest.java | 182 +++++++++++++++++++++ .../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 8 + 26 files changed, 424 insertions(+), 101 deletions(-) diff --git a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/huggingface-component.adoc b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/huggingface-component.adoc index ef3e1097b7b0..847ce9e50d8f 100644 --- a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/huggingface-component.adoc +++ b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/huggingface-component.adoc @@ -131,6 +131,15 @@ include::partial$component-endpoint-headers.adoc[] // endpoint options: START // endpoint options: END +== Authentication + +To download gated or private models, set the `authToken` option to a Hugging Face user access token. + +The producer writes a Python handler for the task into a temporary directory, which only the user that runs Camel can +read, and runs it with the DJL Python engine. The directory is removed when the producer stops. The `authToken` is not +written into the handler: it is given to the Python process as the `HF_TOKEN` environment variable. The token must not +contain a comma. + == OAuth Authentication When accessing private or gated models behind an OAuth-protected endpoint, set the `oauthProfile` parameter to acquire an access token via the OAuth 2.0 Client Credentials grant. The token is used as the `authToken`. This requires `camel-oauth` on the classpath. diff --git a/components/camel-ai/camel-huggingface/src/main/docs/huggingface-component.adoc b/components/camel-ai/camel-huggingface/src/main/docs/huggingface-component.adoc index ef3e1097b7b0..847ce9e50d8f 100644 --- a/components/camel-ai/camel-huggingface/src/main/docs/huggingface-component.adoc +++ b/components/camel-ai/camel-huggingface/src/main/docs/huggingface-component.adoc @@ -131,6 +131,15 @@ include::partial$component-endpoint-headers.adoc[] // endpoint options: START // endpoint options: END +== Authentication + +To download gated or private models, set the `authToken` option to a Hugging Face user access token. + +The producer writes a Python handler for the task into a temporary directory, which only the user that runs Camel can +read, and runs it with the DJL Python engine. The directory is removed when the producer stops. The `authToken` is not +written into the handler: it is given to the Python process as the `HF_TOKEN` environment variable. The token must not +contain a comma. + == OAuth Authentication When accessing private or gated models behind an OAuth-protected endpoint, set the `oauthProfile` parameter to acquire an access token via the OAuth 2.0 Client Credentials grant. The token is used as the `authToken`. This requires `camel-oauth` on the classpath. diff --git a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/AbstractTaskPredictor.java b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/AbstractTaskPredictor.java index ddd793d01b34..e788de0f0fcc 100644 --- a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/AbstractTaskPredictor.java +++ b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/AbstractTaskPredictor.java @@ -27,6 +27,9 @@ import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; import java.util.concurrent.locks.ReentrantLock; import ai.djl.inference.Predictor; @@ -71,42 +74,81 @@ public abstract class AbstractTaskPredictor implements TaskPredictor { @Override public void loadModel() throws Exception { + tmpDir = createModelDir(); + try { + Path reqPath = writeModelFiles(tmpDir); + String modelUrl = "file://" + tmpDir.toAbsolutePath(); + Criteria.Builder<Input, Output> criteriaBuilder = Criteria.builder() + .setTypes(Input.class, Output.class) + .optModelUrls(modelUrl) + .optEngine("Python"); + modelOptions(reqPath).forEach(criteriaBuilder::optOption); + Criteria<Input, Output> criteria = criteriaBuilder.build(); + model = criteria.loadModel(); + } catch (Exception e) { + try { + deleteModelDir(); + } catch (IOException ex) { + e.addSuppressed(ex); + } + throw e; + } + } + + private static Path createModelDir() throws IOException { if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) { - tmpDir = Files.createTempDirectory("hf_model", + return Files.createTempDirectory("hf_model", PosixFilePermissions.asFileAttribute( EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE))); - } else { - tmpDir = Files.createTempDirectory("hf_model"); } - Path handlerPath = tmpDir.resolve("handler.py"); + return Files.createTempDirectory("hf_model"); + } + + /** + * Writes the Python handler and its requirements into the model directory, and returns the path of the requirements + * file. The handler holds no secret: the token is given to the Python process as an environment variable, see + * {@link #modelOptions(Path)}. + */ + Path writeModelFiles(Path dir) throws IOException { String pythonScript = getPythonScript(); - // logged before the token is prepended: withAuthToken writes the configured token into the - // script, and this now runs for every task rather than only chat if (LOG.isDebugEnabled()) { LOG.debug("Generated Python script for task {}:\n{}", config.getTask(), pythonScript); } - Files.writeString(handlerPath, withAuthToken(pythonScript)); - Path reqPath = tmpDir.resolve("requirements.txt"); + Files.writeString(dir.resolve("handler.py"), pythonScript); + Path reqPath = dir.resolve("requirements.txt"); Files.writeString(reqPath, getRequirements()); - String modelUrl = "file://" + tmpDir.toAbsolutePath(); - Criteria.Builder<Input, Output> criteriaBuilder = Criteria.builder() - .setTypes(Input.class, Output.class) - .optModelUrls(modelUrl) - .optOption("handler", "handle") - .optEngine("Python") - .optOption("entryPoint", "handler.py") - .optOption("requirementsFile", reqPath.toString()); + return reqPath; + } + /** + * The options of the DJL Python engine. The Hugging Face token (the {@code authToken} option, or the token resolved + * from the OAuth profile) is given to the Python process as the {@code HF_TOKEN} environment variable, which + * {@code transformers} and {@code huggingface_hub} read when no explicit token is passed, so every task can load + * gated or private models. + */ + Map<String, String> modelOptions(Path reqPath) { + Map<String, String> options = new LinkedHashMap<>(); + options.put("handler", "handle"); + options.put("entryPoint", "handler.py"); + options.put("requirementsFile", reqPath.toString()); if (config.getModelLoadingTimeout() > 0) { - criteriaBuilder.optOption("model_loading_timeout", String.valueOf(config.getModelLoadingTimeout())); + options.put("model_loading_timeout", String.valueOf(config.getModelLoadingTimeout())); } if (config.getPredictTimeout() > 0) { - criteriaBuilder.optOption("predict_timeout", String.valueOf(config.getPredictTimeout())); + options.put("predict_timeout", String.valueOf(config.getPredictTimeout())); } - - Criteria<Input, Output> criteria = criteriaBuilder.build(); - model = criteria.loadModel(); + String authToken = config.getAuthToken(); + if (authToken != null && !authToken.isBlank()) { + authToken = authToken.strip(); + // the Python engine reads the env option as a comma separated list of name=value + if (authToken.indexOf(',') >= 0 || authToken.chars().anyMatch(Character::isISOControl)) { + throw new IllegalArgumentException( + "The authToken must not contain a comma or a control character"); + } + options.put("env", "HF_TOKEN=" + authToken); + } + return options; } @Override @@ -117,29 +159,14 @@ public abstract class AbstractTaskPredictor implements TaskPredictor { protected abstract String getPythonScript(); - /** - * Prepends the configured Hugging Face token to the generated handler as the {@code HF_TOKEN} environment variable - * so that every task can load gated or private models. {@code transformers.pipeline()} reads {@code HF_TOKEN} from - * the environment when no explicit token is passed; previously only the chat task passed a token, so the other - * tasks failed with 401 on gated models. The token comes from the {@code authToken} option or is resolved from an - * OAuth profile (see {@link org.apache.camel.component.huggingface.HuggingFaceProducer}), both surfaced through - * {@code config.getAuthToken()}. - */ - protected String withAuthToken(String pythonScript) { - String authToken = config.getAuthToken(); - if (authToken == null || authToken.isEmpty()) { - return pythonScript; - } - return "import os\nos.environ['HF_TOKEN'] = '" + authToken.replace("'", "\\'") + "'\n\n" + pythonScript; - } - protected String loadPythonScript(String resourcePath, Object... args) { InputStream is = null; try { String fullPath = "classpath:org/apache/camel/component/huggingface/tasks/" + resourcePath; is = ResourceHelper.resolveResourceAsInputStream(endpoint.getCamelContext(), fullPath); String script = IOHelper.loadText(is); - return script.formatted(args); + // Locale.ROOT, so a float is written with a dot in every locale + return String.format(Locale.ROOT, script, args); } catch (IOException e) { throw new RuntimeCamelException("Failed to load python script: " + resourcePath, e); } finally { @@ -147,6 +174,36 @@ public abstract class AbstractTaskPredictor implements TaskPredictor { } } + /** + * Returns the value as a Python string literal, to put into the generated handler: the backslash and the single + * quote are escaped, and every character that is not printable ASCII is written as an escape sequence, so the value + * cannot end the literal or the line. A {@code null} value is {@code None}. + */ + protected static String pythonString(String value) { + if (value == null) { + return "None"; + } + StringBuilder sb = new StringBuilder(value.length() + 2); + sb.append('\''); + value.codePoints().forEach(cp -> { + if (cp == '\\') { + sb.append("\\\\"); + } else if (cp == '\'') { + sb.append("\\'"); + } else if (cp >= 0x20 && cp < 0x7f) { + sb.append((char) cp); + } else if (cp <= 0xff) { + sb.append(String.format(Locale.ROOT, "\\x%02x", cp)); + } else if (cp <= 0xffff) { + sb.append(String.format(Locale.ROOT, "\\u%04x", cp)); + } else { + sb.append(String.format(Locale.ROOT, "\\U%08x", cp)); + } + }); + sb.append('\''); + return sb.toString(); + } + protected String getRequirements() { return """ transformers>=4.30.0 @@ -222,14 +279,23 @@ public abstract class AbstractTaskPredictor implements TaskPredictor { @Override public void close() throws Exception { - if (predictor != null) { - predictor.close(); - } - if (model != null) { - model.close(); + try { + if (predictor != null) { + predictor.close(); + } + if (model != null) { + model.close(); + } + } finally { + deleteModelDir(); } - if (tmpDir != null) { - Files.walkFileTree(tmpDir, new SimpleFileVisitor<>() { + } + + private void deleteModelDir() throws IOException { + Path modelDir = tmpDir; + tmpDir = null; + if (modelDir != null && Files.exists(modelDir)) { + Files.walkFileTree(modelDir, new SimpleFileVisitor<>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); diff --git a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/AutomaticSpeechRecognitionPredictor.java b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/AutomaticSpeechRecognitionPredictor.java index 7c0439d5fdb3..7c26fafd12e8 100644 --- a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/AutomaticSpeechRecognitionPredictor.java +++ b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/AutomaticSpeechRecognitionPredictor.java @@ -102,8 +102,9 @@ public class AutomaticSpeechRecognitionPredictor extends AbstractTaskPredictor { @Override protected String getPythonScript() { - return loadPythonScript("automatic_speech_recognition.py", config.getModelId(), config.getRevision(), - config.getDevice()); + return loadPythonScript("automatic_speech_recognition.py", pythonString(config.getModelId()), + pythonString(config.getRevision()), + pythonString(config.getDevice())); } @Override diff --git a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/ChatPredictor.java b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/ChatPredictor.java index a37d1c15f26d..8aa4a062fa35 100644 --- a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/ChatPredictor.java +++ b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/ChatPredictor.java @@ -136,9 +136,10 @@ public class ChatPredictor extends AbstractTaskPredictor { protected String getPythonScript() { String doSample = config.getTemperature() > 0 ? "True" : "False"; float temperature = config.getTemperature() > 0 ? config.getTemperature() : 1.0f; - // The token is applied centrally as the HF_TOKEN environment variable in - // AbstractTaskPredictor.withAuthToken, so no per-task token clause is needed here. - return loadPythonScript("chat.py", config.getModelId(), config.getRevision(), config.getDevice(), + // The token is given to the Python process as the HF_TOKEN environment variable by + // AbstractTaskPredictor.modelOptions, so no per-task token clause is needed here. + return loadPythonScript("chat.py", pythonString(config.getModelId()), pythonString(config.getRevision()), + pythonString(config.getDevice()), config.getMaxTokens(), doSample, temperature); } diff --git a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/QuestionAnsweringPredictor.java b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/QuestionAnsweringPredictor.java index 02afd48509c7..38091bf65c9b 100644 --- a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/QuestionAnsweringPredictor.java +++ b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/QuestionAnsweringPredictor.java @@ -90,7 +90,8 @@ public class QuestionAnsweringPredictor extends AbstractTaskPredictor { @Override protected String getPythonScript() { - return loadPythonScript("question_answering.py", config.getModelId(), config.getRevision(), config.getDevice()); + return loadPythonScript("question_answering.py", pythonString(config.getModelId()), pythonString(config.getRevision()), + pythonString(config.getDevice())); } @Override diff --git a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/SentenceEmbeddingsPredictor.java b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/SentenceEmbeddingsPredictor.java index b4ac072e86b1..2caeafc2f9f3 100644 --- a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/SentenceEmbeddingsPredictor.java +++ b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/SentenceEmbeddingsPredictor.java @@ -104,7 +104,8 @@ public class SentenceEmbeddingsPredictor extends AbstractTaskPredictor { @Override protected String getPythonScript() { - return loadPythonScript("sentence_embeddings.py", config.getDevice(), config.getModelId(), config.getRevision()); + return loadPythonScript("sentence_embeddings.py", pythonString(config.getDevice()), pythonString(config.getModelId()), + pythonString(config.getRevision())); } @Override diff --git a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/SummarizationPredictor.java b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/SummarizationPredictor.java index 5a7bc4e1b7c9..9003d84ffc1d 100644 --- a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/SummarizationPredictor.java +++ b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/SummarizationPredictor.java @@ -86,7 +86,8 @@ public class SummarizationPredictor extends AbstractTaskPredictor { protected String getPythonScript() { String doSample = config.getTemperature() > 0 ? "True" : "False"; float temperature = config.getTemperature() > 0 ? config.getTemperature() : 1.0f; - return loadPythonScript("summarization.py", config.getModelId(), config.getRevision(), config.getDevice(), + return loadPythonScript("summarization.py", pythonString(config.getModelId()), pythonString(config.getRevision()), + pythonString(config.getDevice()), config.getMinLength(), config.getMaxTokens(), doSample, temperature); } diff --git a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextClassificationPredictor.java b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextClassificationPredictor.java index 6e102dc9a0cb..a9dace6933e1 100644 --- a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextClassificationPredictor.java +++ b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextClassificationPredictor.java @@ -93,7 +93,8 @@ public class TextClassificationPredictor extends AbstractTaskPredictor { @Override protected String getPythonScript() { - return loadPythonScript("text_classification.py", config.getModelId(), config.getRevision(), config.getDevice(), + return loadPythonScript("text_classification.py", pythonString(config.getModelId()), pythonString(config.getRevision()), + pythonString(config.getDevice()), config.getTopK()); } diff --git a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextGenerationPredictor.java b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextGenerationPredictor.java index 932f20dede49..e0dec19e0201 100644 --- a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextGenerationPredictor.java +++ b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextGenerationPredictor.java @@ -84,7 +84,8 @@ public class TextGenerationPredictor extends AbstractTaskPredictor { protected String getPythonScript() { String doSample = config.getTemperature() > 0 ? "True" : "False"; float temperature = config.getTemperature() > 0 ? config.getTemperature() : 1.0f; - return loadPythonScript("text_generation.py", config.getModelId(), config.getRevision(), config.getDevice(), + return loadPythonScript("text_generation.py", pythonString(config.getModelId()), pythonString(config.getRevision()), + pythonString(config.getDevice()), config.getMaxTokens(), doSample, temperature); } diff --git a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextToImagePredictor.java b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextToImagePredictor.java index 9544073353d2..2a3ae2dd9eb1 100644 --- a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextToImagePredictor.java +++ b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextToImagePredictor.java @@ -92,7 +92,8 @@ public class TextToImagePredictor extends AbstractTaskPredictor { @Override protected String getPythonScript() { - return loadPythonScript("text_to_image.py", config.getModelId(), config.getRevision(), config.getDevice()); + return loadPythonScript("text_to_image.py", pythonString(config.getModelId()), pythonString(config.getRevision()), + pythonString(config.getDevice())); } @Override diff --git a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextToSpeechPredictor.java b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextToSpeechPredictor.java index fb2fd8589952..12e2a07eb76a 100644 --- a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextToSpeechPredictor.java +++ b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/TextToSpeechPredictor.java @@ -99,7 +99,8 @@ public class TextToSpeechPredictor extends AbstractTaskPredictor { @Override protected String getPythonScript() { - return loadPythonScript("text_to_speech.py", config.getModelId(), config.getRevision(), config.getDevice()); + return loadPythonScript("text_to_speech.py", pythonString(config.getModelId()), pythonString(config.getRevision()), + pythonString(config.getDevice())); } @Override diff --git a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/ZeroShotClassificationPredictor.java b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/ZeroShotClassificationPredictor.java index 2b67d94d52b9..6804a25979b3 100644 --- a/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/ZeroShotClassificationPredictor.java +++ b/components/camel-ai/camel-huggingface/src/main/java/org/apache/camel/component/huggingface/tasks/ZeroShotClassificationPredictor.java @@ -98,8 +98,9 @@ public class ZeroShotClassificationPredictor extends AbstractTaskPredictor { protected String getPythonScript() { String multiLabel = config.isMultiLabel() ? "True" : "False"; String autoSelect = config.isAutoSelect() ? "True" : "False"; - return loadPythonScript("zero_shot_classification.py", config.getModelId(), config.getRevision(), - config.getDevice(), multiLabel, autoSelect); + return loadPythonScript("zero_shot_classification.py", pythonString(config.getModelId()), + pythonString(config.getRevision()), + pythonString(config.getDevice()), multiLabel, autoSelect); } @Override diff --git a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/automatic_speech_recognition.py b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/automatic_speech_recognition.py index 7af61d4f437b..0f424218f330 100644 --- a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/automatic_speech_recognition.py +++ b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/automatic_speech_recognition.py @@ -30,9 +30,9 @@ def handle(inputs: Input): logging.debug("Initializing pipeline") pipe = pipeline( task='automatic-speech-recognition', - model='%s', - revision='%s', - device_map='%s' + model=%s, + revision=%s, + device_map=%s ) logging.debug("Pipeline initialized") diff --git a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/chat.py b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/chat.py index f20d5c3c35fc..ce9cba314499 100644 --- a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/chat.py +++ b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/chat.py @@ -28,7 +28,7 @@ def handle(inputs: Input): try: if not pipe: logging.debug("Initializing pipeline") - pipe = pipeline(task='text-generation', model='%s', revision='%s', device_map='%s') + pipe = pipeline(task='text-generation', model=%s, revision=%s, device_map=%s) logging.debug("Pipeline initialized") if inputs.content.size() == 0: diff --git a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/question_answering.py b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/question_answering.py index f7015cd9660e..3f28c03e98ca 100644 --- a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/question_answering.py +++ b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/question_answering.py @@ -30,9 +30,9 @@ def handle(inputs: Input): logging.debug("Initializing pipeline") pipe = pipeline( task='question-answering', - model='%s', - revision='%s', - device_map='%s' + model=%s, + revision=%s, + device_map=%s ) logging.debug("Pipeline initialized") diff --git a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/sentence_embeddings.py b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/sentence_embeddings.py index 9ee585c2dde6..9b3e31f23981 100644 --- a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/sentence_embeddings.py +++ b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/sentence_embeddings.py @@ -28,10 +28,10 @@ def handle(inputs: Input): try: if not model: logging.debug("Initializing model") - device = '%s' + device = %s if device == 'auto': device = 'cuda' if torch.cuda.is_available() else 'cpu' - model = SentenceTransformer('%s', device=device, revision='%s') + model = SentenceTransformer(%s, device=device, revision=%s) logging.debug("Model initialized") if inputs.content.size() == 0: diff --git a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/summarization.py b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/summarization.py index 53896e6d2b5d..e2a4f8d95f70 100644 --- a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/summarization.py +++ b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/summarization.py @@ -30,9 +30,9 @@ def handle(inputs: Input): logging.debug("Initializing pipeline") pipe = pipeline( task='summarization', - model='%s', - revision='%s', - device_map='%s' + model=%s, + revision=%s, + device_map=%s ) logging.debug("Pipeline initialized") diff --git a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_classification.py b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_classification.py index be85e8e1e05d..40820f5cd718 100644 --- a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_classification.py +++ b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_classification.py @@ -31,9 +31,9 @@ def handle(inputs: Input): logging.debug("Initializing pipeline") pipe = pipeline( task='text-classification', - model='%s', - revision='%s', - device_map='%s', + model=%s, + revision=%s, + device_map=%s, top_k=%s ) logging.debug("Pipeline initialized") diff --git a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_generation.py b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_generation.py index cbf79fe71447..c4e8c25a1dee 100644 --- a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_generation.py +++ b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_generation.py @@ -30,9 +30,9 @@ def handle(inputs: Input): logging.debug("Initializing pipeline") pipe = pipeline( task='text-generation', - model='%s', - revision='%s', - device_map='%s' + model=%s, + revision=%s, + device_map=%s ) logging.debug("Pipeline initialized") diff --git a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_to_image.py b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_to_image.py index aa7eae92638c..b050f7c6ab4b 100644 --- a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_to_image.py +++ b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_to_image.py @@ -30,12 +30,12 @@ def handle(inputs: Input): if not pipe: logging.debug("Initializing pipeline") pipe = StableDiffusionPipeline.from_pretrained( - '%s', - revision='%s', + %s, + revision=%s, torch_dtype=torch.float32, # CPU-safe safety_checker=None ) - pipe = pipe.to('%s') + pipe = pipe.to(%s) logging.debug("Pipeline initialized") if inputs.content.size() == 0: diff --git a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_to_speech.py b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_to_speech.py index be77d5545a30..9ebd6c530306 100644 --- a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_to_speech.py +++ b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/text_to_speech.py @@ -31,9 +31,9 @@ def handle(inputs: Input): logging.debug("Initializing pipeline") pipe = pipeline( task='text-to-speech', - model='%s', - revision='%s', - device_map='%s' + model=%s, + revision=%s, + device_map=%s ) logging.debug("Pipeline initialized") diff --git a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/zero_shot_classification.py b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/zero_shot_classification.py index 4dd306f353f5..78cd943d6330 100644 --- a/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/zero_shot_classification.py +++ b/components/camel-ai/camel-huggingface/src/main/resources/org/apache/camel/component/huggingface/tasks/zero_shot_classification.py @@ -30,9 +30,9 @@ def handle(inputs: Input): logging.debug("Initializing pipeline") pipe = pipeline( task='zero-shot-classification', - model='%s', - revision='%s', - device_map='%s' + model=%s, + revision=%s, + device_map=%s ) logging.debug("Pipeline initialized") diff --git a/components/camel-ai/camel-huggingface/src/test/java/org/apache/camel/component/huggingface/tasks/AuthTokenInjectionTest.java b/components/camel-ai/camel-huggingface/src/test/java/org/apache/camel/component/huggingface/tasks/AuthTokenInjectionTest.java index 1f651614bfd8..1e0f21457188 100644 --- a/components/camel-ai/camel-huggingface/src/test/java/org/apache/camel/component/huggingface/tasks/AuthTokenInjectionTest.java +++ b/components/camel-ai/camel-huggingface/src/test/java/org/apache/camel/component/huggingface/tasks/AuthTokenInjectionTest.java @@ -16,43 +16,82 @@ */ package org.apache.camel.component.huggingface.tasks; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; + import org.apache.camel.component.huggingface.HuggingFaceConfiguration; import org.apache.camel.component.huggingface.HuggingFaceEndpoint; +import org.apache.camel.impl.DefaultCamelContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * The configured Hugging Face token must be applied for every task, not only chat, so that gated or private models can - * be loaded. The token is injected centrally as the HF_TOKEN environment variable of the generated handler. + * be loaded. The token is given to the Python process as the HF_TOKEN environment variable (the env option of the DJL + * Python engine), and is not written into the generated handler. */ class AuthTokenInjectionTest { + @TempDir + Path dir; + + private DefaultCamelContext context; + + @BeforeEach + void setUp() { + context = new DefaultCamelContext(); + } + + @AfterEach + void tearDown() { + context.stop(); + } + private TextGenerationPredictor predictorWithToken(String token) { HuggingFaceConfiguration config = new HuggingFaceConfiguration(); + config.setModelId("gpt2"); config.setAuthToken(token); - return new TextGenerationPredictor(new HuggingFaceEndpoint(null, null, config)); + HuggingFaceEndpoint endpoint = new HuggingFaceEndpoint(null, null, config); + endpoint.setCamelContext(context); + return new TextGenerationPredictor(endpoint); } @Test - void authTokenIsExposedAsHfTokenEnvForEveryTask() { - String result = predictorWithToken("hf_secret123").withAuthToken("PIPELINE"); - assertTrue(result.contains("os.environ['HF_TOKEN'] = 'hf_secret123'"), - "generated script should export the token as HF_TOKEN"); - assertTrue(result.endsWith("PIPELINE"), "the original task script must be preserved"); + void authTokenIsGivenAsHfTokenEnvironmentVariable() { + Map<String, String> options = predictorWithToken("hf_secret123").modelOptions(dir.resolve("requirements.txt")); + assertEquals("HF_TOKEN=hf_secret123", options.get("env")); + assertEquals("handler.py", options.get("entryPoint")); } @Test - void noAuthTokenLeavesTheScriptUnchanged() { - assertEquals("PIPELINE", predictorWithToken(null).withAuthToken("PIPELINE")); - assertEquals("PIPELINE", predictorWithToken("").withAuthToken("PIPELINE")); + void noAuthTokenSetsNoEnvironmentVariable() { + assertNull(predictorWithToken(null).modelOptions(dir.resolve("requirements.txt")).get("env")); + assertNull(predictorWithToken("").modelOptions(dir.resolve("requirements.txt")).get("env")); + } + + @Test + void authTokenIsNotWrittenIntoTheHandler() throws Exception { + predictorWithToken("hf_secret123").writeModelFiles(dir); + + String handler = Files.readString(dir.resolve("handler.py")); + assertFalse(handler.contains("hf_secret123"), "the token must not be in the generated handler"); + assertFalse(handler.contains("HF_TOKEN"), "the handler must not set the token itself"); + assertFalse(Files.readString(dir.resolve("requirements.txt")).contains("hf_secret123")); } @Test - void authTokenWithASingleQuoteIsEscaped() { - String result = predictorWithToken("ab'cd").withAuthToken("PIPELINE"); - assertTrue(result.contains("os.environ['HF_TOKEN'] = 'ab\\'cd'"), - "a single quote in the token must be escaped so it cannot break the Python string literal"); + void authTokenWithACommaFails() { + TextGenerationPredictor predictor = predictorWithToken("hf_ab,cd"); + Path reqPath = dir.resolve("requirements.txt"); + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> predictor.modelOptions(reqPath)); + assertFalse(e.getMessage().contains("hf_ab"), "the message must not show the token"); } } diff --git a/components/camel-ai/camel-huggingface/src/test/java/org/apache/camel/component/huggingface/tasks/HandlerValuesTest.java b/components/camel-ai/camel-huggingface/src/test/java/org/apache/camel/component/huggingface/tasks/HandlerValuesTest.java new file mode 100644 index 000000000000..73caba34c6e3 --- /dev/null +++ b/components/camel-ai/camel-huggingface/src/test/java/org/apache/camel/component/huggingface/tasks/HandlerValuesTest.java @@ -0,0 +1,182 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.component.huggingface.tasks; + +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.camel.component.huggingface.HuggingFaceConfiguration; +import org.apache.camel.component.huggingface.HuggingFaceEndpoint; +import org.apache.camel.impl.DefaultCamelContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The option values put into the generated Python handler must be proper Python string literals, so a quote, a + * backslash or a newline in a value cannot end the literal or the line, and the temporary model directory must be + * removed. + */ +class HandlerValuesTest { + + @TempDir + Path dir; + + private DefaultCamelContext context; + + @BeforeEach + void setUp() { + context = new DefaultCamelContext(); + } + + @AfterEach + void tearDown() { + context.stop(); + } + + private HuggingFaceEndpoint endpoint(HuggingFaceConfiguration config) { + HuggingFaceEndpoint endpoint = new HuggingFaceEndpoint(null, null, config); + endpoint.setCamelContext(context); + return endpoint; + } + + @Test + void pythonStringEscapesBackslashQuoteAndControlCharacters() { + assertEquals("'gpt2'", AbstractTaskPredictor.pythonString("gpt2")); + assertEquals("'a\\\\b\\'c\"d\\x0ae\\x0d\\x09'", AbstractTaskPredictor.pythonString("a\\b'c\"d\ne\r\t")); + assertEquals("'caf\\xe9 \\u20ac \\U0001f600'", AbstractTaskPredictor.pythonString("café € 😀")); + assertEquals("None", AbstractTaskPredictor.pythonString(null)); + } + + @Test + void valueWithBackslashQuoteAndNewlineStaysInsideTheLiteral() { + HuggingFaceConfiguration plain = new HuggingFaceConfiguration(); + plain.setModelId("gpt2"); + String plainScript = new TextGenerationPredictor(endpoint(plain)).getPythonScript(); + + HuggingFaceConfiguration config = new HuggingFaceConfiguration(); + config.setModelId("org/m\\', revision='x\nimport os"); + config.setRevision("v1\\"); + config.setDevice("cpu'"); + String script = new TextGenerationPredictor(endpoint(config)).getPythonScript(); + + assertTrue(script.contains("model='org/m\\\\\\', revision=\\'x\\x0aimport os',"), script); + assertTrue(script.contains("revision='v1\\\\',"), script); + assertTrue(script.contains("device_map='cpu\\''"), script); + assertEquals(plainScript.lines().count(), script.lines().count(), "a value must not add a line to the handler"); + } + + @Test + void everyTaskPutsTheValuesAsLiterals() { + HuggingFaceConfiguration config = new HuggingFaceConfiguration(); + config.setModelId("a'b"); + config.setRevision("r'1"); + config.setDevice("d'1"); + HuggingFaceEndpoint endpoint = endpoint(config); + AbstractTaskPredictor[] predictors = { + new AutomaticSpeechRecognitionPredictor(endpoint), new ChatPredictor(endpoint), + new QuestionAnsweringPredictor(endpoint), new SentenceEmbeddingsPredictor(endpoint), + new SummarizationPredictor(endpoint), new TextClassificationPredictor(endpoint), + new TextGenerationPredictor(endpoint), new TextToImagePredictor(endpoint), + new TextToSpeechPredictor(endpoint), new ZeroShotClassificationPredictor(endpoint) }; + for (AbstractTaskPredictor predictor : predictors) { + String script = predictor.getPythonScript(); + String name = predictor.getClass().getSimpleName(); + assertTrue(script.contains("'a\\'b'"), name + " must put the model ID as a literal"); + assertTrue(script.contains("'r\\'1'"), name + " must put the revision as a literal"); + assertTrue(script.contains("'d\\'1'"), name + " must put the device as a literal"); + assertFalse(script.contains("a'b"), name + " must not put the model ID unescaped"); + } + } + + @Test + @ResourceLock(Resources.LOCALE) + void temperatureIsWrittenWithADotInEveryLocale() { + HuggingFaceConfiguration config = new HuggingFaceConfiguration(); + config.setModelId("gpt2"); + config.setTemperature(0.5f); + Locale old = Locale.getDefault(); + try { + Locale.setDefault(Locale.GERMANY); + String script = new TextGenerationPredictor(endpoint(config)).getPythonScript(); + assertTrue(script.contains("'temperature': 0.500000"), script); + } finally { + Locale.setDefault(old); + } + } + + @Test + void closeRemovesTheModelDirectory() throws Exception { + HuggingFaceConfiguration config = new HuggingFaceConfiguration(); + config.setModelId("gpt2"); + TextGenerationPredictor predictor = new TextGenerationPredictor(endpoint(config)); + Path modelDir = Files.createDirectory(dir.resolve("hf_model")); + predictor.tmpDir = modelDir; + predictor.writeModelFiles(modelDir); + assertTrue(Files.exists(modelDir.resolve("handler.py"))); + + predictor.close(); + + assertFalse(Files.exists(modelDir), "the model directory must be removed on close"); + assertNull(predictor.tmpDir); + } + + @Test + void modelDirectoryIsRemovedWhenTheModelFailsToLoad() { + HuggingFaceConfiguration config = new HuggingFaceConfiguration(); + config.setModelId("gpt2"); + AtomicReference<Path> modelDir = new AtomicReference<>(); + AtomicReference<String> permissions = new AtomicReference<>(); + TextGenerationPredictor predictor = new TextGenerationPredictor(endpoint(config)) { + @Override + protected String getRequirements() { + // called once handler.py is written, before the Python engine is started + modelDir.set(tmpDir); + if (FileSystems.getDefault().supportedFileAttributeViews().contains("posix")) { + try { + permissions.set(PosixFilePermissions.toString(Files.getPosixFilePermissions(tmpDir))); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + throw new IllegalStateException("cannot load"); + } + }; + + assertThrows(IllegalStateException.class, predictor::loadModel); + + assertNotNull(modelDir.get()); + assertFalse(Files.exists(modelDir.get()), "the model directory must be removed when loading fails"); + if (permissions.get() != null) { + assertEquals("rwx------", permissions.get(), "only the owner may read the model directory"); + } + } +} diff --git a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc index 25708c2cd51b..f09e7cf55302 100644 --- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc +++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc @@ -12297,6 +12297,14 @@ With `allowUrlBody=true`, a body that does not start with `version: 1` and is no with a space or a relative name, now fails with an `InvalidPayloadException`, as a URL with an unknown scheme already did. Before, it failed with an `IllegalArgumentException`. A URL that cannot be fetched keeps its own exception. +=== camel-huggingface - the token is given to the Python process as an environment variable + +The `authToken` (or the token from the `oauthProfile`) is no longer written into the generated Python handler: it is +given to the Python process as the `HF_TOKEN` environment variable, through the `env` option of the DJL Python engine. +That option is a comma separated list, so a token with a comma now fails when the producer starts. The protected +method `withAuthToken` of `AbstractTaskPredictor` is removed. The `modelId`, `revision` and `device` values are now +written into the handler as escaped Python string literals. + === Kamelets - removed Kamelets The Kamelet catalog (camel-kamelets 4.24) removes Kamelets that could not work on Camel 4.23 or 4.24:
