Shridhartd commited on
Commit
0591939
·
verified ·
1 Parent(s): 3537c36

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -19
app.py CHANGED
@@ -1,27 +1,49 @@
1
- from fastapi import FastAPI, UploadFile, File
2
- import shutil
3
  import os
4
- from image_caption import generate_caption
 
 
 
 
 
 
 
 
 
5
 
6
  app = FastAPI()
7
 
8
- UPLOAD_DIR = "uploads"
9
- os.makedirs(UPLOAD_DIR, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
- @app.post("/upload-image/")
12
- async def upload_image(file: UploadFile = File(...)):
13
- """Endpoint to accept image and return generated caption"""
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
- # Generate caption
21
- caption = generate_caption(file_path)
 
22
 
23
- return {"filename": file.filename, "caption": caption}
 
 
 
 
 
24
 
25
- @app.get("/")
26
- async def root():
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)