File size: 6,418 Bytes
b98ed7e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
---
title: HF Inference API
emoji: πŸ€—
colorFrom: yellow
colorTo: pink
sdk: gradio
sdk_version: 6.2.0
app_file: app.py
pinned: false
license: mit
---

# Hugging Face Inference API

REST API and Gradio interface for Hugging Face model inference.

## Features

- **Two inference modes**: HF Inference API (lightweight) or local model loading
- **REST API**: FastAPI with automatic OpenAPI documentation
- **Gradio UI**: Web interface for interactive testing
- **HF Spaces ready**: Deploy directly to Hugging Face Spaces

## Quick Start

### 1. Installation

```bash
# Create virtual environment
python -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# For local model inference (optional)
pip install transformers torch

# Copy and configure environment
cp .env.example .env
```

### 2. Configure

Edit `.env` with your settings:

```bash
# Use HF Inference API (recommended)
HF_USE_API=true
HF_API_TOKEN=hf_xxxxxxxxxxxxx

# Or load models locally
HF_USE_API=false
```

### 3. Run

```bash
# Option A: REST API (FastAPI)
python -m app.main

# Option B: Gradio interface
python app.py
```

## Running Options

### REST API (FastAPI)

```bash
python -m app.main
```

- URL: http://localhost:8000
- Swagger: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc

### Gradio Interface

```bash
python app.py
```

- URL: http://localhost:7860

### Docker

```bash
# Build
docker build -t hf-inference-api .

# Run with HF API
docker run -p 8000:8000 \
  -e HF_USE_API=true \
  -e HF_API_TOKEN=hf_xxxxx \
  -e HF_MODEL_NAME=distilbert-base-uncased-finetuned-sst-2-english \
  hf-inference-api

# Run with local model
docker run -p 8000:8000 \
  -e HF_USE_API=false \
  -e HF_MODEL_NAME=distilbert-base-uncased-finetuned-sst-2-english \
  hf-inference-api
```

### Hugging Face Spaces

1. Create a new Space at https://huggingface.co/new-space
2. Select **Gradio** as SDK
3. Push these files:
   - `app.py`
   - `requirements.txt`
   - `app/` folder
4. Add `HF_API_TOKEN` in Space Settings > Secrets

## API Endpoints

### Health Check

```bash
curl http://localhost:8000/health
```

Response:
```json
{
  "status": "ok",
  "model_loaded": true,
  "model_name": "distilbert-base-uncased-finetuned-sst-2-english"
}
```

### Inference

```bash
curl -X POST http://localhost:8000/predict \
  -H "Content-Type: application/json" \
  -d '{"inputs": "I love this product!"}'
```

Response:
```json
{
  "predictions": [[{"label": "POSITIVE", "score": 0.9998}]],
  "model_name": "distilbert-base-uncased-finetuned-sst-2-english"
}
```

### Batch Inference

```bash
curl -X POST http://localhost:8000/predict \
  -H "Content-Type: application/json" \
  -d '{"inputs": ["I love this!", "This is terrible."]}'
```

### With Parameters

```bash
curl -X POST http://localhost:8000/predict \
  -H "Content-Type: application/json" \
  -d '{
    "inputs": "The capital of France is",
    "parameters": {"max_new_tokens": 50}
  }'
```

## Configuration

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `HF_USE_API` | `true` | Use HF Inference API (`true`) or local model (`false`) |
| `HF_API_TOKEN` | `None` | HF API token (required if `HF_USE_API=true`) |
| `HF_MODEL_NAME` | `cardiffnlp/twitter-roberta-base-sentiment-latest` | Hugging Face model ID |
| `HF_TASK` | `text-classification` | Pipeline task type |
| `HF_HOST` | `0.0.0.0` | Server host |
| `HF_PORT` | `8000` | Server port |
| `HF_DEVICE` | `cpu` | Device for local inference (`cpu`, `cuda`, `cuda:0`) |
| `HF_MAX_BATCH_SIZE` | `32` | Maximum batch size for local inference |

### Inference Modes

#### HF Inference API (Recommended)

```bash
HF_USE_API=true
HF_API_TOKEN=hf_xxxxxxxxxxxxx
```

Pros:
- No model download required
- Lightweight (no torch/transformers)
- Fast startup
- Free tier available

Cons:
- Requires internet connection
- Rate limits on free tier
- API token required

#### Local Model

```bash
HF_USE_API=false
```

Requires additional dependencies:
```bash
pip install transformers torch
```

Pros:
- No internet required after download
- No rate limits
- Full control

Cons:
- Large dependencies (~2GB for torch)
- Model download on first run
- More RAM/CPU required

## Supported Tasks

| Task | Description | Example Model |
|------|-------------|---------------|
| `text-classification` | Classify text into categories | `distilbert-base-uncased-finetuned-sst-2-english` |
| `sentiment-analysis` | Analyze sentiment (alias for text-classification) | `nlptown/bert-base-multilingual-uncased-sentiment` |
| `text-generation` | Generate text from prompt | `gpt2`, `mistralai/Mistral-7B-v0.1` |
| `summarization` | Summarize long text | `facebook/bart-large-cnn` |
| `translation` | Translate text | `Helsinki-NLP/opus-mt-en-fr` |
| `fill-mask` | Fill in masked tokens | `bert-base-uncased` |
| `question-answering` | Answer questions given context | `deepset/roberta-base-squad2` |
| `feature-extraction` | Extract embeddings | `sentence-transformers/all-MiniLM-L6-v2` |

## Project Structure

```
hf-inference-api/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ config.py        # Settings (pydantic-settings)
β”‚   β”œβ”€β”€ inference.py     # Inference engine (API + local)
β”‚   β”œβ”€β”€ main.py          # FastAPI application
β”‚   └── models.py        # Pydantic models
β”œβ”€β”€ app.py               # Gradio interface
β”œβ”€β”€ .env.example         # Environment template
β”œβ”€β”€ .gitignore
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ README.md
└── requirements.txt
```

## Examples

### Text Classification

```bash
HF_MODEL_NAME=distilbert-base-uncased-finetuned-sst-2-english
HF_TASK=text-classification
```

```bash
curl -X POST http://localhost:8000/predict \
  -d '{"inputs": "I love this movie!"}'
```

### Text Generation

```bash
HF_MODEL_NAME=gpt2
HF_TASK=text-generation
```

```bash
curl -X POST http://localhost:8000/predict \
  -d '{"inputs": "Once upon a time", "parameters": {"max_new_tokens": 50}}'
```

### Summarization

```bash
HF_MODEL_NAME=facebook/bart-large-cnn
HF_TASK=summarization
```

```bash
curl -X POST http://localhost:8000/predict \
  -d '{"inputs": "Long article text here..."}'
```

### Translation (EN -> FR)

```bash
HF_MODEL_NAME=Helsinki-NLP/opus-mt-en-fr
HF_TASK=translation
```

```bash
curl -X POST http://localhost:8000/predict \
  -d '{"inputs": "Hello, how are you?"}'
```