Spaces:
Sleeping
Sleeping
Update model.py
Browse files
model.py
CHANGED
@@ -1,121 +1,122 @@
|
|
1 |
-
from typing import List, Optional
|
2 |
-
from pydantic import BaseModel
|
3 |
-
from transformers import pipeline
|
4 |
-
import nltk.data
|
5 |
-
|
6 |
-
# β
Extra: Smart Summarization Imports
|
7 |
-
from sklearn.feature_extraction.text import TfidfVectorizer
|
8 |
-
from sklearn.cluster import KMeans
|
9 |
-
from nltk.tokenize import sent_tokenize
|
10 |
-
from sklearn.metrics.pairwise import cosine_similarity
|
11 |
-
import numpy as np
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
kmeans
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
"
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
"
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
|
|
121 |
context: str
|
|
|
1 |
+
from typing import List, Optional
|
2 |
+
from pydantic import BaseModel
|
3 |
+
from transformers import pipeline
|
4 |
+
import nltk.data
|
5 |
+
|
6 |
+
# β
Extra: Smart Summarization Imports
|
7 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
8 |
+
from sklearn.cluster import KMeans
|
9 |
+
from nltk.tokenize import sent_tokenize
|
10 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
11 |
+
import numpy as np
|
12 |
+
import os
|
13 |
+
os.environ["TRANSFORMERS_CACHE"] = "/tmp/huggingface"
|
14 |
+
# π Load HuggingFace Pipelines
|
15 |
+
summarizer = pipeline("summarization", model="sshleifer/distilbart-cnn-12-6")
|
16 |
+
sentiment_analyzer = pipeline("sentiment-analysis")
|
17 |
+
|
18 |
+
# π§ Basic Summarization (Abstractive)
|
19 |
+
def summarize_review(text):
|
20 |
+
return summarizer(text, max_length=60, min_length=10, do_sample=False, no_repeat_ngram_size=3)[0]["summary_text"]
|
21 |
+
|
22 |
+
# π§ Smart Summarization (Clustered Key Sentences)
|
23 |
+
def smart_summarize(text, n_clusters=1):
|
24 |
+
"""Improved summarization using clustering on sentence embeddings"""
|
25 |
+
tokenizer = nltk.tokenize.PunktSentenceTokenizer() # β
Use default trained Punkt tokenizer
|
26 |
+
sentences = tokenizer.tokenize(text)
|
27 |
+
|
28 |
+
if len(sentences) <= 1:
|
29 |
+
return text
|
30 |
+
|
31 |
+
vectorizer = TfidfVectorizer(stop_words="english")
|
32 |
+
tfidf_matrix = vectorizer.fit_transform(sentences)
|
33 |
+
|
34 |
+
if len(sentences) <= n_clusters:
|
35 |
+
return " ".join(sentences)
|
36 |
+
|
37 |
+
kmeans = KMeans(n_clusters=n_clusters, random_state=42)
|
38 |
+
kmeans.fit(tfidf_matrix)
|
39 |
+
|
40 |
+
avg = []
|
41 |
+
for i in range(n_clusters):
|
42 |
+
idx = np.where(kmeans.labels_ == i)[0]
|
43 |
+
if len(idx) == 0:
|
44 |
+
continue
|
45 |
+
avg_vector = tfidf_matrix[idx].mean(axis=0).A1.reshape(1, -1) # Convert np.matrix to ndarray
|
46 |
+
sim = cosine_similarity(avg_vector, tfidf_matrix[idx])
|
47 |
+
most_representative_idx = idx[np.argmax(sim)]
|
48 |
+
avg.append(sentences[most_representative_idx])
|
49 |
+
|
50 |
+
return " ".join(sorted(avg, key=sentences.index))
|
51 |
+
|
52 |
+
# π Sentiment Detection
|
53 |
+
def analyze_sentiment(text):
|
54 |
+
result = sentiment_analyzer(text)[0]
|
55 |
+
label = result["label"]
|
56 |
+
score = result["score"]
|
57 |
+
|
58 |
+
if "star" in label:
|
59 |
+
stars = int(label[0])
|
60 |
+
if stars <= 2:
|
61 |
+
label = "NEGATIVE"
|
62 |
+
elif stars == 3:
|
63 |
+
label = "NEUTRAL"
|
64 |
+
else:
|
65 |
+
label = "POSITIVE"
|
66 |
+
|
67 |
+
return {
|
68 |
+
"label": label,
|
69 |
+
"score": score
|
70 |
+
}
|
71 |
+
|
72 |
+
# π₯ Emotion Detection (heuristic-based)
|
73 |
+
def detect_emotion(text):
|
74 |
+
text_lower = text.lower()
|
75 |
+
if "angry" in text_lower or "hate" in text_lower:
|
76 |
+
return "anger"
|
77 |
+
elif "happy" in text_lower or "love" in text_lower:
|
78 |
+
return "joy"
|
79 |
+
elif "sad" in text_lower or "disappointed" in text_lower:
|
80 |
+
return "sadness"
|
81 |
+
elif "confused" in text_lower or "unclear" in text_lower:
|
82 |
+
return "confusion"
|
83 |
+
else:
|
84 |
+
return "neutral"
|
85 |
+
|
86 |
+
# π§© Aspect-Based Sentiment (mock)
|
87 |
+
def extract_aspect_sentiment(text, aspects: list):
|
88 |
+
results = {}
|
89 |
+
text_lower = text.lower()
|
90 |
+
for asp in aspects:
|
91 |
+
label = "positive" if asp in text_lower and "not" not in text_lower else "neutral"
|
92 |
+
results[asp] = {
|
93 |
+
"label": label,
|
94 |
+
"confidence": 0.85
|
95 |
+
}
|
96 |
+
return results
|
97 |
+
|
98 |
+
# β
Pydantic Schemas for FastAPI
|
99 |
+
class ReviewInput(BaseModel):
|
100 |
+
text: str
|
101 |
+
model: str = "distilbert-base-uncased-finetuned-sst-2-english"
|
102 |
+
industry: str = "Generic"
|
103 |
+
aspects: bool = False
|
104 |
+
follow_up: Optional[str] = None
|
105 |
+
product_category: Optional[str] = None
|
106 |
+
device: Optional[str] = None
|
107 |
+
|
108 |
+
class BulkReviewInput(BaseModel):
|
109 |
+
reviews: List[str]
|
110 |
+
model: str = "distilbert-base-uncased-finetuned-sst-2-english"
|
111 |
+
industry: str = "Generic"
|
112 |
+
aspects: bool = False
|
113 |
+
product_category: Optional[str] = None
|
114 |
+
device: Optional[str] = None
|
115 |
+
|
116 |
+
class TranslationInput(BaseModel):
|
117 |
+
text: str
|
118 |
+
target_lang: str = "fr"
|
119 |
+
|
120 |
+
class ChatInput(BaseModel):
|
121 |
+
question: str
|
122 |
context: str
|