Spaces:
Runtime error
Runtime error
Upload 2 files
Browse files- app.py +45 -0
- requirements.txt +4 -0
app.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sentence_transformers import SentenceTransformer
|
| 2 |
+
from flask import Flask, request, jsonify
|
| 3 |
+
from flask_cors import CORS # Import CORS
|
| 4 |
+
|
| 5 |
+
app = Flask(__name__)
|
| 6 |
+
CORS(app) # Enable CORS for all routes
|
| 7 |
+
|
| 8 |
+
# Load the model once when the application starts
|
| 9 |
+
# This is efficient as it avoids reloading on every request.
|
| 10 |
+
print("Loading sentence-transformer model...")
|
| 11 |
+
model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
| 12 |
+
print("Model loaded successfully.")
|
| 13 |
+
|
| 14 |
+
@app.route('/', methods=['GET'])
|
| 15 |
+
def health_check():
|
| 16 |
+
"""A simple endpoint to check if the service is running."""
|
| 17 |
+
return jsonify({
|
| 18 |
+
'status': 'ok',
|
| 19 |
+
'model': 'sentence-transformers/all-MiniLM-L6-v2'
|
| 20 |
+
})
|
| 21 |
+
|
| 22 |
+
@app.route('/embed', methods=['POST'])
|
| 23 |
+
def embed_text():
|
| 24 |
+
"""The main endpoint to generate embeddings."""
|
| 25 |
+
data = request.json
|
| 26 |
+
if not data or 'text' not in data:
|
| 27 |
+
return jsonify({'error': 'No text provided in JSON body'}), 400
|
| 28 |
+
|
| 29 |
+
text = data.get('text')
|
| 30 |
+
|
| 31 |
+
if not isinstance(text, str) or not text.strip():
|
| 32 |
+
return jsonify({'error': 'Text must be a non-empty string'}), 400
|
| 33 |
+
|
| 34 |
+
try:
|
| 35 |
+
# Generate embedding
|
| 36 |
+
embedding = model.encode(text) # No need to wrap in a list for a single string
|
| 37 |
+
|
| 38 |
+
return jsonify({
|
| 39 |
+
'embedding': embedding.tolist(),
|
| 40 |
+
'model': 'all-MiniLM-L6-v2',
|
| 41 |
+
'dimension': len(embedding)
|
| 42 |
+
})
|
| 43 |
+
except Exception as e:
|
| 44 |
+
print(f"Error during embedding: {e}")
|
| 45 |
+
return jsonify({'error': 'Failed to generate embedding'}), 500
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask
|
| 2 |
+
sentence-transformers
|
| 3 |
+
torch
|
| 4 |
+
flask-cors
|