Download the PHP package codewithkyrian/huggingface without Composer

On this page you can find all versions of the php package codewithkyrian/huggingface. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package huggingface

Hugging Face PHP

GitHub Workflow Status (main) Total Downloads Latest Version License

A comprehensive PHP client for the Hugging Face Hub. Access thousands of machine learning models, datasets, run inference, and more, all from your PHP application.

Table of Contents

Installation

Install the package via Composer:

Requirements

If you don't have a PSR-18 client installed, add Guzzle:

Quick Start

The client works without authentication for public resources:

For operations requiring authentication (private repos, inference, uploads), provide a token:

Configuration

Authentication

A token is optional for public Hub operations (downloading, searching, listing). You need a token for:

Getting a token:

  1. Create a free account at huggingface.co
  2. Go to Settings → Access Tokens
  3. Create a token with appropriate permissions

Basic Setup

Environment Variables

The client automatically checks these environment variables:

Advanced Configuration

Use the factory for full control:

Hub API

The Hub API lets you manage repositories, upload models, and search the Hugging Face Hub.

Repository Basics

Get a RepoManager for any repository. All operations (info, files, download, commit) flow through it.

Working with Revisions

By default, operations use the main branch. Use revision() to target a specific branch, tag, or commit.

Repository Info

Get metadata about a repository.

Shorthand methods when you only need metadata:

Creating Repositories

Create Options

Method Description
private() Make repository private
license(string $id) Set license (e.g., mit, apache-2.0)
sdk(SpaceSdk $sdk, string $version) Set Space SDK and version (for spaces only)
hardware(SpaceHardware $hw) Set Space hardware tier (for spaces only)

Updating Repositories

Repository Operations

Branch Management

Deleting Repositories

File Operations

Listing Files

Listing Options

Method Description
files(recursive: true) Include files in subdirectories
files(expand: true) Include expanded metadata
files(path: 'subdir') List files in specific directory

File Information

Downloading Files

Download Options

Method Description
force() Re-download even if cached
useCache(false) Skip cache entirely
save(?string $path) Save to directory, or cache if null
getContent() Get raw content as string
json() Parse content as JSON

Cache Helpers

Downloading Entire Repositories

Download all files to a local cached snapshot.

Snapshots are additive, so you can call snapshot() multiple times to build up a local content cache. Use force: false to skip the remote update check if you already have a cached revision.

Uploading Files

Quick Upload

Commit Builder

For complex operations, use the commit builder:

addFile() accepts: string (content or path), URL, or resource (stream).

Deleting Files

Listing Commits

[!NOTE] commits() returns a Generator that fetches pages lazily. The batchSize argument (1–1000) controls how many commits are fetched per API request; the generator keeps requesting more pages until all commits are returned, so use a break when you have enough results.

Collections

Collections are curated lists of models, datasets, spaces, or papers.

Listing Collections

Creating Collections

Managing Items

Searching Models, Datasets, and Spaces

Search returns a Generator that fetches results lazily.

Models

Model Search Options

Method Description
search(string $query) Full-text search
task(string $task) Filter by pipeline task
library(string $lib) Filter by library (e.g., transformers)
author(string $author) Filter by author/organization
language(string $lang) Filter by language code
sort(SortField $field) Sort by downloads, likes, etc.
descending() Sort in descending order
limit(int $n) Maximum results to fetch

Datasets

Spaces

[!WARNING] Without limit(), the generator fetches ALL matching results. Always set a limit or break manually.

Inference API

The Inference API lets you run machine learning models on Hugging Face's infrastructure. It supports text generation, embeddings, classification, image generation, speech recognition, and more.

Provider Configuration

The inference client supports multiple providers. Pass the provider directly to inference():

Supported Providers

Provider Slug Tasks
Hugging Face hf-inference (default) All tasks
Black Forest Labs black-forest-labs Text-to-Image
Cerebras cerebras Chat
Cohere cohere Chat
Fal.ai fal-ai Text-to-Image, Text-to-Video, Image-to-Image, Image-to-Video, ASR, TTS
Featherless AI featherless-ai Chat, Text Generation
Fireworks AI fireworks-ai Chat
Groq groq Chat, Text Generation
Hyperbolic hyperbolic Chat, Text Generation, Text-to-Image
Nebius nebius Chat, Text Generation, Text-to-Image, Embeddings
Novita novita Chat, Text Generation
Nscale nscale Chat, Text-to-Image
OpenAI openai Chat (requires direct API key)
OVHcloud ovhcloud Chat, Text Generation
Replicate replicate Text-to-Image
Sambanova sambanova Chat, Embeddings
Scaleway scaleway Chat, Text Generation, Embeddings
Together AI together Chat, Text Generation, Text-to-Image
ZAI zai-org Chat, Text-to-Image

Provider Resolution

When you don't specify a provider (or use InferenceProvider::Auto), the client automatically selects the best available provider for your model. Here's how it works:

  1. Map Model Providers: The client queries the Hugging Face Hub to find all providers that serve this model following the priority order of providers you've configured in your Inference Provider settings on Hugging Face.
  2. Availability & Compatibility: It selects the first provider that is currently available and supports the requested task.
  3. Exception: If no viable provider is found for the model and task, a RoutingException is thrown.

This ensures you always get the most reliable inference endpoint based on your personal or organization settings.

Billing

Bill requests to an organization:

Chat Completion

Chat with large language models using a conversational interface. Supports system prompts, multi-turn conversations, and streaming.

Multi-turn Conversations

Streaming

Options

Method Description
system(string $content) Add a system message
user(string $content) Add a user message
assistant(string $content) Add an assistant message
maxTokens(int $tokens) Maximum tokens to generate
temperature(float $temp) Sampling temperature (0.0–2.0)
topP(float $p) Nucleus sampling probability
topK(int $k) Top-k sampling
stop(array $sequences) Stop sequences
seed(int $seed) Random seed for reproducibility
frequencyPenalty(float $penalty) Reduce repetition of tokens
presencePenalty(float $penalty) Encourage new topics
logprobs(bool $b, ?int $k) Return log probabilities
responseFormat(array $fmt) Set response format (e.g. JSON)
tool(ChatCompletionTool $tool) Add a tool definition
tools(array<ChatCompletionTool> $tools) Add multiple tools
toolChoice(string\|array $c) Control tool choice

Text Generation

Generate text continuations from a prompt. Unlike chat completion, this is for raw text completion without conversation structure.

Options

Method Description
maxNewTokens(int $n) Max new tokens to generate
temperature(float $t) Sampling temperature
topK(float $k) Top-k sampling
topP(float $p) Nucleus sampling
repetitionPenalty(float $p) Repetition penalty (> 1.0)
doSample(bool $b) Enable/disable sampling
returnFullText(bool $b) Include prompt in output
seed(int $s) Random seed
stop(string\|array $s) Stop sequence(s)
truncate(int $t) Truncate inputs to size
watermark(bool $b) Enable watermarking
frequencyPenalty(float $p) Frequency penalty
bestOf(int $n) Generate best of N sequences
decoderInputDetails(bool $b) Return decoder input details

Also supports: adapterId, details, grammar, topNTokens, typicalP

Feature Extraction (Embeddings)

Generate vector embeddings for text. Useful for semantic search, clustering, and similarity comparisons.

Options

Method Description
normalize() Normalize embeddings to unit length
truncate() Truncate input to model's max length
promptName(string $name) Use a specific prompt template
truncationDirection(TruncationDirection $direction) Left or Right truncation

Text Classification

Classify text into categories. Returns scored labels.

Options

Method Description
topK(int $k) Number of predictions to return
functionToApply(ClassificationOutputTransform $f) Function to apply to scores (Sigmoid, Softmax, None)

Token Classification

Classify individual tokens in a text, such as identifying entities (NER) or parts of speech (POS).

Options

Method Description
aggregationStrategy(AggregationStrategy $s) Strategy to fuse tokens (None, Simple, First, Average, Max)
ignoreLabels(array $labels) List of labels to ignore during classification
stride(int $n) Overlap tokens between chunks for long text

Summarization

Summarize long text into shorter versions.

Options

Method Description
maxLength(int $length) Maximum summary length
minLength(int $length) Minimum summary length
doSample(bool $sample) Enable sampling for varied output
temperature(float $temp) Sampling temperature

Question Answering

Extract answers from a context passage.

Options

Method Description
topK(int $k) Number of answers to return
docStride(int $n) Overlap size for long context chunks
maxAnswerLen(int $n) Max answer length
maxQuestionLen(int $n) Max question length
maxSeqLen(int $n) Max chunk length (context + question)
alignToWords(bool $b) Align answer to words (true by default)
handleImpossibleAnswer(bool $b) Accept impossible answers

Translation

Translate text between languages. Model determines the language pair.

Options

Method Description
srcLang(string $lang) Source language code
tgtLang(string $lang) Target language code
maxNewTokens(int $n) Max new tokens to generate
temperature(float $t) Sampling temperature
doSample(bool $b) Enable sampling
cleanUpTokenizationSpaces(bool $b) Clean up spaces
truncation(TruncationStrategy $s) Truncation strategy

Supports other generation parameters like topK, topP, etc.

Fill Mask

Predict masked tokens in text (like BERT's pre-training task).

Options

Method Description
topK(int $k) Number of predictions to return
targets(array $targets) Limit predictions to specific words

Sentence Similarity

Compare a source sentence against multiple target sentences.

Text to Image

Generate images from text prompts.

Options

Method Description
numInferenceSteps(int $steps) Number of denoising steps
guidanceScale(float $scale) How closely to follow the prompt
width(int $px) Output image width
height(int $px) Output image height
size(int $w, int $h) Set both width and height
seed(int $seed) Random seed for reproducibility
negativePrompt(string $prompt) What to avoid in the image

Image Classification

Classify images into categories.

Options

Method Description
topK(int $k) Number of predictions to return
functionToApply(ClassificationOutputTransform $f) Function to apply to scores (Sigmoid, Softmax, None)

Object Detection

Detect objects in an image with bounding boxes.

Options

Method Description
threshold(float $threshold) Probability threshold to make a prediction

Image to Text

Generate captions for images.

Options

Method Description
maxNewTokens(int $n) Max new tokens to generate
temperature(float $t) Sampling temperature
doSample(bool $b) Enable sampling
topK(int $k) Top-k sampling
topP(float $p) Nucleus sampling
minNewTokens(int $n) Min new tokens to generate
numBeams(int $n) Number of beams for beam search

Supports other standard generation parameters: earlyStopping, numBeamGroups, penaltyAlpha, useCache, etaCutoff, epsilonCutoff, typicalP

Text to Speech

Convert text to audio.

Options

Method Description
maxNewTokens(int $n) Max new tokens to generate
temperature(float $t) Sampling temperature
doSample(bool $b) Enable sampling
topK(int $k) Top-k sampling
topP(float $p) Nucleus sampling
minNewTokens(int $n) Min new tokens to generate
numBeams(int $n) Number of beams for beam search

Supports other standard generation parameters: earlyStopping, numBeamGroups, penaltyAlpha, useCache, etaCutoff, epsilonCutoff, typicalP

Automatic Speech Recognition

Transcribe audio to text.

Zero-Shot Classification

Classify text into arbitrary categories without training.

Options

Method Description
multiLabel(bool $enable) Allow multiple labels to be true
hypothesisTemplate(string $template) Custom hypothesis template

Caching

The library uses a unified repository-based cache system with blob deduplication. This means:

Cache Structure

Cache Management

You can inspect and manage the cache programmatically:

Default Cache Location

The cache is stored in a platform-appropriate location:

You can override with the HF_HUB_CACHE or HF_HOME environment variables.

Custom Cache Directory

Downloading to Cache

Disabling Cache

Force Re-download

Error Handling

The library uses specific exception types for different error conditions:

Automatic Retries

The library automatically retries on transient failures:

This happens transparently so you don't need to implement retry logic yourself.

Examples

The examples/ directory contains ready-to-run scripts:

Directory Description
examples/hub/ Hub operations (search, download, upload)
examples/inference/ Inference API examples for all tasks

Run any example:

API Reference

See the API Reference for complete documentation of all classes and methods.

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

License

MIT License. See LICENSE for details.


All versions of huggingface with dependencies

PHP Build Version
Package Version
Requires php Version ^8.2
ext-curl Version *
psr/http-client Version ^1.0
psr/http-factory Version ^1.1
php-http/discovery Version ^1.20
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package codewithkyrian/huggingface contains the following files

Loading the files please wait ...