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
// 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);
$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;
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)
$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');
$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();