Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,129 +1,76 @@
|
|
| 1 |
-
import torch
|
| 2 |
-
from transformers import pipeline
|
| 3 |
import spacy
|
| 4 |
-
import textwrap
|
| 5 |
-
import streamlit as st
|
| 6 |
-
import subprocess
|
| 7 |
-
import networkx as nx
|
| 8 |
-
import matplotlib.pyplot as plt
|
| 9 |
-
import concurrent.futures
|
| 10 |
import json
|
| 11 |
-
import
|
| 12 |
import docx
|
| 13 |
from bs4 import BeautifulSoup
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
try:
|
| 18 |
-
nlp = spacy.load("en_core_web_sm")
|
| 19 |
-
except OSError:
|
| 20 |
-
subprocess.run(["python", "-m", "spacy", "download", "en_core_web_sm"])
|
| 21 |
-
nlp = spacy.load("en_core_web_sm")
|
| 22 |
-
return nlp
|
| 23 |
-
|
| 24 |
-
# Load sentiment analysis model
|
| 25 |
-
sentiment_pipeline = pipeline("sentiment-analysis")
|
| 26 |
-
|
| 27 |
-
# Load spaCy model for Named Entity Recognition (NER)
|
| 28 |
-
nlp = ensure_spacy_model()
|
| 29 |
|
| 30 |
def extract_text_from_file(uploaded_file):
|
| 31 |
-
"""
|
| 32 |
file_type = uploaded_file.name.split(".")[-1].lower()
|
| 33 |
-
text = ""
|
| 34 |
|
| 35 |
if file_type == "txt":
|
| 36 |
-
text = uploaded_file.
|
|
|
|
| 37 |
elif file_type == "html":
|
| 38 |
-
soup = BeautifulSoup(uploaded_file.
|
| 39 |
text = soup.get_text()
|
|
|
|
| 40 |
elif file_type == "json":
|
| 41 |
data = json.load(uploaded_file)
|
| 42 |
-
text = "\n".join(
|
|
|
|
| 43 |
elif file_type == "pdf":
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
|
|
|
| 46 |
elif file_type == "docx":
|
| 47 |
doc = docx.Document(uploaded_file)
|
| 48 |
text = "\n".join([para.text for para in doc.paragraphs])
|
| 49 |
-
else:
|
| 50 |
-
st.error("Unsupported file format. Please upload a TXT, HTML, JSON, PDF, or DOCX file.")
|
| 51 |
-
return None
|
| 52 |
|
| 53 |
-
|
|
|
|
| 54 |
|
| 55 |
-
|
| 56 |
-
"""Parses chat logs to extract speaker names and messages."""
|
| 57 |
-
chat_lines = chat_text.split("\n")
|
| 58 |
-
chat_data = []
|
| 59 |
-
for line in chat_lines:
|
| 60 |
-
if ":" in line:
|
| 61 |
-
speaker, message = line.split(":", 1)
|
| 62 |
-
chat_data.append((speaker.strip(), message.strip()))
|
| 63 |
-
return chat_data
|
| 64 |
|
| 65 |
-
def
|
| 66 |
-
"""
|
| 67 |
-
|
| 68 |
-
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
for speaker, message in messages:
|
| 75 |
-
count = sum(1 for word in humor_keywords if word in message.lower())
|
| 76 |
-
humor_count[speaker] = humor_count.get(speaker, 0) + count
|
| 77 |
-
return humor_count
|
| 78 |
|
| 79 |
-
def infer_relationships(messages):
|
| 80 |
-
"""Infers relationships based on interactions."""
|
| 81 |
-
relationship_scores = {}
|
| 82 |
-
for speaker, message in messages:
|
| 83 |
-
doc = nlp(message)
|
| 84 |
-
for ent in doc.ents:
|
| 85 |
-
if ent.label_ == "PERSON":
|
| 86 |
-
key = tuple(sorted([speaker, ent.text]))
|
| 87 |
-
relationship_scores[key] = relationship_scores.get(key, 0) + 1
|
| 88 |
return relationship_scores
|
| 89 |
|
| 90 |
-
def
|
| 91 |
-
"""
|
| 92 |
-
|
| 93 |
-
for (p1, p2), weight in relationships.items():
|
| 94 |
-
G.add_edge(p1, p2, weight=weight)
|
| 95 |
-
plt.figure(figsize=(8, 6))
|
| 96 |
-
pos = nx.spring_layout(G)
|
| 97 |
-
nx.draw(G, pos, with_labels=True, node_size=3000, node_color="lightblue", edge_color="gray")
|
| 98 |
-
st.pyplot(plt)
|
| 99 |
|
| 100 |
def main():
|
| 101 |
-
st.title("Chat
|
| 102 |
-
|
| 103 |
-
uploaded_file = st.file_uploader("
|
| 104 |
|
| 105 |
if uploaded_file is not None:
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
if humor_scores:
|
| 117 |
-
funniest = max(humor_scores, key=humor_scores.get)
|
| 118 |
-
st.write(f"😂 {funniest} is the funniest with {humor_scores[funniest]} laugh reactions!")
|
| 119 |
-
else:
|
| 120 |
-
st.write("No humor detected.")
|
| 121 |
-
|
| 122 |
-
st.subheader("Relationship Graph")
|
| 123 |
-
if relationship_scores:
|
| 124 |
-
generate_graph(relationship_scores)
|
| 125 |
-
else:
|
| 126 |
-
st.write("No relationships detected.")
|
| 127 |
|
| 128 |
if __name__ == "__main__":
|
| 129 |
main()
|
|
|
|
|
|
|
|
|
|
| 1 |
import spacy
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import json
|
| 3 |
+
import pdfplumber
|
| 4 |
import docx
|
| 5 |
from bs4 import BeautifulSoup
|
| 6 |
+
from io import StringIO
|
| 7 |
+
import streamlit as st
|
| 8 |
|
| 9 |
+
nlp = spacy.load("en_core_web_sm")
|
| 10 |
+
nlp.max_length = 50_000_000 # Increase max length to handle large texts
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
def extract_text_from_file(uploaded_file):
|
| 13 |
+
"""Extract text from various file formats."""
|
| 14 |
file_type = uploaded_file.name.split(".")[-1].lower()
|
|
|
|
| 15 |
|
| 16 |
if file_type == "txt":
|
| 17 |
+
text = uploaded_file.getvalue().decode("utf-8")
|
| 18 |
+
|
| 19 |
elif file_type == "html":
|
| 20 |
+
soup = BeautifulSoup(uploaded_file.getvalue(), "html.parser")
|
| 21 |
text = soup.get_text()
|
| 22 |
+
|
| 23 |
elif file_type == "json":
|
| 24 |
data = json.load(uploaded_file)
|
| 25 |
+
text = "\n".join(str(value) for value in data.values()) if isinstance(data, dict) else json.dumps(data)
|
| 26 |
+
|
| 27 |
elif file_type == "pdf":
|
| 28 |
+
text = ""
|
| 29 |
+
with pdfplumber.open(uploaded_file) as pdf:
|
| 30 |
+
for page in pdf.pages:
|
| 31 |
+
text += page.extract_text() + "\n"
|
| 32 |
+
|
| 33 |
elif file_type == "docx":
|
| 34 |
doc = docx.Document(uploaded_file)
|
| 35 |
text = "\n".join([para.text for para in doc.paragraphs])
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
else:
|
| 38 |
+
raise ValueError("Unsupported file format")
|
| 39 |
|
| 40 |
+
return text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
|
| 42 |
+
def infer_relationships(chat_data):
|
| 43 |
+
"""Process large text inputs in chunks to avoid memory issues."""
|
| 44 |
+
relationship_scores = []
|
| 45 |
+
max_chars = 1_000_000 # Keep within spaCy's safe limits
|
| 46 |
|
| 47 |
+
for i in range(0, len(chat_data), max_chars):
|
| 48 |
+
chunk = chat_data[i : i + max_chars]
|
| 49 |
+
doc = nlp(chunk) # Process each chunk separately
|
| 50 |
+
relationship_scores.append(analyze_relationships(doc))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
return relationship_scores
|
| 53 |
|
| 54 |
+
def analyze_relationships(doc):
|
| 55 |
+
"""Placeholder function for analyzing relationships in text."""
|
| 56 |
+
return {"entities": [(ent.text, ent.label_) for ent in doc.ents]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
def main():
|
| 59 |
+
st.title("Chat Relationship Analyzer")
|
| 60 |
+
|
| 61 |
+
uploaded_file = st.file_uploader("Upload a file", type=["txt", "html", "json", "pdf", "docx"])
|
| 62 |
|
| 63 |
if uploaded_file is not None:
|
| 64 |
+
try:
|
| 65 |
+
chat_text = extract_text_from_file(uploaded_file)
|
| 66 |
+
if len(chat_text) > nlp.max_length:
|
| 67 |
+
st.warning("Text is too long. Processing in chunks.")
|
| 68 |
+
|
| 69 |
+
relationship_scores = infer_relationships(chat_text)
|
| 70 |
+
st.json(relationship_scores)
|
| 71 |
+
|
| 72 |
+
except Exception as e:
|
| 73 |
+
st.error(f"Error: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
if __name__ == "__main__":
|
| 76 |
main()
|