Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,27 +1,49 @@
|
|
| 1 |
-
from fastapi import FastAPI, UploadFile, File
|
| 2 |
-
import shutil
|
| 3 |
import os
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
app = FastAPI()
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
file_path = f"{UPLOAD_DIR}/{file.filename}"
|
| 15 |
-
|
| 16 |
-
# Save the uploaded file
|
| 17 |
-
with open(file_path, "wb") as buffer:
|
| 18 |
-
shutil.copyfileobj(file.file, buffer)
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
|
|
|
| 22 |
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
return {"message": "Image-to-Text API is running. Use /upload-image to send an image."}
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
|
| 3 |
+
os.environ["HF_HOME"] = "/tmp/huggingface"
|
| 4 |
+
os.makedirs("/tmp/huggingface", exist_ok=True)
|
| 5 |
+
from fastapi import FastAPI
|
| 6 |
+
from pydantic import BaseModel
|
| 7 |
+
import torch
|
| 8 |
+
import numpy as np
|
| 9 |
+
from transformers import AutoTokenizer, AutoModel
|
| 10 |
+
from sklearn.linear_model import LogisticRegression
|
| 11 |
+
import uvicorn
|
| 12 |
|
| 13 |
app = FastAPI()
|
| 14 |
|
| 15 |
+
# Load Hugging Face model
|
| 16 |
+
model_name = "bert-base-uncased"
|
| 17 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 18 |
+
model = AutoModel.from_pretrained(model_name)
|
| 19 |
+
|
| 20 |
+
# Function to get text embeddings
|
| 21 |
+
def get_embedding(text):
|
| 22 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
|
| 23 |
+
with torch.no_grad():
|
| 24 |
+
outputs = model(**inputs)
|
| 25 |
+
return outputs.last_hidden_state[:, 0, :].numpy()
|
| 26 |
+
|
| 27 |
+
# Sample dataset
|
| 28 |
+
texts = ["I love this!", "This is terrible.", "Fantastic experience!", "I hate it.", "Absolutely wonderful!", "Worst ever!"]
|
| 29 |
+
labels = [1, 0, 1, 0, 1, 0] # 1 = Positive, 0 = Negative
|
| 30 |
+
X = np.vstack([get_embedding(text) for text in texts])
|
| 31 |
+
y = np.array(labels)
|
| 32 |
|
| 33 |
+
# Train model
|
| 34 |
+
clf = LogisticRegression()
|
| 35 |
+
clf.fit(X, y)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
# Define request format
|
| 38 |
+
class InputText(BaseModel):
|
| 39 |
+
text: str
|
| 40 |
|
| 41 |
+
@app.post("/predict")
|
| 42 |
+
def predict_sentiment(data: InputText):
|
| 43 |
+
user_embedding = get_embedding(data.text)
|
| 44 |
+
prediction = clf.predict(user_embedding)
|
| 45 |
+
sentiment = "Positive 😊" if prediction[0] == 1 else "Negative 😡"
|
| 46 |
+
return {"sentiment": sentiment}
|
| 47 |
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|