raz-1412 commited on
Commit
e34b6a7
·
verified ·
1 Parent(s): 8327a5b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -97
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 fitz # PyMuPDF
12
  import docx
13
  from bs4 import BeautifulSoup
 
 
14
 
15
- # Ensure spaCy model is downloaded
16
- def ensure_spacy_model():
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
- """Extracts text from various file types."""
32
  file_type = uploaded_file.name.split(".")[-1].lower()
33
- text = ""
34
 
35
  if file_type == "txt":
36
- text = uploaded_file.read().decode("utf-8").strip()
 
37
  elif file_type == "html":
38
- soup = BeautifulSoup(uploaded_file.read(), "html.parser")
39
  text = soup.get_text()
 
40
  elif file_type == "json":
41
  data = json.load(uploaded_file)
42
- text = "\n".join(map(str, data.values())) if isinstance(data, dict) else "\n".join(map(str, data))
 
43
  elif file_type == "pdf":
44
- doc = fitz.open(stream=uploaded_file.read(), filetype="pdf")
45
- text = "\n".join([page.get_text("text") for page in doc])
 
 
 
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
- return text.strip()
 
54
 
55
- def parse_chat_log(chat_text):
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 analyze_sentiment(messages):
66
- """Analyzes sentiment of messages."""
67
- results = sentiment_pipeline(messages)
68
- return [res['label'] for res in results]
69
 
70
- def detect_humor(messages):
71
- """Detects humor based on laughter-related keywords."""
72
- humor_keywords = {"lol", "haha", "lmao", "rofl", "😂", "🤣"}
73
- humor_count = {}
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 generate_graph(relationships):
91
- """Generates a graph of relationships."""
92
- G = nx.Graph()
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 Affinity Analyzer")
102
- st.write("Upload a chat log to analyze affinity between participants.")
103
- uploaded_file = st.file_uploader("Choose a chat log (TXT, HTML, JSON, PDF, DOCX)", type=["txt", "html", "json", "pdf", "docx"])
104
 
105
  if uploaded_file is not None:
106
- chat_text = extract_text_from_file(uploaded_file)
107
- if not chat_text:
108
- st.error("Error: No valid chat messages found.")
109
- return
110
-
111
- chat_data = parse_chat_log(chat_text)
112
- humor_scores = detect_humor(chat_data)
113
- relationship_scores = infer_relationships(chat_data)
114
-
115
- st.subheader("Funniest Person")
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()