Spaces:
Sleeping
Sleeping
added project
Browse files- Dockerfile +22 -0
- main.py +123 -0
- requirements.txt +6 -0
- sms_process_data_main.xlsx +0 -0
Dockerfile
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM python:3.9
|
2 |
+
|
3 |
+
WORKDIR /app
|
4 |
+
COPY . /app
|
5 |
+
|
6 |
+
ENV HF_HOME=/app/.cache
|
7 |
+
|
8 |
+
RUN mkdir -p /app/.cache/huggingface/hub && \
|
9 |
+
chmod -R 777 /app/.cache && \
|
10 |
+
chmod -R 777 /app/.cache/huggingface
|
11 |
+
|
12 |
+
|
13 |
+
|
14 |
+
RUN pip install --upgrade pip
|
15 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
16 |
+
|
17 |
+
COPY --chown=user ./requirements.txt requirements.txt
|
18 |
+
RUN pip install --no-cache-dir --upgrade -r requirements.txt
|
19 |
+
|
20 |
+
EXPOSE 7860
|
21 |
+
|
22 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
main.py
ADDED
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, HTTPException
|
2 |
+
from pydantic import BaseModel
|
3 |
+
from sentence_transformers import SentenceTransformer,util
|
4 |
+
from sklearn.model_selection import train_test_split
|
5 |
+
from sklearn.linear_model import LogisticRegression
|
6 |
+
from fastapi.middleware.cors import CORSMiddleware
|
7 |
+
import uvicorn
|
8 |
+
import numpy as np
|
9 |
+
import pandas as pd
|
10 |
+
|
11 |
+
app = FastAPI()
|
12 |
+
|
13 |
+
app.add_middleware(
|
14 |
+
CORSMiddleware,
|
15 |
+
allow_origins=["*"], # Allow all origins; restrict this in production
|
16 |
+
allow_credentials=True,
|
17 |
+
allow_methods=["*"], # Allow all HTTP methods
|
18 |
+
allow_headers=["*"], # Allow all HTTP headers
|
19 |
+
)
|
20 |
+
|
21 |
+
|
22 |
+
# Initialize the FastAPI app
|
23 |
+
|
24 |
+
|
25 |
+
# Load the pre-trained SentenceTransformer model
|
26 |
+
model = SentenceTransformer("Alibaba-NLP/gte-base-en-v1.5", trust_remote_code=True)
|
27 |
+
|
28 |
+
# Define the request body schema
|
29 |
+
class TextInput(BaseModel):
|
30 |
+
text: str
|
31 |
+
|
32 |
+
# Home route
|
33 |
+
@app.get("/")
|
34 |
+
async def home():
|
35 |
+
return {"message": "welcome to home page"}
|
36 |
+
|
37 |
+
# Define the API endpoint for generating embeddings
|
38 |
+
@app.post("/embed")
|
39 |
+
async def generate_embedding(text_input: TextInput):
|
40 |
+
"""
|
41 |
+
Generate a 768-dimensional embedding for the input text.
|
42 |
+
Returns the embedding in a structured format with rounded values.
|
43 |
+
"""
|
44 |
+
try:
|
45 |
+
# Generate the embedding
|
46 |
+
embedding = model.encode(text_input.text, convert_to_tensor=True).cpu().numpy()
|
47 |
+
|
48 |
+
# Round embedding values to 2 decimal places
|
49 |
+
rounded_embedding = np.round(embedding, 2).tolist()
|
50 |
+
|
51 |
+
# Return structured response
|
52 |
+
return {
|
53 |
+
"dimensions": len(rounded_embedding),
|
54 |
+
"embeddings": [rounded_embedding]
|
55 |
+
}
|
56 |
+
|
57 |
+
except Exception as e:
|
58 |
+
# Handle any errors
|
59 |
+
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
|
60 |
+
|
61 |
+
|
62 |
+
|
63 |
+
model = SentenceTransformer("Alibaba-NLP/gte-base-en-v1.5", trust_remote_code=True)
|
64 |
+
df = pd.read_excel("sms_process_data_main.xlsx")
|
65 |
+
|
66 |
+
# Split the data into training and testing sets
|
67 |
+
X_train, X_test, y_train, y_test = train_test_split(df["MessageText"], df["label"], test_size=0.2, random_state=42)
|
68 |
+
|
69 |
+
# Generate embeddings for the training data
|
70 |
+
X_train_embeddings = model.encode(X_train.tolist(), show_progress_bar=True)
|
71 |
+
|
72 |
+
# Initialize and train the Logistic Regression model
|
73 |
+
logreg_model = LogisticRegression(max_iter=100)
|
74 |
+
logreg_model.fit(X_train_embeddings, y_train)
|
75 |
+
|
76 |
+
# Define input schema
|
77 |
+
class TextInput(BaseModel):
|
78 |
+
text: str
|
79 |
+
|
80 |
+
@app.post("/prediction")
|
81 |
+
async def generate_prediction(text_input: TextInput):
|
82 |
+
"""
|
83 |
+
Predict the label for the given text input using the trained model.
|
84 |
+
"""
|
85 |
+
try:
|
86 |
+
# Check if input text is provided
|
87 |
+
if not text_input.text.strip():
|
88 |
+
raise ValueError("Input text cannot be empty.")
|
89 |
+
|
90 |
+
# Generate embedding for the input text
|
91 |
+
new_embedding = model.encode([text_input.text])
|
92 |
+
|
93 |
+
# Predict the label using the trained Logistic Regression model
|
94 |
+
prediction = logreg_model.predict(new_embedding).tolist()[0] # Extract single prediction
|
95 |
+
|
96 |
+
# Return structured response
|
97 |
+
return {
|
98 |
+
"predicted_label": prediction
|
99 |
+
}
|
100 |
+
except ValueError as ve:
|
101 |
+
raise HTTPException(status_code=400, detail=str(ve))
|
102 |
+
except Exception as e:
|
103 |
+
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
|
104 |
+
|
105 |
+
class SentencesInput(BaseModel):
|
106 |
+
sentence1: str
|
107 |
+
sentence2: str
|
108 |
+
@app.post("/text_to_tensor")
|
109 |
+
def text_to_tensor(input: SentencesInput):
|
110 |
+
try:
|
111 |
+
# Generate embeddings
|
112 |
+
embeddings = model.encode([input.sentence1, input.sentence2])
|
113 |
+
|
114 |
+
# Compute cosine similarity
|
115 |
+
cosine_similarity = util.cos_sim(embeddings[0], embeddings[1]).item()
|
116 |
+
|
117 |
+
return {"cosine_similarity": round(cosine_similarity, 3)}
|
118 |
+
except Exception as e:
|
119 |
+
raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")
|
120 |
+
|
121 |
+
|
122 |
+
if __name__ == "__main__":
|
123 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
requirements.txt
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
fastapi[standard]
|
2 |
+
pandas
|
3 |
+
scikit-learn
|
4 |
+
joblib
|
5 |
+
uvicorn
|
6 |
+
sentence-transformers
|
sms_process_data_main.xlsx
ADDED
Binary file (49.3 kB). View file
|
|