PHP code example of codewithkyrian / huggingface

1. Go to this page and download the library: Download codewithkyrian/huggingface library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

codewithkyrian / huggingface example snippets


use Codewithkyrian\HuggingFace\HuggingFace;

$hf = HuggingFace::client();

// Download a model config
$config = $hf->hub()->repo('bert-base-uncased')
    ->download('config.json')
    ->json();

// List models
$models = $hf->hub()->models()
    ->search('sentiment')
    ->limit(5)
    ->get();

// Chat with an LLM
$response = $hf->inference()
    ->chatCompletion('meta-llama/Llama-3.1-8B-Instruct')
    ->system('You are a helpful assistant.')
    ->user('What is PHP?')
    ->generate();

// Generate embeddings
$embeddings = $hf->inference()
    ->featureExtraction('sentence-transformers/all-MiniLM-L6-v2')
    ->normalize()
    ->execute('Hello world');



odewithkyrian\HuggingFace\HuggingFace;

$hf = HuggingFace::client();

// Download a model file
$config = $hf->hub()
    ->repo('bert-base-uncased')
    ->download('config.json')
    ->json();

echo "Model type: {$config['model_type']}\n";

// List models
$models = $hf->hub()
    ->models()
    ->search('text-classification')
    ->library('transformers')
    ->limit(5)
    ->get();

foreach ($models->items as $model) {
    echo "{$model->id} - {$model->downloads} downloads\n";
}

// List files in a repository
$files = $hf->hub()->repo('gpt2')->files();

foreach ($files as $file) {
    echo "{$file->path} ({$file->size} bytes)\n";
}

// Work with specific revisions
$v1Repo = $hf->hub()->repo('gpt2')->revision('v1.0');
$info = $v1Repo->info();
$files = $v1Repo->files();

$hf = HuggingFace::client('hf_your_token');

// Run inference
$classifier = $hf->inference()->textClassification('distilbert-base-uncased-finetuned-sst-2-english');

$results = $classifier->execute('I love this product!');

echo $results[0]->label; // "POSITIVE"

use Codewithkyrian\HuggingFace\HuggingFace;

// Without token (public operations only)
$hf = HuggingFace::client();

// With token
$hf = HuggingFace::client('hf_your_token_here');

// Set HF_TOKEN or HUGGING_FACE_HUB_TOKEN in your environment
$hf = HuggingFace::client(); // Token loaded automatically

$hf = HuggingFace::factory()
    ->withToken('hf_your_token')          // Optional
    ->withCacheDir('/path/to/cache')      // Custom cache directory
    ->withHubUrl('https://custom.hf')     // Custom Hub endpoint
    ->make();

use Codewithkyrian\HuggingFace\Enums\RepoType;

$hub = $hf->hub();

$repo = $hub->repo('bert-base-uncased');                      // Model (default)
$repo = $hub->repo('squad', RepoType::Dataset);               // Dataset
$repo = $hub->repo('gradio/hello-world', RepoType::Space);    // Space

$repo = $hub->repo('bert-base-uncased');

$v1Repo = $repo->revision('v1.0');
$info = $v1Repo->info();
$files = $v1Repo->files();

$repo = $hub->repo('bert-base-uncased');

$info = $repo->info();
echo $info->id;        // "bert-base-uncased"
echo $info->downloads; // 12345678

$modelInfo = $hub->modelInfo('bert-base-uncased');
$datasetInfo = $hub->datasetInfo('squad');
$spaceInfo = $hub->spaceInfo('gradio/hello-world');

use Codewithkyrian\HuggingFace\Enums\RepoType;
use Codewithkyrian\HuggingFace\Enums\SpaceSdk;

// Model repository
$repo = $hub->createRepo('my-model', RepoType::Model)
    ->private()
    ->license('mit')
    ->save();

// Dataset
$repo = $hub->createRepo('my-dataset', RepoType::Dataset)->save();

// Space
$repo = $hub->createRepo('my-space', RepoType::Space)
    ->sdk(SpaceSdk::Gradio, '4.0.0')
    ->save();

use Codewithkyrian\HuggingFace\Enums\Visibility;

$repo = $hub->repo('username/my-model');

$repo->setVisibility(Visibility::Public);

$repo->update([
    'description' => 'Updated description',
    'tags' => ['pytorch', 'text-classification'],
]);

$repo = $hub->repo('username/my-model');

// Check existence
if ($repo->exists()) {
    echo "Repository exists";
}

// Check access
$repo->checkAccess(); // Throws AuthenticationException or ApiException if denied

// Rename/move
$renamedRepo = $repo->move('new-name');

// Fork
$forkedRepo = $repo->fork();
$forkedRepo = $repo->fork(targetNamespace: 'my-org');

// Delete
$repo->delete();
$repo->delete(missingOk: true); // Don't throw if not found

$repo = $hub->repo('username/my-model');

// Create branches
$repo->createBranch('feature-x');
$repo->createBranch('feature-y', revision: 'v1.0');
$repo->createBranch('empty-branch', empty: true);

// Delete branch
$repo->deleteBranch('old-branch');

// List branches and tags
$branches = $repo->branches();
$tags = $repo->tags();
$refs = $repo->refs(); // All refs (branches, tags, converts)

// Throws if repo is not found
$hub->repo('username/my-model')->delete();

// Don't throw if not found
$hub->repo('username/maybe-exists')->delete(missingOk: true);

$repo = $hub->repo('bert-base-uncased');

$files = $repo->files();  // returns Generator

foreach ($files as $file) {
    echo "{$file->path} ({$file->size} bytes)\n";
}

$repo = $hub->repo('bert-base-uncased');

// Check existence
$exists = $repo->fileExists('config.json');

// Single file info
$info = $repo->fileInfo('config.json');
echo $info->size;
echo $info->oid;
echo $info->isLfs();

// Multiple files
$filesInfo = $repo->pathsInfo(['config.json', 'model.safetensors']);

$repo = $hub->repo('bert-base-uncased');

// Download to directory
$path = $repo->download('config.json')->save('/local/path');

// Download to cache (returns cached path)
$cachedPath = $repo->download('config.json')->save();

// Get content directly
$content = $repo->download('config.json')->getContent();

// Parse as JSON
$config = $repo->download('config.json')->json();

// Get metadata only
$info = $repo->download('config.json')->info();
echo "Size: {$info->size} bytes";
echo "ETag: {$info->etag}";

$repo = $hub->repo('bert-base-uncased');

$isCached = $repo->isCached('config.json');
$path = $repo->getCachedPath('config.json'); // null if not cached

$repo = $hub->repo('bert-base-uncased');

$snapshotPath = $repo->snapshot();

// With filtering
$snapshotPath = $repo->snapshot(
    allowPatterns: ['*.json', '*.txt'],
    ignorePatterns: ['*.bin', '*.safetensors']
);

// Optimized (skip network check)
$snapshotPath = $repo->snapshot(force: false);

$repo = $hub->repo('username/my-model');

// Single file
$repo->uploadFile('config.json', json_encode($config));
$repo->uploadFile('model.bin', '/local/path/model.bin');

// Multiple files
$repo->uploadFiles([
    'config.json' => json_encode($config),
    'model.bin' => '/local/path/model.bin',
]);

$repo->commit('Add model files')
    ->addFile('config.json', json_encode($config))
    ->addFile('model.bin', '/local/path/model.bin')
    ->addFile('readme.md', fopen('readme.md', 'r'))
    ->push();

$repo = $hub->repo('username/my-model');

// Single file
$repo->deleteFile('old-file.txt');

// Multiple files
$repo->deleteFiles(['file1.txt', 'file2.txt']);

// Combined with uploads
$repo->commit('Update files')
    ->addFile('new.json', $content)
    ->deleteFile('old.json')
    ->push();

$repo = $hub->repo('bert-base-uncased');

$commits = $repo->commits(batchSize: 50);

foreach ($commits as $commit) {
    echo $commit->commit->title;
    echo $commit->commit->date;
}

$totalCommits = $repo->commitCount();

$collections = $hub->collections()
    ->search('bert')
    ->owner('huggingface')
    ->limit(10)
    ->get();

foreach ($collections as $collection) {
    echo "{$collection->title} ({$collection->slug})\n";
}

$collection = $hub->createCollection('My Favorite Models')
    ->description('A curated list of awesome models')
    ->private()
    ->save();

use Codewithkyrian\HuggingFace\Enums\CollectionItemType;

$collection = $hub->collection('my-collection-slug');

$info = $collection->info();

$collection->addItem('bert-base-uncased', CollectionItemType::Model, note: 'Great for NLP');
$collection->deleteItem('item-object-id');
$collection->delete();

use Codewithkyrian\HuggingFace\Enums\SortField;

$models = $hub->models()
    ->search('sentiment')
    ->task('text-classification')
    ->library('transformers')
    ->author('huggingface')
    ->language('en')
    ->sort(SortField::Downloads)
    ->descending()
    ->limit(20)
    ->get();

foreach ($models as $model) {
    echo "{$model->id}: {$model->downloads} downloads\n";
}

$datasets = $hub->datasets()
    ->search('summarization')
    ->author('huggingface')
    ->limit(10)
    ->get();

foreach ($datasets as $dataset) {
    echo $dataset->id;
}

$spaces = $hub->spaces()
    ->search('gradio')
    ->limit(10)
    ->get();

foreach ($spaces as $space) {
    echo "{$space->id} ({$space->sdk})\n";
}

use Codewithkyrian\HuggingFace\Inference\Enums\InferenceProvider;

// Default: Auto resolved
$inference = $hf->inference();

// External provider (enum)
$inference = $hf->inference(InferenceProvider::Together);

// External provider (string slug)
$inference = $hf->inference('groq');
$inference = $hf->inference('nebius');

// Custom endpoint URL
$inference = $hf->inference('https://your-endpoint.huggingface.cloud');

$chat = $hf->inference(InferenceProvider::Together)
    ->billTo('my-org-id')
    ->chatCompletion('meta-llama/Llama-3.1-8B-Instruct');

$chat = $hf->inference()->chatCompletion('meta-llama/Llama-3.1-8B-Instruct');

$response = $chat
    ->system('You are a helpful assistant.')
    ->user('What is PHP?')
    ->maxTokens(200)
    ->generate();

echo $response->content();
echo $response->finishReason(); // "stop", "length", etc.

$response = $chat
    ->system('You are a coding tutor.')
    ->user('What is a variable?')
    ->assistant('A variable is a named container that stores a value.')
    ->user('Give me a PHP example.')
    ->generate();

$stream = $chat
    ->system('You are a storyteller.')
    ->user('Tell me a short story.')
    ->maxTokens(500)
    ->stream();

foreach ($stream as $chunk) {
    echo $chunk->choices[0]->delta->content ?? '';
}

$generator = $hf->inference()->textGeneration('gpt2');

$response = $generator
    ->maxNewTokens(100)
    ->temperature(0.7)
    ->execute('The future of AI is');

echo $response->generatedText;

$embedder = $hf->inference()->featureExtraction('sentence-transformers/all-MiniLM-L6-v2');

// Single text
$embedding = $embedder->execute('Hello world');
echo count($embedding); // e.g., 384 dimensions

// Batch processing
$embeddings = $embedder->execute([
    'First sentence',
    'Second sentence',
    'Third sentence',
]);

$classifier = $hf->inference()->textClassification('distilbert-base-uncased-finetuned-sst-2-english');

$results = $classifier->execute('I absolutely love this product!');

foreach ($results as $result) {
    echo "{$result->label}: " . round($result->score * 100, 2) . "%\n";
}
// POSITIVE: 99.87%
// NEGATIVE: 0.13%

use Codewithkyrian\HuggingFace\Inference\Enums\AggregationStrategy;

$ner = $hf->inference()->tokenClassification('dbmdz/bert-large-cased-finetuned-conll03-english');

$results = $ner
    ->aggregationStrategy(AggregationStrategy::Simple)
    ->execute('My name is Sarah and I live in London');

foreach ($results as $result) {
    echo "{$result->word}: {$result->entityGroup} ({$result->score})\n";
}
// Sarah: PER (0.99)
// London: LOC (0.99)

$summarizer = $hf->inference()->summarization('facebook/bart-large-cnn');

$result = $summarizer
    ->maxLength(130)
    ->minLength(30)
    ->execute($longArticle);

echo $result->summaryText;

$qa = $hf->inference()->questionAnswering('deepset/roberta-base-squad2');

$context = "PHP was created by Rasmus Lerdorf in 1994.";

$result = $qa->execute('Who created PHP?', $context);

echo $result->answer;  // "Rasmus Lerdorf"
echo $result->score;   // Confidence score
echo $result->start;   // Start position in context
echo $result->end;     // End position in context

$translator = $hf->inference()->translation('Helsinki-NLP/opus-mt-en-fr');

$result = $translator->execute('Hello, how are you?');

echo $result->translationText; // "Bonjour, comment allez-vous?"

$mask = $hf->inference()->fillMask('bert-base-uncased');

$results = $mask->execute('Paris is the [MASK] of France.');

foreach ($results as $result) {
    echo "{$result->tokenStr}: " . round($result->score * 100, 2) . "%\n";
    echo "  → {$result->sequence}\n";
}
// capital: 85.42%
//   → paris is the capital of france.

$similarity = $hf->inference()->sentenceSimilarity('sentence-transformers/all-MiniLM-L6-v2');

$scores = $similarity->execute(
    'I love cats',
    ['I love dogs', 'I hate cats', 'The weather is nice']
);

// $scores = [0.92, 0.45, 0.12]

$imageGen = $hf->inference()->textToImage('black-forest-labs/FLUX.1-schnell');

$imageData = $imageGen
    ->numInferenceSteps(20)
    ->guidanceScale(7.5)
    ->execute('A serene lake surrounded by mountains at sunset');

file_put_contents('output.png', $imageData);

// Or save directly
$imageGen->save('A beautiful sunset', 'sunset.png');

$classifier = $hf->inference()->imageClassification('google/vit-base-patch16-224');

// From URL
$results = $classifier->execute('https://example.com/cat.jpg');

// From base64
$results = $classifier->execute(base64_encode(file_get_contents('cat.jpg')));

foreach ($results as $result) {
    echo "{$result->label}: " . round($result->score * 100, 2) . "%\n";
}

$detector = $hf->inference()->objectDetection('facebook/detr-resnet-50');

// From URL or file path
$results = $detector->execute('https://example.com/photo.jpg');

foreach ($results as $result) {
    echo "Label: {$result->label}, Score: " . round($result->score, 4) . "\n";
    echo "Box: [{$result->box->xmin}, {$result->box->ymin}, {$result->box->xmax}, {$result->box->ymax}]\n";
}

$captioner = $hf->inference()->imageToText('Salesforce/blip-image-captioning-base');

$result = $captioner->execute('https://example.com/photo.jpg');

echo $result->generatedText; // "a dog playing in the park"

$tts = $hf->inference()->textToSpeech('espnet/kan-bayashi_ljspeech_vits');

$audioData = $tts->execute('Hello, how are you today?');

file_put_contents('output.wav', $audioData);

// Or save directly
$tts->save('Hello world', 'greeting.wav');

$transcriber = $hf->inference()->automaticSpeechRecognition('openai/whisper-large-v3');

// From file path
$result = $transcriber->execute('/path/to/audio.mp3');

// From base64 data
$result = $transcriber->execute('data:audio/mpeg;base64,...');

echo $result->text;

$zeroShot = $hf->inference()->zeroShotClassification('facebook/bart-large-mnli');

$results = $zeroShot->execute(
    'I need to book a flight to New York',
    ['travel', 'finance', 'technology', 'sports']
);

foreach ($results as $result) {
    echo "{$result->label}: " . round($result->score * 100, 2) . "%\n";
}

// List all cached repositories
$repos = $hf->cache()->list();
foreach ($repos as $repo) {
    echo "{$repo['id']} ({$repo['type']}): " . round($repo['size'] / 1024 / 1024, 2) . " MB\n";
}

// Delete a specific repository (frees up space)
$hf->cache()->delete('google/bert-base-uncased');

// Clear the entire cache (use with caution!)
$hf->cache()->clear();

$hf = HuggingFace::factory()
    ->withToken('token')
    ->withCacheDir('/custom/cache/path')
    ->make();

// Download single file to cache
$cachedPath = $hub->repo('model')
    ->download('config.json')
    ->save();

// Check if file is cached
$isCached = $hub->repo('model')
    ->isCached('config.json');

// Get cached file path
$cachedPath = $hub->repo('model')
    ->getCachedPath('config.json');

$content = $hub->repo('model')
    ->download('file.bin')
    ->useCache(false)
    ->getContent();

$content = $hub->repo('model')
    ->download('file.bin')
    ->force()
    ->getContent();

use Codewithkyrian\HuggingFace\Exceptions\{
    HuggingFaceException,
    AuthenticationException,
    RateLimitException,
    NotFoundException,
    ApiException,
    NetworkException
};

try {
    $modelInfo = $hf->hub()->modelInfo('gp2');
} catch (AuthenticationException $e) {
    // Invalid or expired token
    echo "Auth error: " . $e->getMessage();
} catch (RateLimitException $e) {
    // Too many requests
    echo "Rate limited. Retry after: " . $e->retryAfter . " seconds";
} catch (NotFoundException $e) {
    // Model or resource not found
    echo "Not found: " . $e->getMessage();
} catch (NetworkException $e) {
    // Connection issues
    echo "Network error: " . $e->getMessage();
} catch (ApiException $e) {
    // Other API errors
    echo "API error ({$e->statusCode}): " . $e->getMessage();
}
bash
HF_TOKEN=your_token php examples/inference/chat_completion.php

php examples/hub/search.php