Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,123 +1,100 @@
|
|
| 1 |
-
import
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
from sklearn.
|
| 7 |
-
from sentence_transformers import SentenceTransformer
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 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 |
-
|
| 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 |
-
# --- Display output ---
|
| 102 |
-
output_text = f"β
**Detected {num_topics} Topics:**\n\n"
|
| 103 |
-
for title, examples in topic_data:
|
| 104 |
-
output_text += f"### {title}\n{examples}\n\n"
|
| 105 |
-
|
| 106 |
-
return output_text
|
| 107 |
-
|
| 108 |
-
# ----------------------------
|
| 109 |
-
# π¨ Gradio Interface
|
| 110 |
-
# ----------------------------
|
| 111 |
-
demo = gr.Interface(
|
| 112 |
-
fn=analyze_input,
|
| 113 |
-
inputs=[
|
| 114 |
-
gr.File(label="π Upload PDF (optional)"),
|
| 115 |
-
gr.Textbox(lines=10, placeholder="βοΈ Write or paste your essay here...", label="Essay Text")
|
| 116 |
-
],
|
| 117 |
-
outputs=gr.Markdown(label="π§ Detected Topics"),
|
| 118 |
-
title="PDF + Essay Topic Discovery (Transformer-Based)",
|
| 119 |
-
description="Upload a PDF and/or write an essay. The system identifies and summarizes main topics using transformer embeddings."
|
| 120 |
-
)
|
| 121 |
-
|
| 122 |
-
if __name__ == "__main__":
|
| 123 |
-
demo.launch()
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import re
|
| 3 |
+
import fitz # PyMuPDF for PDF extraction
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import numpy as np
|
| 6 |
+
from sklearn.cluster import KMeans
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
# ---------- Helper: extract text from PDF ----------
|
| 11 |
+
def extract_text_from_pdf(pdf_path):
|
| 12 |
+
text = ""
|
| 13 |
+
with fitz.open(pdf_path) as doc:
|
| 14 |
+
for page in doc:
|
| 15 |
+
text += page.get_text()
|
| 16 |
+
return text
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# ---------- Helper: Transformer Topic Modeling ----------
|
| 20 |
+
def transformer_topic_modeling(sentences, auto_topics=True, num_topics=5):
|
| 21 |
+
print("πΉ Using Transformer-based Embeddings...")
|
| 22 |
+
model = SentenceTransformer("flax-sentence-embeddings/multi-qa_v1-distilbert-cls_dot")
|
| 23 |
+
|
| 24 |
+
embeddings = model.encode(sentences)
|
| 25 |
+
|
| 26 |
+
# Auto-detect number of topics
|
| 27 |
+
if auto_topics:
|
| 28 |
+
distortions = []
|
| 29 |
+
K = range(2, min(10, len(sentences)//2 + 2))
|
| 30 |
+
for k in K:
|
| 31 |
+
km = KMeans(n_clusters=k, random_state=42).fit(embeddings)
|
| 32 |
+
distortions.append(km.inertia_)
|
| 33 |
+
diffs = np.diff(distortions)
|
| 34 |
+
num_topics = K[np.argmin(diffs)] if len(diffs) > 0 else 3
|
| 35 |
+
|
| 36 |
+
kmeans = KMeans(n_clusters=num_topics, random_state=42)
|
| 37 |
+
labels = kmeans.fit_predict(embeddings)
|
| 38 |
+
df = pd.DataFrame({"Sentence": sentences, "Topic": labels})
|
| 39 |
+
|
| 40 |
+
topics = []
|
| 41 |
+
for i in range(num_topics):
|
| 42 |
+
topic_sentences = df[df["Topic"] == i]["Sentence"].tolist()
|
| 43 |
+
joined_text = " ".join(topic_sentences)
|
| 44 |
+
words = re.findall(r"\b\w+\b", joined_text.lower())
|
| 45 |
+
top_words = pd.Series(words).value_counts().head(3).index.tolist()
|
| 46 |
+
title = " & ".join(top_words).title()
|
| 47 |
+
topics.append((title, " ".join(topic_sentences[:3])))
|
| 48 |
+
|
| 49 |
+
return topics, num_topics
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ---------- Main Function ----------
|
| 53 |
+
def analyze_input(pdf_file, essay_text):
|
| 54 |
+
try:
|
| 55 |
+
pdf_text = ""
|
| 56 |
+
if pdf_file:
|
| 57 |
+
pdf_text = extract_text_from_pdf(pdf_file.name)
|
| 58 |
+
print("β
PDF extracted successfully, length:", len(pdf_text))
|
| 59 |
+
|
| 60 |
+
full_text = (pdf_text + "\n" + (essay_text or "")).strip()
|
| 61 |
+
if not full_text:
|
| 62 |
+
return "β Please upload a PDF or write an essay."
|
| 63 |
+
|
| 64 |
+
sentences = [s.strip() for s in re.split(r'[.!?]', full_text) if len(s.strip()) > 20]
|
| 65 |
+
print("π§Ύ Sentence count:", len(sentences))
|
| 66 |
+
|
| 67 |
+
if len(sentences) < 2:
|
| 68 |
+
return "β οΈ Not enough text for topic modeling."
|
| 69 |
+
|
| 70 |
+
topic_data, num_topics = transformer_topic_modeling(sentences, auto_topics=True)
|
| 71 |
+
print("β
Topics discovered:", num_topics)
|
| 72 |
+
|
| 73 |
+
# Build Markdown output (Gradio-safe)
|
| 74 |
+
output_lines = [f"β
**Detected {num_topics} Topics:**\n"]
|
| 75 |
+
for i, (title, examples) in enumerate(topic_data, 1):
|
| 76 |
+
output_lines.append(f"**Topic {i}: {title}**\n{examples}\n")
|
| 77 |
+
result = "\n\n".join(output_lines)
|
| 78 |
+
|
| 79 |
+
return result # β
Must return a string
|
| 80 |
+
|
| 81 |
+
except Exception as e:
|
| 82 |
+
import traceback
|
| 83 |
+
print(traceback.format_exc()) # full error log for Hugging Face
|
| 84 |
+
return f"β οΈ Error: {str(e)}"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# ---------- Gradio UI ----------
|
| 88 |
+
demo = gr.Interface(
|
| 89 |
+
fn=analyze_input,
|
| 90 |
+
inputs=[
|
| 91 |
+
gr.File(label="π Upload a PDF (optional)"),
|
| 92 |
+
gr.Textbox(label="π Essay Text", lines=7, placeholder="Write or paste your essay here...")
|
| 93 |
+
],
|
| 94 |
+
outputs=gr.Markdown(label="π§ Topic Analysis Result"),
|
| 95 |
+
title="Topic Modeling App",
|
| 96 |
+
description="Upload a PDF and/or write an essay. The system identifies and summarizes main topics using transformer embeddings."
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
if __name__ == "__main__":
|
| 100 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|