File size: 10,065 Bytes
e8f9d10
 
 
65c747d
b0cb394
 
 
65c747d
 
e8f9d10
 
65c747d
 
 
 
 
 
4252268
 
65c747d
 
 
 
 
e8f9d10
 
 
 
ea8754a
 
 
 
 
 
 
 
 
 
 
e8f9d10
 
1dc5abe
e8f9d10
ea8754a
65c747d
0f24792
ea8754a
9001620
ea8754a
9001620
ea8754a
9001620
 
 
 
 
ea8754a
9001620
ea8754a
 
 
073aa83
e8f9d10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86d6248
e8f9d10
 
 
 
b0cb394
86d6248
 
b0cb394
86d6248
 
b0cb394
 
86d6248
 
 
b0cb394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86d6248
 
e8f9d10
 
 
 
 
 
26238e1
de24ee4
 
 
 
e8f9d10
65c747d
 
977f802
e8f9d10
 
 
073aa83
0176b09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e86e8b
0176b09
e8f9d10
b0cb394
0176b09
86d6248
b0cb394
 
 
 
 
 
 
 
 
 
 
 
86d6248
 
e8f9d10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import requests
import json
import logging
import pandas as pd
from typing import Tuple

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from gradio.routes import mount_gradio_app


# Filter out /v1 requests from the access log
class LogFilter(logging.Filter):
    def filter(self, record):
        if record.args and len(record.args) >= 3:
            if "/v1" in str(record.args[2]):
                return True
        return False


logger = logging.getLogger("uvicorn.access")
logger.addFilter(LogFilter())

# Application metadata
__version__ = "1.0.0"
__author__ = "lamhieu"
__description__ = "Fast, lightweight, multilingual embeddings solution."
__metadata__ = {
    "project": "Lightweight Embeddings Service",
    "version": __version__,
    "description": (
        "Fast and efficient multilingual text and image embeddings service "
        "powered by sentence-transformers, supporting 100+ languages and multi-modal inputs"
    ),
    "docs": "https://lamhieu-lightweight-embeddings.hf.space/docs",
    "github": "https://github.com/lh0x00/lightweight-embeddings",
    "spaces": "https://huggingface.co/spaces/lamhieu/lightweight-embeddings",
}

# Set your embeddings API URL here (change host/port if needed)
EMBEDDINGS_API_URL = "http://localhost:7860/v1/embeddings"

# Markdown description for the main interface
APP_DESCRIPTION = f"""
# πŸš€ **Lightweight Embeddings API**  

The **Lightweight Embeddings API** is a fast, free, and multilingual service designed for generating embeddings and reranking with support for both **text** and **image** inputs.

### ✨ Features & Privacy

- **Free & Multilingual**: Unlimited API service supporting 100+ languages with no usage restrictions
- **Advanced Processing**: High-quality text and image-text embeddings using state-of-the-art models with reranking capabilities
- **Privacy-First**: No storage of input data (text/images), only anonymous usage statistics for service improvement
- **Production-Ready**: Docker deployment, interactive Gradio playground, and comprehensive REST API documentation
- **Open & Efficient**: Fully open-source codebase using lightweight transformer models for rapid inference

### πŸ”— Resources
- [Documentation]({__metadata__["docs"]}) | [GitHub]({__metadata__["github"]}) | [Playground]({__metadata__["spaces"]})
"""


# Initialize FastAPI application
app = FastAPI(
    title="Lightweight Embeddings API",
    description=__description__,
    version=__version__,
    docs_url="/docs",
    redoc_url="/redoc",
)

# Configure CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Adjust if needed for specific domains
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Include your existing router (which provides /v1/embeddings, /v1/rank, etc.)
from .router import router

app.include_router(router, prefix="/v1")


def call_embeddings_api(user_input: str, selected_model: str) -> str:
    """
    Send a request to the /v1/embeddings endpoint with the given model and input.
    Return a pretty-printed JSON response or an error message.
    """
    payload = {
        "model": selected_model,
        "input": user_input,
    }
    headers = {"Content-Type": "application/json"}

    try:
        response = requests.post(
            EMBEDDINGS_API_URL, json=payload, headers=headers, timeout=20
        )
    except requests.exceptions.RequestException as e:
        return f"❌ Network Error: {str(e)}"

    if response.status_code != 200:
        # Provide detailed error message
        return f"❌ API Error {response.status_code}: {response.text}"

    try:
        data = response.json()
        return json.dumps(data, indent=2, ensure_ascii=False)
    except ValueError:
        return "❌ Failed to parse JSON from API response."


def call_stats_api_df() -> Tuple[pd.DataFrame, pd.DataFrame]:
    """
    Calls the /v1/stats endpoint to retrieve analytics data.
    Returns two DataFrames (access_df, tokens_df) constructed from the JSON response.
    """
    url = "https://lamhieu-lightweight-embeddings.hf.space/v1/stats"

    # Fetch stats
    response = requests.get(url)
    if response.status_code != 200:
        raise ValueError(f"Failed to fetch stats: {response.text}")

    data = response.json()
    access_data = data["access"]
    tokens_data = data["tokens"]

    def build_stats_df(bucket: dict) -> pd.DataFrame:
        """
        Helper to build a DataFrame with columns: Model, total, daily, weekly, monthly, yearly.
        bucket is a dictionary like data["access"] or data["tokens"] in the stats response.
        """
        all_models = set()
        for time_range in ["total", "daily", "weekly", "monthly", "yearly"]:
            all_models.update(bucket[time_range].keys())

        # Prepare a data structure for DataFrame creation
        result_dict = {
            "Model": [],
            "Total": [],
            "Daily": [],
            "Weekly": [],
            "Monthly": [],
            "Yearly": [],
        }

        for model in sorted(all_models):
            result_dict["Model"].append(model)
            result_dict["Total"].append(bucket["total"].get(model, 0))
            result_dict["Daily"].append(bucket["daily"].get(model, 0))
            result_dict["Weekly"].append(bucket["weekly"].get(model, 0))
            result_dict["Monthly"].append(bucket["monthly"].get(model, 0))
            result_dict["Yearly"].append(bucket["yearly"].get(model, 0))

        df = pd.DataFrame(result_dict)
        return df

    access_df = build_stats_df(access_data)
    tokens_df = build_stats_df(tokens_data)
    return access_df, tokens_df


def create_main_interface():
    """
    Creates a Gradio Blocks interface showing project info and an embeddings playground.
    """
    # Available model options for the dropdown
    model_options = [
        "snowflake-arctic-embed-l-v2.0",
        "bge-m3",
        "gte-multilingual-base",
        "paraphrase-multilingual-MiniLM-L12-v2",
        "paraphrase-multilingual-mpnet-base-v2",
        "multilingual-e5-small",
        "multilingual-e5-base",
        "multilingual-e5-large",
        "siglip-base-patch16-256-multilingual",
    ]

    with gr.Blocks(title="Lightweight Embeddings", theme="default") as demo:
        gr.Markdown(APP_DESCRIPTION)
        with gr.Tab("Embeddings Playground"):
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### πŸ”¬ Try the Embeddings Playground")
                    input_text = gr.Textbox(
                        label="Input Text or Image URL",
                        placeholder="Enter text or an image URL...",
                        lines=3,
                    )
                    model_dropdown = gr.Dropdown(
                        choices=model_options,
                        value=model_options[0],
                        label="Select Model",
                    )
                    generate_btn = gr.Button("Generate Embeddings")
                    output_json = gr.Textbox(
                        label="Embeddings API Response",
                        lines=10,
                        interactive=False,
                    )

                    generate_btn.click(
                        fn=call_embeddings_api,
                        inputs=[input_text, model_dropdown],
                        outputs=output_json,
                    )

                with gr.Column():
                    gr.Markdown(
                        """
                    ### πŸ› οΈ cURL Examples

                    **Generate Embeddings (OpenAI compatible)**
                    ```bash
                    curl -X 'POST' \\
                      'https://lamhieu-lightweight-embeddings.hf.space/v1/embeddings' \\
                      -H 'accept: application/json' \\
                      -H 'Content-Type: application/json' \\
                      -d '{
                      "model": "snowflake-arctic-embed-l-v2.0",
                      "input": "That is a happy person"
                    }'
                    ```

                    **Perform Ranking**
                    ```bash
                    curl -X 'POST' \\
                      'https://lamhieu-lightweight-embeddings.hf.space/v1/rank' \\
                      -H 'accept: application/json' \\
                      -H 'Content-Type: application/json' \\
                      -d '{
                      "model": "snowflake-arctic-embed-l-v2.0",
                      "queries": "That is a happy person",
                      "candidates": [
                        "That is a happy dog",
                        "That is a very happy person",
                        "Today is a sunny day"
                      ]
                    }'
                    ```
                    """
                    )

        # STATS SECTION: display stats in tables
        with gr.Tab("Analytics Stats"):
            stats_btn = gr.Button("Get Stats")
            access_df = gr.DataFrame(
                label="Access Stats",
                headers=["Model", "Total", "Daily", "Weekly", "Monthly", "Yearly"],
                interactive=False,
            )
            tokens_df = gr.DataFrame(
                label="Token Stats",
                headers=["Model", "Total", "Daily", "Weekly", "Monthly", "Yearly"],
                interactive=False,
            )
            stats_btn.click(
                fn=call_stats_api_df, inputs=[], outputs=[access_df, tokens_df]
            )

    return demo


# Create and mount the Gradio Blocks at the root path
main_interface = create_main_interface()
mount_gradio_app(app, main_interface, path="/")


# Startup and shutdown events
@app.on_event("startup")
async def startup_event():
    """
    Initialize resources (like model loading) when the application starts.
    """
    pass


@app.on_event("shutdown")
async def shutdown_event():
    """
    Perform cleanup before the application shuts down.
    """
    pass