Sysnern commited on
Commit
bc916a6
·
0 Parent(s):

Initial commit with LFS

Browse files
Files changed (5) hide show
  1. .gitattributes +1 -0
  2. Dockerfile +26 -0
  3. requirements.txt +5 -0
  4. sentence_best_model 2.bin +3 -0
  5. server.py +77 -0
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.bin filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ # Root kullanıcısı olarak sistem bağımlılıklarını kur
4
+ RUN apt-get update && apt-get install -y --no-install-recommends \
5
+ build-essential \
6
+ && rm -rf /var/lib/apt/lists/*
7
+
8
+ # Hugging Face Spaces için gerekli olan yetkisiz (non-root) kullanıcıyı oluştur
9
+ RUN useradd -m -u 1000 user
10
+ USER user
11
+ ENV PATH="/home/user/.local/bin:$PATH"
12
+
13
+ WORKDIR /app
14
+
15
+ # Dosyaları kullanıcı yetkisiyle kopyala ve Python paketlerini kur
16
+ COPY --chown=user ./requirements.txt requirements.txt
17
+ RUN pip install --no-cache-dir -r requirements.txt --extra-index-url https://download.pytorch.org/whl/cpu
18
+
19
+ # Geri kalan uygulama dosyalarını kopyala
20
+ COPY --chown=user . /app
21
+
22
+ # Hugging Face zorunlu portu
23
+ EXPOSE 7860
24
+
25
+ # FastAPI'yi başlat
26
+ CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "7860"]
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi==0.115.12
2
+ uvicorn[standard]==0.34.3
3
+ torch==2.7.0
4
+ transformers==4.52.3
5
+ pydantic==2.11.3
sentence_best_model 2.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:38a82177f44021ee1426f470147f0aa7a5a7ff211277748ba316f252e61ad166
3
+ size 442655265
server.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
+ import torch
5
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoConfig
6
+
7
+ app = FastAPI()
8
+
9
+ app.add_middleware(
10
+ CORSMiddleware,
11
+ allow_origins=["*"],
12
+ allow_credentials=False,
13
+ allow_methods=["*"],
14
+ allow_headers=["*"],
15
+ )
16
+
17
+ class AnalyzeRequest(BaseModel):
18
+ text: str
19
+
20
+ # ---------------------------------------------------------
21
+ # BERTurk Duygu Analizi / Sınıflandırma Modeli
22
+ # ---------------------------------------------------------
23
+ MODEL_PATH = "sentence_best_model 2.bin"
24
+ BASE_MODEL_NAME = "dbmdz/bert-base-turkish-cased"
25
+
26
+ print("Model yükleniyor, lütfen bekleyin...")
27
+ try:
28
+ tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_NAME)
29
+
30
+ # Modelinizi eğitirken kelime dağarcığına (vocab) 30 adet yeni token eklemişsiniz.
31
+ # Orijinal BERTurk'ün vocab boyutu 32000 iken, sizin modelinizinki 32030 olmuş.
32
+ # Bu yüzden konfigürasyonda bunu belirtmemiz gerekiyor, yoksa çöker ve Nötr döner!
33
+ config = AutoConfig.from_pretrained(BASE_MODEL_NAME, num_labels=3, vocab_size=32030)
34
+
35
+ # Konfigürasyonla iskeleti oluşturuyoruz
36
+ model = AutoModelForSequenceClassification.from_config(config)
37
+
38
+ # Kendi eğittiğiniz ağırlıkları (.bin) içine yüklüyoruz
39
+ model.load_state_dict(torch.load(MODEL_PATH, map_location=torch.device('cpu'), weights_only=False))
40
+
41
+ model.eval()
42
+ print("Model başarıyla yüklendi!")
43
+ except Exception as e:
44
+ print(f"Model yüklenirken hata oluştu: {e}")
45
+ model = None
46
+ tokenizer = None
47
+
48
+
49
+ @app.post("/predict")
50
+ async def predict_sentiment(request: AnalyzeRequest):
51
+ """
52
+ Frontend'den gelen günlüğü okur ve duygu durumunu sınıflandırır.
53
+ """
54
+ if not model or not tokenizer:
55
+ return {"sentiment": "Neutral"}
56
+
57
+ inputs = tokenizer(request.text, return_tensors="pt", truncation=True, padding=True)
58
+ with torch.no_grad():
59
+ outputs = model(**inputs)
60
+ predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
61
+ predicted_class = torch.argmax(predictions, dim=-1).item()
62
+
63
+ # Sınıf numaralarını metne çevirme (Örnek: 0: Negative, 1: Neutral, 2: Positive)
64
+ # NOT: Kendi modelinizin label mapping'ine göre burayı değiştirebilirsiniz!
65
+ sentiment_map = {0: "Negative", 1: "Neutral", 2: "Positive"}
66
+ detected_sentiment = sentiment_map.get(predicted_class, "Neutral")
67
+
68
+ return {"sentiment": detected_sentiment}
69
+
70
+ @app.get("/health")
71
+ async def health_check():
72
+ """
73
+ Konteynerin ve modelin durumunu kontrol etmek için health endpoint.
74
+ """
75
+ if model and tokenizer:
76
+ return {"status": "healthy", "model_loaded": True}
77
+ return {"status": "degraded", "model_loaded": False, "message": "Model not loaded. Using fallback responses."}