Upload folder using huggingface_hub
Browse files- Dockerfile +12 -0
- handler.py +236 -0
- requirements.txt +11 -0
Dockerfile
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 7 |
+
|
| 8 |
+
COPY handler.py .
|
| 9 |
+
|
| 10 |
+
EXPOSE 7861
|
| 11 |
+
|
| 12 |
+
CMD ["python", "handler.py"]
|
handler.py
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Text Feature Extraction β Hugging Face Inference Endpoint Handler
|
| 3 |
+
|
| 4 |
+
Extracts all 9 text features from conversation transcript:
|
| 5 |
+
t0_explicit_free, t1_explicit_busy, t2_avg_resp_len, t3_short_ratio,
|
| 6 |
+
t4_cognitive_load, t5_time_pressure, t6_deflection, t7_sentiment,
|
| 7 |
+
t8_coherence, t9_latency
|
| 8 |
+
|
| 9 |
+
Derived from: src/text_features.py
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import re
|
| 13 |
+
import numpy as np
|
| 14 |
+
from typing import List, Dict
|
| 15 |
+
from transformers import pipeline
|
| 16 |
+
from sentence_transformers import SentenceTransformer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ #
|
| 20 |
+
# TextFeatureExtractorEndpoint (mirrors src/text_features.py)
|
| 21 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ #
|
| 22 |
+
|
| 23 |
+
class TextFeatureExtractorEndpoint:
|
| 24 |
+
"""Stateless text feature extraction for HF endpoint."""
|
| 25 |
+
|
| 26 |
+
# Keywords from src/text_features.py
|
| 27 |
+
BUSY_KEYWORDS = [
|
| 28 |
+
"busy", "driving", "can't talk", "in a meeting", "call me later",
|
| 29 |
+
"call back", "not now", "not a good time", "occupied", "running late",
|
| 30 |
+
"in the middle of", "hold on", "give me a minute", "let me call you back",
|
| 31 |
+
"gotta go", "heading out", "right now", "on the road", "at work",
|
| 32 |
+
"hung up", "hang up", "rushing",
|
| 33 |
+
]
|
| 34 |
+
FREE_KEYWORDS = [
|
| 35 |
+
"free", "available", "go ahead", "i have time", "i'm listening",
|
| 36 |
+
"sure", "yes", "yeah", "okay", "what's up", "tell me",
|
| 37 |
+
"i can talk", "go on", "fire away",
|
| 38 |
+
]
|
| 39 |
+
FILLER_WORDS = [
|
| 40 |
+
"um", "uh", "hmm", "like", "you know", "sort of",
|
| 41 |
+
"kind of", "i mean", "well", "so", "right", "actually",
|
| 42 |
+
]
|
| 43 |
+
URGENCY_MARKERS = [
|
| 44 |
+
"hurry", "quick", "fast", "rush", "soon", "asap",
|
| 45 |
+
"right now", "immediately", "no time",
|
| 46 |
+
]
|
| 47 |
+
DEFLECTION_PHRASES = [
|
| 48 |
+
"later", "not now", "another time", "busy", "can't",
|
| 49 |
+
"don't have time", "gotta go", "let me", "call me back",
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
def __init__(self):
|
| 53 |
+
print("Loading NLP models for text features...")
|
| 54 |
+
|
| 55 |
+
# Sentiment β RoBERTa-based
|
| 56 |
+
try:
|
| 57 |
+
self.sentiment_model = pipeline(
|
| 58 |
+
"sentiment-analysis",
|
| 59 |
+
model="cardiffnlp/twitter-roberta-base-sentiment-latest",
|
| 60 |
+
truncation=True,
|
| 61 |
+
max_length=512,
|
| 62 |
+
)
|
| 63 |
+
print("β Sentiment model loaded")
|
| 64 |
+
except Exception as e:
|
| 65 |
+
print(f"β Sentiment model fallback: {e}")
|
| 66 |
+
self.sentiment_model = None
|
| 67 |
+
|
| 68 |
+
# Coherence β Sentence Transformer
|
| 69 |
+
try:
|
| 70 |
+
self.coherence_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 71 |
+
print("β Coherence model loaded")
|
| 72 |
+
except Exception as e:
|
| 73 |
+
print(f"β Coherence model fallback: {e}")
|
| 74 |
+
self.coherence_model = None
|
| 75 |
+
|
| 76 |
+
print("β Text feature extractor ready")
|
| 77 |
+
|
| 78 |
+
# --- T0: Explicit Free ---
|
| 79 |
+
def extract_explicit_free(self, transcript: str) -> float:
|
| 80 |
+
text = transcript.lower()
|
| 81 |
+
for kw in self.FREE_KEYWORDS:
|
| 82 |
+
if kw in text:
|
| 83 |
+
return 1.0
|
| 84 |
+
return 0.0
|
| 85 |
+
|
| 86 |
+
# --- T1: Explicit Busy ---
|
| 87 |
+
def extract_explicit_busy(self, transcript: str) -> float:
|
| 88 |
+
text = transcript.lower()
|
| 89 |
+
for kw in self.BUSY_KEYWORDS:
|
| 90 |
+
if kw in text:
|
| 91 |
+
return 1.0
|
| 92 |
+
return 0.0
|
| 93 |
+
|
| 94 |
+
# --- T2-T3: Response patterns ---
|
| 95 |
+
def extract_response_patterns(self, transcript_list: List[str]) -> Dict[str, float]:
|
| 96 |
+
if not transcript_list:
|
| 97 |
+
return {"t2_avg_resp_len": 0.0, "t3_short_ratio": 0.0}
|
| 98 |
+
lengths = [len(r.split()) for r in transcript_list]
|
| 99 |
+
avg_len = float(np.mean(lengths))
|
| 100 |
+
short_ratio = sum(1 for l in lengths if l <= 3) / len(lengths)
|
| 101 |
+
return {"t2_avg_resp_len": avg_len, "t3_short_ratio": float(short_ratio)}
|
| 102 |
+
|
| 103 |
+
# --- T4-T6: Marker counts ---
|
| 104 |
+
def extract_marker_counts(self, transcript: str) -> Dict[str, float]:
|
| 105 |
+
text = transcript.lower()
|
| 106 |
+
words = text.split()
|
| 107 |
+
total = max(len(words), 1)
|
| 108 |
+
|
| 109 |
+
filler_count = sum(1 for w in words if w in self.FILLER_WORDS)
|
| 110 |
+
urgency_count = sum(1 for phrase in self.URGENCY_MARKERS if phrase in text)
|
| 111 |
+
deflection_count = sum(1 for phrase in self.DEFLECTION_PHRASES if phrase in text)
|
| 112 |
+
|
| 113 |
+
return {
|
| 114 |
+
"t4_cognitive_load": float(filler_count / total),
|
| 115 |
+
"t5_time_pressure": float(urgency_count / total),
|
| 116 |
+
"t6_deflection": float(deflection_count / total),
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
# --- T7: Sentiment ---
|
| 120 |
+
def extract_sentiment(self, transcript: str) -> float:
|
| 121 |
+
if self.sentiment_model is None or not transcript.strip():
|
| 122 |
+
return 0.0
|
| 123 |
+
try:
|
| 124 |
+
result = self.sentiment_model(transcript[:512])[0]
|
| 125 |
+
label = result["label"].lower()
|
| 126 |
+
score = result["score"]
|
| 127 |
+
if "positive" in label:
|
| 128 |
+
return float(score)
|
| 129 |
+
elif "negative" in label:
|
| 130 |
+
return float(-score)
|
| 131 |
+
else:
|
| 132 |
+
return 0.0
|
| 133 |
+
except Exception:
|
| 134 |
+
return 0.0
|
| 135 |
+
|
| 136 |
+
# --- T8: Coherence ---
|
| 137 |
+
def extract_coherence(self, question: str, responses: List[str]) -> float:
|
| 138 |
+
if self.coherence_model is None or not question or not responses:
|
| 139 |
+
return 0.5
|
| 140 |
+
try:
|
| 141 |
+
q_emb = self.coherence_model.encode(question)
|
| 142 |
+
r_embs = self.coherence_model.encode(responses)
|
| 143 |
+
from sklearn.metrics.pairwise import cosine_similarity as cos_sim
|
| 144 |
+
similarities = cos_sim([q_emb], r_embs)[0]
|
| 145 |
+
return float(np.mean(similarities))
|
| 146 |
+
except Exception:
|
| 147 |
+
return 0.5
|
| 148 |
+
|
| 149 |
+
# --- T9: Latency ---
|
| 150 |
+
def extract_latency(self, events: List[Dict]) -> float:
|
| 151 |
+
if not events or len(events) < 2:
|
| 152 |
+
return 0.0
|
| 153 |
+
latencies = []
|
| 154 |
+
for i in range(1, len(events)):
|
| 155 |
+
if events[i].get("speaker") != events[i - 1].get("speaker"):
|
| 156 |
+
t1 = events[i - 1].get("timestamp", 0)
|
| 157 |
+
t2 = events[i].get("timestamp", 0)
|
| 158 |
+
if t2 > t1:
|
| 159 |
+
latencies.append(t2 - t1)
|
| 160 |
+
return float(np.mean(latencies)) if latencies else 0.0
|
| 161 |
+
|
| 162 |
+
# --- Extract all ---
|
| 163 |
+
def extract_all(
|
| 164 |
+
self,
|
| 165 |
+
transcript_list: List[str],
|
| 166 |
+
full_transcript: str = "",
|
| 167 |
+
question: str = "",
|
| 168 |
+
events: List[Dict] = None,
|
| 169 |
+
) -> Dict[str, float]:
|
| 170 |
+
if not full_transcript and transcript_list:
|
| 171 |
+
full_transcript = " ".join(transcript_list)
|
| 172 |
+
|
| 173 |
+
features = {}
|
| 174 |
+
features["t0_explicit_free"] = self.extract_explicit_free(full_transcript)
|
| 175 |
+
features["t1_explicit_busy"] = self.extract_explicit_busy(full_transcript)
|
| 176 |
+
patterns = self.extract_response_patterns(transcript_list)
|
| 177 |
+
features.update(patterns)
|
| 178 |
+
markers = self.extract_marker_counts(full_transcript)
|
| 179 |
+
features.update(markers)
|
| 180 |
+
features["t7_sentiment"] = self.extract_sentiment(full_transcript)
|
| 181 |
+
features["t8_coherence"] = self.extract_coherence(question, transcript_list)
|
| 182 |
+
features["t9_latency"] = self.extract_latency(events or [])
|
| 183 |
+
return features
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ #
|
| 187 |
+
# FastAPI handler for deployment
|
| 188 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ #
|
| 189 |
+
|
| 190 |
+
from fastapi import FastAPI
|
| 191 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 192 |
+
from pydantic import BaseModel
|
| 193 |
+
from typing import Optional
|
| 194 |
+
|
| 195 |
+
app = FastAPI(title="Text Feature Extraction API", version="1.0.0")
|
| 196 |
+
app.add_middleware(
|
| 197 |
+
CORSMiddleware,
|
| 198 |
+
allow_origins=["*"], allow_credentials=True,
|
| 199 |
+
allow_methods=["*"], allow_headers=["*"],
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
extractor = TextFeatureExtractorEndpoint()
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class TextRequest(BaseModel):
|
| 206 |
+
transcript: str = ""
|
| 207 |
+
utterances: List[str] = []
|
| 208 |
+
question: str = ""
|
| 209 |
+
events: Optional[List[Dict]] = None
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@app.get("/health")
|
| 213 |
+
async def health():
|
| 214 |
+
return {
|
| 215 |
+
"status": "healthy",
|
| 216 |
+
"sentiment_loaded": extractor.sentiment_model is not None,
|
| 217 |
+
"coherence_loaded": extractor.coherence_model is not None,
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
@app.post("/extract-text-features")
|
| 222 |
+
async def extract_text_features(data: TextRequest):
|
| 223 |
+
"""Extract all 9 text features from transcript."""
|
| 224 |
+
transcript_list = data.utterances if data.utterances else [data.transcript]
|
| 225 |
+
features = extractor.extract_all(
|
| 226 |
+
transcript_list=transcript_list,
|
| 227 |
+
full_transcript=data.transcript,
|
| 228 |
+
question=data.question,
|
| 229 |
+
events=data.events,
|
| 230 |
+
)
|
| 231 |
+
return features
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
if __name__ == "__main__":
|
| 235 |
+
import uvicorn
|
| 236 |
+
uvicorn.run(app, host="0.0.0.0", port=7861)
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NLP
|
| 2 |
+
transformers==4.35.0
|
| 3 |
+
sentence-transformers==2.2.2
|
| 4 |
+
torch==2.1.0
|
| 5 |
+
numpy==1.24.3
|
| 6 |
+
scikit-learn==1.3.2
|
| 7 |
+
|
| 8 |
+
# API
|
| 9 |
+
fastapi==0.95.2
|
| 10 |
+
uvicorn==0.22.0
|
| 11 |
+
pydantic==1.10.13
|