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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr # type: ignore
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import re
|
| 4 |
+
import spacy # type: ignore
|
| 5 |
+
from sklearn.cluster import KMeans
|
| 6 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 7 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 8 |
+
from sentence_transformers import SentenceTransformer, util # type: ignore
|
| 9 |
+
from transformers import pipeline, AutoTokenizer
|
| 10 |
+
import textstat # type: ignore
|
| 11 |
+
|
| 12 |
+
sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
|
| 13 |
+
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english")
|
| 14 |
+
|
| 15 |
+
nlp = spacy.load("en_core_web_sm")
|
| 16 |
+
|
| 17 |
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 18 |
+
|
| 19 |
+
weights = {
|
| 20 |
+
"information_density": 0.2,
|
| 21 |
+
"unique_key_points": 0.8,
|
| 22 |
+
"strength_word_count": 0.002,
|
| 23 |
+
"weakness_word_count": 0.004,
|
| 24 |
+
"discussion_word_count": 0.01
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
THRESHOLDS = {
|
| 28 |
+
"normalized_length": (0.15, 0.25),
|
| 29 |
+
"unique_key_points": (3, 10),
|
| 30 |
+
"information_density": (0.01, 0.02),
|
| 31 |
+
"unique_insights_per_word": 0.002,
|
| 32 |
+
"optimization_score": 0.7,
|
| 33 |
+
"composite_score": 5,
|
| 34 |
+
"adjusted_argument_strength": 0.75
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
def chunk_text(text, max_length):
|
| 38 |
+
tokens = tokenizer(text, return_tensors="pt", truncation=False)["input_ids"].squeeze(0).tolist()
|
| 39 |
+
return [tokenizer.decode(tokens[i:i+max_length]) for i in range(0, len(tokens), max_length)]
|
| 40 |
+
|
| 41 |
+
def analyze_text(texts):
|
| 42 |
+
results = []
|
| 43 |
+
for text in texts:
|
| 44 |
+
chunks = chunk_text(text, max_length=200)
|
| 45 |
+
chunk_results = sentiment_analyzer(chunks)
|
| 46 |
+
overall_sentiment = {
|
| 47 |
+
"label": "POSITIVE" if sum(1 for res in chunk_results if res["label"] == "POSITIVE") >= len(chunk_results) / 2 else "NEGATIVE",
|
| 48 |
+
"score": sum(res["score"] for res in chunk_results) / len(chunk_results),
|
| 49 |
+
}
|
| 50 |
+
results.append(overall_sentiment)
|
| 51 |
+
return results
|
| 52 |
+
|
| 53 |
+
def word_count(text):
|
| 54 |
+
return len(text.split()) if isinstance(text, str) else 0
|
| 55 |
+
|
| 56 |
+
def count_citations(text):
|
| 57 |
+
doc = nlp(text)
|
| 58 |
+
return sum(1 for ent in doc.ents if ent.label_ in ['WORK_OF_ART', 'ORG', 'GPE'])
|
| 59 |
+
|
| 60 |
+
def calculate_unique_insights_per_word(text):
|
| 61 |
+
sentences = text.split('.')
|
| 62 |
+
tfidf = TfidfVectorizer().fit_transform(sentences)
|
| 63 |
+
similarities = cosine_similarity(tfidf)
|
| 64 |
+
avg_similarity = (similarities.sum() - len(sentences)) / (len(sentences)**2 - len(sentences))
|
| 65 |
+
return 1 - avg_similarity
|
| 66 |
+
|
| 67 |
+
def calculate_unique_key_points_and_density(texts):
|
| 68 |
+
unique_key_points = []
|
| 69 |
+
information_density = []
|
| 70 |
+
|
| 71 |
+
for text in texts:
|
| 72 |
+
if not isinstance(text, str) or text.strip() == "":
|
| 73 |
+
unique_key_points.append(0)
|
| 74 |
+
information_density.append(0)
|
| 75 |
+
continue
|
| 76 |
+
|
| 77 |
+
doc = nlp(text)
|
| 78 |
+
sentences = [sent.text for sent in doc.sents]
|
| 79 |
+
|
| 80 |
+
embeddings = model.encode(sentences)
|
| 81 |
+
|
| 82 |
+
n_clusters = max(1, len(sentences) // 5)
|
| 83 |
+
kmeans = KMeans(n_clusters=n_clusters, random_state=42)
|
| 84 |
+
kmeans.fit(embeddings)
|
| 85 |
+
|
| 86 |
+
cluster_centers = kmeans.cluster_centers_
|
| 87 |
+
unique_points_count = len(cluster_centers)
|
| 88 |
+
|
| 89 |
+
word_count = len(text.split())
|
| 90 |
+
density = unique_points_count / word_count if word_count > 0 else 0
|
| 91 |
+
|
| 92 |
+
unique_key_points.append(unique_points_count)
|
| 93 |
+
information_density.append(density)
|
| 94 |
+
|
| 95 |
+
return unique_key_points, information_density
|
| 96 |
+
|
| 97 |
+
def segment_comments(comments):
|
| 98 |
+
if comments == "N/A":
|
| 99 |
+
return {"strengths": "", "weaknesses": "", "general_discussion": ""}
|
| 100 |
+
|
| 101 |
+
strengths = re.search(r"- Strengths:\n([\s\S]*?)(\n- Weaknesses:|\Z)", comments)
|
| 102 |
+
weaknesses = re.search(r"- Weaknesses:\n([\s\S]*?)(\n- General Discussion:|\Z)", comments)
|
| 103 |
+
general_discussion = re.search(r"- General Discussion:\n([\s\S]*?)\Z", comments)
|
| 104 |
+
|
| 105 |
+
return {
|
| 106 |
+
"strengths": strengths.group(1).strip() if strengths else "",
|
| 107 |
+
"weaknesses": weaknesses.group(1).strip() if weaknesses else "",
|
| 108 |
+
"general_discussion": general_discussion.group(1).strip() if general_discussion else ""
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
def preprocess(comment, abstract):
|
| 112 |
+
df = pd.DataFrame({"comments": [comment]})
|
| 113 |
+
abstracts = pd.DataFrame({"abstract": [abstract]})
|
| 114 |
+
|
| 115 |
+
segmented_reviews = df["comments"].apply(segment_comments)
|
| 116 |
+
df["strengths"] = segmented_reviews.apply(lambda x: x["strengths"])
|
| 117 |
+
df["weaknesses"] = segmented_reviews.apply(lambda x: x["weaknesses"])
|
| 118 |
+
df["general_discussion"] = segmented_reviews.apply(lambda x: x["general_discussion"])
|
| 119 |
+
|
| 120 |
+
comments_embeddings = model.encode(df['comments'].tolist(), convert_to_tensor=True)
|
| 121 |
+
abstract_embeddings = model.encode(abstracts["abstract"].tolist(), convert_to_tensor=True)
|
| 122 |
+
df['content_relevance'] = util.cos_sim(comments_embeddings, abstract_embeddings).diagonal()
|
| 123 |
+
|
| 124 |
+
df['evidence_support'] = df['comments'].apply(count_citations)
|
| 125 |
+
|
| 126 |
+
df['strengths'] = df['strengths'].fillna('').astype(str)
|
| 127 |
+
texts = df['strengths'].tolist()
|
| 128 |
+
results = analyze_text(texts)
|
| 129 |
+
df['strength_argument_score'] = [result['score'] for result in results]
|
| 130 |
+
|
| 131 |
+
df['weaknesses'] = df['weaknesses'].fillna('').astype(str)
|
| 132 |
+
texts = df['weaknesses'].tolist()
|
| 133 |
+
results = analyze_text(texts)
|
| 134 |
+
df['weakness_argument_score'] = [result['score'] for result in results]
|
| 135 |
+
|
| 136 |
+
df['argument_strength'] = (df['strength_argument_score'] + df['weakness_argument_score']) / 2
|
| 137 |
+
|
| 138 |
+
df['readability_index'] = df['comments'].apply(textstat.flesch_reading_ease)
|
| 139 |
+
df['sentence_complexity'] = df['comments'].apply(textstat.sentence_count)
|
| 140 |
+
df['technical_depth'] = df['readability_index'] / df['sentence_complexity']
|
| 141 |
+
|
| 142 |
+
df['total_word_count'] = df['comments'].apply(word_count)
|
| 143 |
+
df['strength_word_count'] = df['strengths'].apply(word_count)
|
| 144 |
+
df['weakness_word_count'] = df['weaknesses'].apply(word_count)
|
| 145 |
+
df['discussion_word_count'] = df['general_discussion'].apply(word_count)
|
| 146 |
+
|
| 147 |
+
average_length = df['total_word_count'].mean()
|
| 148 |
+
df['normalized_length'] = df['total_word_count'] / average_length
|
| 149 |
+
df["unique_key_points"], df["information_density"] = calculate_unique_key_points_and_density(df["comments"])
|
| 150 |
+
|
| 151 |
+
df['unique_insights_per_word'] = df['comments'].apply(calculate_unique_insights_per_word) / df['total_word_count']
|
| 152 |
+
|
| 153 |
+
return df
|
| 154 |
+
|
| 155 |
+
def calculate_composite_score(df):
|
| 156 |
+
df['composite_score'] = (
|
| 157 |
+
weights['information_density'] * df['information_density'] +
|
| 158 |
+
weights['unique_key_points'] * df['unique_key_points'] +
|
| 159 |
+
weights['strength_word_count'] * df['strength_word_count'] +
|
| 160 |
+
weights['weakness_word_count'] * df['weakness_word_count'] +
|
| 161 |
+
weights['discussion_word_count'] * df['discussion_word_count']
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
return df
|
| 165 |
+
|
| 166 |
+
def classify_review_quality(row):
|
| 167 |
+
if row['composite_score'] > 12:
|
| 168 |
+
return 'Excellent Review Quality'
|
| 169 |
+
elif row['composite_score'] < 3:
|
| 170 |
+
return 'Poor Review Quality'
|
| 171 |
+
else:
|
| 172 |
+
return 'Moderate Review Quality'
|
| 173 |
+
|
| 174 |
+
def determine_review_quality(df):
|
| 175 |
+
|
| 176 |
+
df['normalized_length'] = df['total_word_count'] / df['total_word_count'].max()
|
| 177 |
+
df['unique_insights_per_word'] = df['unique_key_points'] / df['normalized_length']
|
| 178 |
+
df['adjusted_argument_strength'] = df['argument_strength'] / (1 + df['sentence_complexity'])
|
| 179 |
+
|
| 180 |
+
df['review_quality'] = df.apply(classify_review_quality, axis=1)
|
| 181 |
+
|
| 182 |
+
return df
|
| 183 |
+
|
| 184 |
+
def heuristic_optimization(row):
|
| 185 |
+
suggestions = []
|
| 186 |
+
|
| 187 |
+
if row["strength_word_count"] > 100 and row["strength_argument_score"] < THRESHOLDS["adjusted_argument_strength"]:
|
| 188 |
+
suggestions.append("Summarize redundant strengths.")
|
| 189 |
+
elif row["strength_word_count"] < 50 and row["strength_argument_score"] < THRESHOLDS["adjusted_argument_strength"]:
|
| 190 |
+
suggestions.append("Add more impactful strengths.")
|
| 191 |
+
|
| 192 |
+
if row["weakness_word_count"] > 100 and row["weakness_argument_score"] < THRESHOLDS["adjusted_argument_strength"]:
|
| 193 |
+
suggestions.append("Remove repetitive criticisms.")
|
| 194 |
+
elif row["weakness_word_count"] < 50 and row["weakness_argument_score"] < THRESHOLDS["adjusted_argument_strength"]:
|
| 195 |
+
suggestions.append("Add specific, actionable weaknesses.")
|
| 196 |
+
|
| 197 |
+
if row["discussion_word_count"] < 100 and row["information_density"] < THRESHOLDS["information_density"][0]:
|
| 198 |
+
suggestions.append("Elaborate with new insights or examples.")
|
| 199 |
+
elif row["discussion_word_count"] > 300 and row["information_density"] > THRESHOLDS["information_density"][1]:
|
| 200 |
+
suggestions.append("Summarize key discussion points.")
|
| 201 |
+
|
| 202 |
+
if row["normalized_length"] < THRESHOLDS["normalized_length"][0]:
|
| 203 |
+
suggestions.append("Expand sections for better coverage.")
|
| 204 |
+
elif row["normalized_length"] > THRESHOLDS["normalized_length"][1]:
|
| 205 |
+
suggestions.append("Condense content to improve readability.")
|
| 206 |
+
|
| 207 |
+
if row["unique_key_points"] < THRESHOLDS["unique_key_points"][0]:
|
| 208 |
+
suggestions.append("Add more unique insights.")
|
| 209 |
+
elif row["unique_key_points"] > THRESHOLDS["unique_key_points"][1]:
|
| 210 |
+
suggestions.append("Streamline ideas for clarity.")
|
| 211 |
+
|
| 212 |
+
if row["composite_score"] < THRESHOLDS["composite_score"]:
|
| 213 |
+
suggestions.append("Enhance clarity, evidence, and argumentation.")
|
| 214 |
+
|
| 215 |
+
if row["review_quality"] == "Low":
|
| 216 |
+
suggestions.append("Significant revisions required.")
|
| 217 |
+
elif row["review_quality"] == "Moderate":
|
| 218 |
+
suggestions.append("Minor refinements recommended.")
|
| 219 |
+
|
| 220 |
+
return suggestions
|
| 221 |
+
|
| 222 |
+
def pipeline(comment, abstract):
|
| 223 |
+
df = preprocess(comment, abstract)
|
| 224 |
+
df = calculate_composite_score(df)
|
| 225 |
+
df = determine_review_quality(df)
|
| 226 |
+
df["optimization_suggestions"] = df.apply(heuristic_optimization, axis=1)
|
| 227 |
+
return df["composite_score"][0], " ".join(df["optimization_suggestions"][0])
|
| 228 |
+
|
| 229 |
+
demo = gr.Interface(fn=pipeline, inputs=["text", "text"], outputs=["text", "text"])
|
| 230 |
+
demo.launch()
|
requirements.txt
ADDED
|
Binary file (3.5 kB). View file
|
|
|