Spaces:
Paused
Paused
Commit ·
2404dc3
0
Parent(s):
feat: initial release of machine learning space
Browse files- README.md +19 -0
- app.py +224 -0
- requirements.txt +4 -0
README.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Stylometry Analyzer
|
| 3 |
+
emoji: 🖋️
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: orange
|
| 6 |
+
sdk: gradio
|
| 7 |
+
app_file: app.py
|
| 8 |
+
pinned: false
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# Stylometry & Authorship Analyzer
|
| 12 |
+
|
| 13 |
+
An interactive digital humanities application designed to help students analyze and compare the mathematical "writing styles" or "stylometric fingerprints" of multiple documents. Perfect for investigating anonymous works, historical authorship, or changes in an author's style over time.
|
| 14 |
+
|
| 15 |
+
### Features
|
| 16 |
+
1. **Interactive HEATMAPS**: Map similarity values (%) side-by-side using cosine and Euclidean distance matrices.
|
| 17 |
+
2. **Ward Hierarchical Clustering**: Render beautiful dendrogram hierarchies natively in Plotly, grouping texts by style.
|
| 18 |
+
3. **Comprehensive Punctuation & Lexical Fingerprints**: Extract type-token ratios (TTR), average sentence lengths, word lengths, commas, semicolons, and exclamations automatically.
|
| 19 |
+
4. **Data Exports**: Download the full list of extracted stylometrics as a CSV file.
|
app.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import re
|
| 5 |
+
from scipy.spatial.distance import pdist, squareform
|
| 6 |
+
from scipy.cluster.hierarchy import linkage
|
| 7 |
+
import plotly.figure_factory as ff
|
| 8 |
+
import plotly.graph_objects as go
|
| 9 |
+
import tempfile
|
| 10 |
+
import os
|
| 11 |
+
|
| 12 |
+
def extract_features(text):
|
| 13 |
+
# Basic tokens
|
| 14 |
+
tokens = re.findall(r'\b[a-zA-Z]+\b', text.lower())
|
| 15 |
+
total_words = len(tokens)
|
| 16 |
+
|
| 17 |
+
if total_words < 10:
|
| 18 |
+
return None
|
| 19 |
+
|
| 20 |
+
unique_words = len(set(tokens))
|
| 21 |
+
|
| 22 |
+
# 1. Type-Token Ratio (Vocabulary Richness)
|
| 23 |
+
ttr = unique_words / total_words
|
| 24 |
+
|
| 25 |
+
# 2. Average Word Length
|
| 26 |
+
avg_word_len = np.mean([len(w) for w in tokens])
|
| 27 |
+
|
| 28 |
+
# 3. Sentence Length Metrics
|
| 29 |
+
sentences = re.split(r'[.!?]+', text)
|
| 30 |
+
sentences = [s.strip() for s in sentences if s.strip()]
|
| 31 |
+
sent_lengths = [len(re.findall(r'\b[a-zA-Z]+\b', s)) for s in sentences]
|
| 32 |
+
avg_sent_len = np.mean(sent_lengths) if sent_lengths else 0
|
| 33 |
+
std_sent_len = np.std(sent_lengths) if sent_lengths else 0
|
| 34 |
+
|
| 35 |
+
# 4. Punctuation frequencies
|
| 36 |
+
commas = len(re.findall(r',', text)) / total_words
|
| 37 |
+
semicolons = len(re.findall(r';', text)) / total_words
|
| 38 |
+
exclamations = len(re.findall(r'!', text)) / total_words
|
| 39 |
+
questions = len(re.findall(r'\?', text)) / total_words
|
| 40 |
+
|
| 41 |
+
return {
|
| 42 |
+
"Vocabulary Richness (TTR)": ttr,
|
| 43 |
+
"Average Word Length": avg_word_len,
|
| 44 |
+
"Average Sentence Length": avg_sent_len,
|
| 45 |
+
"Sentence Length Variation (STD)": std_sent_len,
|
| 46 |
+
"Commas Frequency": commas,
|
| 47 |
+
"Semicolons Frequency": semicolons,
|
| 48 |
+
"Exclamation Frequency": exclamations,
|
| 49 |
+
"Question Frequency": questions
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
def run_stylometry(files, chosen_features):
|
| 53 |
+
if not files or len(files) < 3:
|
| 54 |
+
return "Please upload at least 3 distinct text files (TXT format) to perform comparative stylometry.", None, None, None
|
| 55 |
+
|
| 56 |
+
documents = {}
|
| 57 |
+
doc_features = {}
|
| 58 |
+
|
| 59 |
+
for file_obj in files:
|
| 60 |
+
# Extract filename as label
|
| 61 |
+
label = os.path.splitext(os.path.basename(file_obj.name))[0]
|
| 62 |
+
try:
|
| 63 |
+
with open(file_obj.name, "r", encoding="utf-8", errors="ignore") as f:
|
| 64 |
+
text = f.read()
|
| 65 |
+
feats = extract_features(text)
|
| 66 |
+
if feats:
|
| 67 |
+
documents[label] = text
|
| 68 |
+
doc_features[label] = feats
|
| 69 |
+
except Exception as e:
|
| 70 |
+
return f"Error reading file '{label}': {str(e)}", None, None, None
|
| 71 |
+
|
| 72 |
+
if len(doc_features) < 3:
|
| 73 |
+
return "At least 3 files must have valid text content of at least 10 words.", None, None, None
|
| 74 |
+
|
| 75 |
+
df_features = pd.DataFrame(doc_features).transpose()
|
| 76 |
+
|
| 77 |
+
# Subset by chosen features
|
| 78 |
+
if not chosen_features:
|
| 79 |
+
chosen_features = list(df_features.columns)
|
| 80 |
+
|
| 81 |
+
df_sub = df_features[chosen_features]
|
| 82 |
+
|
| 83 |
+
# Standardize features (Z-Score)
|
| 84 |
+
df_norm = (df_sub - df_sub.mean()) / df_sub.std()
|
| 85 |
+
# Replace possible NaNs from zero standard deviation
|
| 86 |
+
df_norm = df_norm.fillna(0)
|
| 87 |
+
|
| 88 |
+
labels = list(df_norm.index)
|
| 89 |
+
|
| 90 |
+
# Calculate Distance Matrix (Euclidean)
|
| 91 |
+
distances = pdist(df_norm.values, metric='euclidean')
|
| 92 |
+
dist_matrix = squareform(distances)
|
| 93 |
+
|
| 94 |
+
# Max similarity corresponds to 0 distance
|
| 95 |
+
# Convert distance to a similarity score between 0 and 100%
|
| 96 |
+
max_d = np.max(dist_matrix) if np.max(dist_matrix) > 0 else 1.0
|
| 97 |
+
sim_matrix = (1.0 - (dist_matrix / max_d)) * 100
|
| 98 |
+
|
| 99 |
+
# 1. Similarity Heatmap Plotly
|
| 100 |
+
fig_heatmap = go.Figure(data=go.Heatmap(
|
| 101 |
+
z=sim_matrix,
|
| 102 |
+
x=labels,
|
| 103 |
+
y=labels,
|
| 104 |
+
colorscale='Hot',
|
| 105 |
+
text=[[f"{val:.1f}%" for val in row] for row in sim_matrix],
|
| 106 |
+
texttemplate="%{text}",
|
| 107 |
+
hoverinfo='z'
|
| 108 |
+
))
|
| 109 |
+
|
| 110 |
+
fig_heatmap.update_layout(
|
| 111 |
+
title="Stylometric Style Similarity Heatmap (%)",
|
| 112 |
+
paper_bgcolor='#16100c',
|
| 113 |
+
plot_bgcolor='#16100c',
|
| 114 |
+
font_color='#f4eee6',
|
| 115 |
+
xaxis=dict(gridcolor='rgba(255,255,255,0.05)'),
|
| 116 |
+
yaxis=dict(gridcolor='rgba(255,255,255,0.05)'),
|
| 117 |
+
margin=dict(l=40, r=40, t=50, b=40)
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
# 2. Hierarchical Cluster Dendrogram
|
| 121 |
+
try:
|
| 122 |
+
Z = linkage(distances, 'ward')
|
| 123 |
+
fig_dendro = ff.create_dendrogram(df_norm.values, orientation='left', labels=labels, linkagefun=lambda x: Z)
|
| 124 |
+
fig_dendro.update_layout(
|
| 125 |
+
title="Hierarchical Stylistic Cluster Dendrogram",
|
| 126 |
+
paper_bgcolor='#16100c',
|
| 127 |
+
plot_bgcolor='#16100c',
|
| 128 |
+
font_color='#f4eee6',
|
| 129 |
+
xaxis=dict(showgrid=True, gridcolor='rgba(255,255,255,0.05)', title="Distance (Ward threshold)"),
|
| 130 |
+
yaxis=dict(gridcolor='rgba(255,255,255,0.05)'),
|
| 131 |
+
margin=dict(l=80, r=40, t=50, b=40)
|
| 132 |
+
)
|
| 133 |
+
# Match colors to style system
|
| 134 |
+
for trace in fig_dendro.data:
|
| 135 |
+
if 'color' in trace:
|
| 136 |
+
trace.line.color = '#ff7043'
|
| 137 |
+
except Exception as e:
|
| 138 |
+
# Fallback to simple placeholder scatter if dendrogram linkage fails (e.g. from numerical identical elements)
|
| 139 |
+
fig_dendro = go.Figure()
|
| 140 |
+
fig_dendro.add_annotation(text=f"Hierarchical linkage omitted: {str(e)}", showarrow=False, font=dict(size=14))
|
| 141 |
+
fig_dendro.update_layout(paper_bgcolor='#16100c', font_color='#f4eee6')
|
| 142 |
+
|
| 143 |
+
# Prep output tables
|
| 144 |
+
df_features_out = df_features.round(4).reset_index().rename(columns={"index": "Document Label"})
|
| 145 |
+
|
| 146 |
+
# Save CSV
|
| 147 |
+
out_csv = tempfile.mktemp(suffix=".csv")
|
| 148 |
+
df_features_out.to_csv(out_csv, index=False)
|
| 149 |
+
|
| 150 |
+
return "", fig_heatmap, fig_dendro, df_features_out, gr.update(value=out_csv, visible=True)
|
| 151 |
+
|
| 152 |
+
theme = gr.themes.Default(
|
| 153 |
+
primary_hue="orange",
|
| 154 |
+
neutral_hue="stone"
|
| 155 |
+
).set(
|
| 156 |
+
body_background_fill="#0d0907",
|
| 157 |
+
body_text_color="#c4bbae",
|
| 158 |
+
block_background_fill="#16100c",
|
| 159 |
+
block_border_width="1px",
|
| 160 |
+
block_label_text_color="#f4eee6"
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
all_features = [
|
| 164 |
+
"Vocabulary Richness (TTR)",
|
| 165 |
+
"Average Word Length",
|
| 166 |
+
"Average Sentence Length",
|
| 167 |
+
"Sentence Length Variation (STD)",
|
| 168 |
+
"Commas Frequency",
|
| 169 |
+
"Semicolons Frequency",
|
| 170 |
+
"Exclamation Frequency",
|
| 171 |
+
"Question Frequency"
|
| 172 |
+
]
|
| 173 |
+
|
| 174 |
+
with gr.Blocks(theme=theme, title="Comparative Stylometry Analyzer") as demo:
|
| 175 |
+
gr.Markdown(
|
| 176 |
+
"""
|
| 177 |
+
# 🖋️ Comparative Stylometry & Authorship Analyzer
|
| 178 |
+
### Extract, analyze, and map the quantitative writing styles of multiple documents. Perfect for authorship debates, forensic linguistics, and distant reading comparisons.
|
| 179 |
+
"""
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
error_msg = gr.Markdown("", visible=False)
|
| 183 |
+
|
| 184 |
+
with gr.Row():
|
| 185 |
+
with gr.Column(scale=1):
|
| 186 |
+
file_objs = gr.File(
|
| 187 |
+
label="Upload Text Files (Select at least 3 TXT files)",
|
| 188 |
+
file_types=[".txt"],
|
| 189 |
+
file_count="multiple"
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
chosen_features = gr.CheckboxGroup(
|
| 193 |
+
choices=all_features,
|
| 194 |
+
value=all_features[:5],
|
| 195 |
+
label="Stylometric Features to Compare",
|
| 196 |
+
info="Toggle features to customize the mathematical fingerprint vector."
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
btn = gr.Button("Calculate Writing Footprints", variant="primary")
|
| 200 |
+
|
| 201 |
+
with gr.Column(scale=2):
|
| 202 |
+
with gr.Tabs():
|
| 203 |
+
with gr.TabItem("Style Similarity Matrix"):
|
| 204 |
+
plot_heatmap = gr.Plot()
|
| 205 |
+
with gr.TabItem("Clustering Dendrogram"):
|
| 206 |
+
plot_dendro = gr.Plot()
|
| 207 |
+
with gr.TabItem("Extracted Stylometrics Table"):
|
| 208 |
+
table_features = gr.Dataframe()
|
| 209 |
+
download_btn = gr.File(label="Download Full Stylometrics CSV", visible=False)
|
| 210 |
+
|
| 211 |
+
def process(files, features):
|
| 212 |
+
err, heatmap, dendro, table, csv_path = run_stylometry(files, features)
|
| 213 |
+
if err:
|
| 214 |
+
return gr.update(value=err, visible=True), None, None, None, gr.update(visible=False)
|
| 215 |
+
return gr.update(visible=False), heatmap, dendro, table, csv_path
|
| 216 |
+
|
| 217 |
+
btn.click(
|
| 218 |
+
process,
|
| 219 |
+
inputs=[file_objs, chosen_features],
|
| 220 |
+
outputs=[error_msg, plot_heatmap, plot_dendro, table_features, download_btn]
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
if __name__ == "__main__":
|
| 224 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pandas
|
| 2 |
+
numpy
|
| 3 |
+
scipy
|
| 4 |
+
plotly
|