ccocks-deca commited on
Commit
41bddaf
·
verified ·
1 Parent(s): 1ff4499

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -25
app.py CHANGED
@@ -1,41 +1,66 @@
1
  import gradio as gr
2
  from sentence_transformers import SentenceTransformer
 
3
 
4
- # Load a fast, high-quality embedding model (runs great on CPU or GPU)
5
- model = SentenceTransformer("all-MiniLM-L6-v2") # 22M params, ~80 MB
6
- # Alternatives: "BAAI/bge-small-en-v1.5", "nomic-ai/nomic-embed-text-v1", etc.
 
 
 
 
 
 
 
7
 
8
- def generate_embeddings(texts: str):
9
- """Accepts one text per line (batch) or a single sentence."""
10
- # Split by lines for easy batching
11
  lines = [line.strip() for line in texts.split("\n") if line.strip()]
12
  if not lines:
13
- return {"embeddings": [], "texts": []}
14
-
15
- # Generate embeddings (automatically batched)
16
- embeddings = model.encode(lines, convert_to_numpy=True).tolist()
17
-
 
 
 
 
 
 
 
18
  return {
19
- "embeddings": embeddings, # list of lists of floats
20
- "texts": lines
 
 
21
  }
22
 
23
- # Gradio interface (provides both a nice UI for testing + the full API)
 
24
  demo = gr.Interface(
25
  fn=generate_embeddings,
26
- inputs=gr.Textbox(
27
- lines=8,
28
- placeholder="Enter one text per line for batch embedding...\n\nThe quick brown fox jumps over the lazy dog.",
29
- label="Input Texts"
30
- ),
31
- outputs=gr.JSON(label="Embeddings"),
32
- title="🔥 Free Embedding API",
33
- description="Powered by sentence-transformers on Hugging Face Spaces. Returns 384-dimensional embeddings (MiniLM).",
 
 
 
 
 
 
 
 
34
  examples=[
35
- ["The quick brown fox jumps over the lazy dog."],
36
- ["Hello world!\nThis is a second sentence."]
37
  ],
38
- allow_flagging="never"
39
  )
40
 
41
  demo.launch()
 
1
  import gradio as gr
2
  from sentence_transformers import SentenceTransformer
3
+ import torch
4
 
5
+ # Load Qwen3-Embedding-4B (best performance on GPU)
6
+ model = SentenceTransformer(
7
+ "Qwen/Qwen3-Embedding-4B",
8
+ model_kwargs={
9
+ "attn_implementation": "flash_attention_2", # recommended for speed + lower VRAM
10
+ "device_map": "auto",
11
+ "torch_dtype": torch.float16, # halves memory usage
12
+ },
13
+ tokenizer_kwargs={"padding_side": "left"},
14
+ )
15
 
16
+ def generate_embeddings(texts: str, use_query_mode: bool):
17
+ """One text per line. Returns 2560-dim embeddings."""
 
18
  lines = [line.strip() for line in texts.split("\n") if line.strip()]
19
  if not lines:
20
+ return {"embeddings": [], "texts": [], "dimension": 2560}
21
+
22
+ # Use "query" prompt for better retrieval performance (adds instruction internally)
23
+ prompt_name = "query" if use_query_mode else None
24
+
25
+ embeddings = model.encode(
26
+ lines,
27
+ prompt_name=prompt_name,
28
+ convert_to_numpy=True,
29
+ normalize_embeddings=True, # cosine-ready vectors
30
+ ).tolist()
31
+
32
  return {
33
+ "embeddings": embeddings, # list of lists (2560 floats each)
34
+ "texts": lines,
35
+ "dimension": len(embeddings[0]) if embeddings else 2560,
36
+ "mode": "query (with instruction)" if use_query_mode else "document (raw)",
37
  }
38
 
39
+
40
+ # Gradio UI + automatic REST API
41
  demo = gr.Interface(
42
  fn=generate_embeddings,
43
+ inputs=[
44
+ gr.Textbox(
45
+ lines=10,
46
+ placeholder="Paste one text per line...\n\nThe capital of France is Paris.\nExplain quantum entanglement.",
47
+ label="Input Texts (one per line)",
48
+ ),
49
+ gr.Checkbox(
50
+ label="Use Query Mode (recommended for search/retrieval)",
51
+ value=True,
52
+ info="Adds task-specific instruction automatically for much better results",
53
+ ),
54
+ ],
55
+ outputs=gr.JSON(label="Embedding Response"),
56
+ title="🚀 Qwen3-Embedding-4B API",
57
+ description="""State-of-the-art 4B embedding model (2560-dim, 32k context, 100+ languages).
58
+ Powered by Qwen/Qwen3-Embedding-4B on Hugging Face Spaces.""",
59
  examples=[
60
+ ["What is the capital of China?\nExplain gravity", True],
61
+ ["The capital of China is Beijing.\nGravity is a force...", False],
62
  ],
63
+ allow_flagging="never",
64
  )
65
 
66
  demo.launch()