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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
import json
|
3 |
+
import os
|
4 |
+
from collections import Counter
|
5 |
+
from langgraph.graph import StateGraph, END
|
6 |
+
from typing import TypedDict, Annotated
|
7 |
+
import operator
|
8 |
+
from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage, ToolMessage, AIMessage
|
9 |
+
from langchain_community.tools.tavily_search import TavilySearchResults
|
10 |
+
from langchain.chat_models import init_chat_model
|
11 |
+
import gradio as gr
|
12 |
+
from langchain.schema import HumanMessage
|
13 |
+
from langchain.tools import tool
|
14 |
+
import ebooklib
|
15 |
+
from ebooklib import epub, ITEM_DOCUMENT
|
16 |
+
from bs4 import BeautifulSoup
|
17 |
+
import matplotlib.pyplot as plt
|
18 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer, pipeline
|
19 |
+
import numpy as np
|
20 |
+
import tempfile
|
21 |
+
from typing import List, Dict
|
22 |
+
import seaborn as sns
|
23 |
+
import re
|
24 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
25 |
+
import nltk
|
26 |
+
from nltk.corpus import stopwords
|
27 |
+
|
28 |
+
MISTRAL_API_KEY = os.getenv("MISTRAL_API_KEY")
|
29 |
+
|
30 |
+
def extract_clean_chapters(epub_path):
|
31 |
+
skip_titles = ['about the author', 'acknowledgment', 'acknowledgements',
|
32 |
+
'copyright', 'table of contents', 'dedication', 'preface', 'foreword']
|
33 |
+
book = epub.read_epub(epub_path)
|
34 |
+
chapters = {}
|
35 |
+
|
36 |
+
chapter_index = 1
|
37 |
+
for item in book.get_items():
|
38 |
+
if item.get_type() == ebooklib.ITEM_DOCUMENT:
|
39 |
+
soup = BeautifulSoup(item.get_content(), 'html.parser')
|
40 |
+
text = soup.get_text().strip()
|
41 |
+
title_tag = soup.title.string if soup.title else None
|
42 |
+
title = title_tag.strip() if title_tag else f"Chapter {chapter_index}"
|
43 |
+
|
44 |
+
title_lower = title.lower()
|
45 |
+
if any(skip in title_lower for skip in skip_titles):
|
46 |
+
continue
|
47 |
+
if len(text.split()) < 300:
|
48 |
+
continue
|
49 |
+
|
50 |
+
chapters[title] = text
|
51 |
+
chapter_index += 1
|
52 |
+
|
53 |
+
return chapters
|
54 |
+
|
55 |
+
def plot_word_count(chapter_word_counts):
|
56 |
+
titles = list(chapter_word_counts.keys())
|
57 |
+
word_counts = list(chapter_word_counts.values())
|
58 |
+
|
59 |
+
fig, ax = plt.subplots(figsize=(12, 6))
|
60 |
+
ax.bar(range(len(titles)), word_counts, color='skyblue')
|
61 |
+
ax.set_xticks(range(len(titles)))
|
62 |
+
ax.set_xticklabels([f"{i+1}" for i in range(len(titles))], rotation=90)
|
63 |
+
ax.set_xlabel("Chapters")
|
64 |
+
ax.set_ylabel("Word Count")
|
65 |
+
ax.set_title("Word Count per Chapter")
|
66 |
+
plt.tight_layout()
|
67 |
+
|
68 |
+
return fig # Return the figure directly
|
69 |
+
|
70 |
+
@tool
|
71 |
+
def get_chapter_wordcount_plot(book_path: str) -> str:
|
72 |
+
"""
|
73 |
+
Extracts chapter-wise word counts from an EPUB book and plots a bar chart.
|
74 |
+
|
75 |
+
Args:
|
76 |
+
book_path: Path to the .epub file.
|
77 |
+
|
78 |
+
Returns:
|
79 |
+
A dictionary with total chapter count, average word count, and plot image path.
|
80 |
+
"""
|
81 |
+
chapters = extract_clean_chapters(book_path)
|
82 |
+
chapter_word_counts = {title: len(text.split()) for title, text in chapters.items()}
|
83 |
+
|
84 |
+
avg_words = sum(chapter_word_counts.values()) / len(chapter_word_counts) if chapter_word_counts else 0
|
85 |
+
fig = plot_word_count(chapter_word_counts)
|
86 |
+
|
87 |
+
image_path = "/tmp/wordcount_plot.png"
|
88 |
+
fig.savefig(image_path)
|
89 |
+
plt.close(fig) # free memory
|
90 |
+
return image_path
|
91 |
+
|
92 |
+
|
93 |
+
# Load sentiment model + tokenizer with correct label mapping
|
94 |
+
model = AutoModelForSequenceClassification.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
95 |
+
tokenizer = AutoTokenizer.from_pretrained("cardiffnlp/twitter-roberta-base-sentiment")
|
96 |
+
model.config.id2label = {
|
97 |
+
0: "negative",
|
98 |
+
1: "neutral",
|
99 |
+
2: "positive"
|
100 |
+
}
|
101 |
+
|
102 |
+
sentiment_pipeline = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
|
103 |
+
|
104 |
+
def extract_epub_text(epub_path: str) -> str:
|
105 |
+
book = epub.read_epub(epub_path)
|
106 |
+
text = []
|
107 |
+
for item in book.get_items():
|
108 |
+
if item.get_type() == ITEM_DOCUMENT:
|
109 |
+
soup = BeautifulSoup(item.get_content(), "html.parser")
|
110 |
+
text.append(soup.get_text())
|
111 |
+
return ' '.join(' '.join(text).split())
|
112 |
+
|
113 |
+
def extract_text(file_path: str) -> str:
|
114 |
+
if file_path.endswith(".epub"):
|
115 |
+
return extract_epub_text(file_path)
|
116 |
+
else:
|
117 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
118 |
+
return ' '.join(f.read().split())
|
119 |
+
|
120 |
+
def chunk_text(text: str, chunk_size: int = 1000) -> List[str]:
|
121 |
+
words = text.split()
|
122 |
+
return [' '.join(words[i:i + chunk_size]) for i in range(0, len(words), chunk_size)]
|
123 |
+
|
124 |
+
def analyze_chunks(chunks: List[str]) -> List[float]:
|
125 |
+
sentiment_scores = []
|
126 |
+
for i, chunk in enumerate(chunks): # analyze all chunks
|
127 |
+
result = sentiment_pipeline(chunk[:512])[0]
|
128 |
+
# print(f"Chunk {i}: {result}") # useful for debugging
|
129 |
+
label = result['label'].lower()
|
130 |
+
confidence = result['score']
|
131 |
+
if label == "positive":
|
132 |
+
sentiment_scores.append(confidence)
|
133 |
+
elif label == "negative":
|
134 |
+
sentiment_scores.append(-confidence)
|
135 |
+
else: # neutral
|
136 |
+
sentiment_scores.append(0.0)
|
137 |
+
return sentiment_scores
|
138 |
+
|
139 |
+
def smooth(scores: List[float], window: int = 3) -> List[float]:
|
140 |
+
return np.convolve(scores, np.ones(window)/window, mode='same')
|
141 |
+
|
142 |
+
def plot_sentiment_arc(scores: List[float], title="Sentiment Arc"):
|
143 |
+
fig, ax = plt.subplots(figsize=(10, 4))
|
144 |
+
ax.plot(scores, color='teal', linewidth=2)
|
145 |
+
ax.set_title(title)
|
146 |
+
ax.set_xlabel("Book Position (Chunks)")
|
147 |
+
ax.set_ylabel("Sentiment Score")
|
148 |
+
ax.grid(True)
|
149 |
+
plt.tight_layout()
|
150 |
+
return fig # return the matplotlib figure
|
151 |
+
|
152 |
+
@tool
|
153 |
+
def get_sentiment_arc(book_path: str) -> str:
|
154 |
+
"""
|
155 |
+
Generates a sentiment arc from a .txt or .epub book file.
|
156 |
+
|
157 |
+
Args:
|
158 |
+
book_path: Path to the .txt or .epub book file.
|
159 |
+
|
160 |
+
Returns:
|
161 |
+
A dictionary with chunk count, average sentiment score, and plot path.
|
162 |
+
"""
|
163 |
+
text = extract_text(book_path)
|
164 |
+
chunks = chunk_text(text)
|
165 |
+
raw_scores = analyze_chunks(chunks)
|
166 |
+
smoothed_scores = smooth(raw_scores)
|
167 |
+
|
168 |
+
fig = plot_sentiment_arc(smoothed_scores)
|
169 |
+
|
170 |
+
image_path = "/tmp/sentiment_arc.png"
|
171 |
+
fig.savefig(image_path)
|
172 |
+
plt.close(fig) # free memory
|
173 |
+
return image_path
|
174 |
+
|
175 |
+
|
176 |
+
nltk.download('stopwords')
|
177 |
+
STOPWORDS = set(stopwords.words('english'))
|
178 |
+
|
179 |
+
def extract_epub_chapters(epub_path: str) -> List[str]:
|
180 |
+
book = epub.read_epub(epub_path)
|
181 |
+
chapters = []
|
182 |
+
for item in book.get_items():
|
183 |
+
if item.get_type() == ITEM_DOCUMENT:
|
184 |
+
soup = BeautifulSoup(item.get_content(), "html.parser")
|
185 |
+
text = soup.get_text()
|
186 |
+
cleaned = re.sub(r'\s+', ' ', text.strip())
|
187 |
+
if len(cleaned.split()) > 50:
|
188 |
+
chapters.append(cleaned)
|
189 |
+
return chapters
|
190 |
+
|
191 |
+
def extract_chapters(file_path: str) -> List[str]:
|
192 |
+
if file_path.endswith(".epub"):
|
193 |
+
return extract_epub_chapters(file_path)
|
194 |
+
else:
|
195 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
196 |
+
full_text = f.read()
|
197 |
+
split_text = re.split(r'\n\s*(Chapter|CHAPTER|chapter)\s+\d+', full_text)
|
198 |
+
return [t.strip() for t in split_text if len(t.split()) > 50]
|
199 |
+
|
200 |
+
def clean_text(text: str) -> str:
|
201 |
+
text = text.lower()
|
202 |
+
text = re.sub(r'[^a-z\s]', '', text)
|
203 |
+
return ' '.join([w for w in text.split() if w not in STOPWORDS])
|
204 |
+
|
205 |
+
def extract_theme_words(chapters: List[str], top_n: int = 10) -> List[str]:
|
206 |
+
cleaned = [clean_text(c) for c in chapters]
|
207 |
+
vectorizer = TfidfVectorizer(max_features=1000)
|
208 |
+
tfidf_matrix = vectorizer.fit_transform(cleaned)
|
209 |
+
summed_scores = np.asarray(tfidf_matrix.sum(axis=0)).flatten()
|
210 |
+
word_scores = list(zip(vectorizer.get_feature_names_out(), summed_scores))
|
211 |
+
top_words = sorted(word_scores, key=lambda x: x[1], reverse=True)[:top_n]
|
212 |
+
return [w for w, _ in top_words]
|
213 |
+
|
214 |
+
def compute_normalized_frequencies(chapters: List[str], theme_words: List[str]) -> List[Dict[str, float]]:
|
215 |
+
freq_matrix = []
|
216 |
+
for chap in chapters:
|
217 |
+
tokens = clean_text(chap).split()
|
218 |
+
total = len(tokens)
|
219 |
+
freqs = {w: tokens.count(w) / total for w in theme_words}
|
220 |
+
freq_matrix.append(freqs)
|
221 |
+
return freq_matrix
|
222 |
+
|
223 |
+
def plot_heatmap(freq_matrix: List[Dict[str, float]], theme_words: List[str]) -> str:
|
224 |
+
data = np.array([[chapter[word] for word in theme_words] for chapter in freq_matrix])
|
225 |
+
fig, ax = plt.subplots(figsize=(15, 12), dpi=100)
|
226 |
+
sns.heatmap(data, annot=True, cmap='viridis',
|
227 |
+
xticklabels=theme_words,
|
228 |
+
yticklabels=[f"C{i+1}" for i in range(len(freq_matrix))],
|
229 |
+
ax=ax)
|
230 |
+
|
231 |
+
ax.set_xlabel("Theme Words")
|
232 |
+
ax.set_ylabel("Chapters")
|
233 |
+
ax.set_title("Word Frequency Heatmap")
|
234 |
+
plt.tight_layout()
|
235 |
+
|
236 |
+
return fig # return the matplotlib figure
|
237 |
+
|
238 |
+
@tool
|
239 |
+
def get_word_frequency_heatmap(book_path: str, top_n_words: int = 10) -> str:
|
240 |
+
"""
|
241 |
+
Generates a word frequency heatmap from a .txt or .epub book.
|
242 |
+
|
243 |
+
Args:
|
244 |
+
book_path: Path to the .txt or .epub book file.
|
245 |
+
top_n_words: Number of top theme words to extract via TF-IDF.
|
246 |
+
|
247 |
+
Returns:
|
248 |
+
A dictionary with chapter count, theme words, and heatmap image path.
|
249 |
+
"""
|
250 |
+
chapters = extract_chapters(book_path)
|
251 |
+
theme_words = extract_theme_words(chapters, top_n=top_n_words)
|
252 |
+
freq_matrix = compute_normalized_frequencies(chapters, theme_words)
|
253 |
+
fig = plot_heatmap(freq_matrix, theme_words)
|
254 |
+
|
255 |
+
image_path = "/tmp/word_freq_heatmap.png"
|
256 |
+
fig.savefig(image_path)
|
257 |
+
plt.close(fig) # free memory
|
258 |
+
return image_path
|
259 |
+
|
260 |
+
|
261 |
+
class AgentState(TypedDict):
|
262 |
+
messages: Annotated[list[AnyMessage], operator.add]
|
263 |
+
|
264 |
+
|
265 |
+
class Agent:
|
266 |
+
|
267 |
+
def __init__(self, model, tools, system=""):
|
268 |
+
self.system = system
|
269 |
+
graph = StateGraph(AgentState)
|
270 |
+
graph.add_node("llm", self.call_mistral_ai)
|
271 |
+
graph.add_node("action", self.take_action)
|
272 |
+
graph.add_node("final", self.final_answer)
|
273 |
+
graph.add_conditional_edges(
|
274 |
+
"llm",
|
275 |
+
self.exists_action,
|
276 |
+
{True: "action", False: END}
|
277 |
+
)
|
278 |
+
graph.add_edge("action", "final") # π
|
279 |
+
graph.add_edge("final", END) # π
|
280 |
+
graph.set_entry_point("llm")
|
281 |
+
self.graph = graph.compile()
|
282 |
+
self.tools = {t.name: t for t in tools}
|
283 |
+
self.model = model.bind_tools(tools)
|
284 |
+
|
285 |
+
def exists_action(self, state: AgentState):
|
286 |
+
result = state['messages'][-1]
|
287 |
+
return len(result.tool_calls) > 0
|
288 |
+
|
289 |
+
def call_mistral_ai(self, state: AgentState):
|
290 |
+
messages = state['messages']
|
291 |
+
if self.system:
|
292 |
+
messages = [SystemMessage(content=self.system)] + messages
|
293 |
+
message = self.model.invoke(messages)
|
294 |
+
return {'messages': [message]}
|
295 |
+
|
296 |
+
def take_action(self, state: AgentState):
|
297 |
+
tool_calls = state['messages'][-1].tool_calls
|
298 |
+
results = []
|
299 |
+
for t in tool_calls:
|
300 |
+
print(f"Calling: {t}")
|
301 |
+
if not t['name'] in self.tools: # check for bad tool name from LLM
|
302 |
+
print("\n ....bad tool name....")
|
303 |
+
result = "bad tool name, retry" # instruct LLM to retry if bad
|
304 |
+
else:
|
305 |
+
result = self.tools[t['name']].invoke(t['args'])
|
306 |
+
results.append(ToolMessage(tool_call_id=t['id'], name=t['name'], content=str(result)))
|
307 |
+
return {'messages': results}
|
308 |
+
|
309 |
+
def final_answer(self, state: AgentState):
|
310 |
+
"""Return the final tool output cleanly."""
|
311 |
+
return {"messages": [AIMessage(content=state['messages'][-1].content.strip())]}
|
312 |
+
|
313 |
+
|
314 |
+
|
315 |
+
prompt = """You are a reading Assistant. Your task is to help users analyze the novel, books, text.
|
316 |
+
|
317 |
+
Use the available tools to get overall summary of the book, novel. You can make multiple lookups if necessary, either together or in sequence.
|
318 |
+
|
319 |
+
Your goal is to ensure help the user.
|
320 |
+
|
321 |
+
"""
|
322 |
+
|
323 |
+
model = init_chat_model("mistral-large-latest", model_provider="mistralai")
|
324 |
+
abot = Agent(model, [get_chapter_wordcount_plot, get_word_frequency_heatmap, get_sentiment_arc], system=prompt)
|
325 |
+
|
326 |
+
|
327 |
+
def query_agent(epub_file, prompt):
|
328 |
+
file_path = epub_file.name
|
329 |
+
user_input = f"{file_path} {prompt}"
|
330 |
+
messages = [HumanMessage(content=user_input)]
|
331 |
+
|
332 |
+
result = abot.graph.invoke({"messages": messages})
|
333 |
+
final_output = result['messages'][-1].content.strip()
|
334 |
+
|
335 |
+
# If tool returned a file path to an image
|
336 |
+
if os.path.exists(final_output) and final_output.endswith(".png"):
|
337 |
+
return final_output
|
338 |
+
else:
|
339 |
+
return f"No plot image found. Raw response: {final_output}"
|
340 |
+
|
341 |
+
gr.Interface(
|
342 |
+
fn=query_agent,
|
343 |
+
inputs=[
|
344 |
+
gr.File(label="Upload EPUB", type="filepath"),
|
345 |
+
gr.Textbox(label="Prompt", placeholder="e.g., Generate word frequency heatmap.")
|
346 |
+
],
|
347 |
+
outputs=gr.Image(label="Sentiment Arc or Heatmap", type="filepath"),
|
348 |
+
title="Book Analyzer"
|
349 |
+
).launch(share=True)
|
requirements.txt
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Core dependencies
|
2 |
+
requests
|
3 |
+
jsonlib
|
4 |
+
numpy
|
5 |
+
matplotlib
|
6 |
+
seaborn
|
7 |
+
scikit-learn
|
8 |
+
beautifulsoup4
|
9 |
+
ebooklib
|
10 |
+
nltk
|
11 |
+
transformers
|
12 |
+
torch # Required for transformers models
|
13 |
+
gradio
|
14 |
+
langchain
|
15 |
+
langgraph
|
16 |
+
langchain-community
|
17 |
+
langchain-core
|
18 |
+
langchain_mistralai
|
19 |
+
tavily-python # for TavilySearchResults tool
|
20 |
+
typing-extensions
|
21 |
+
mistralai
|
22 |
+
# Specific versions for stability (optional, recommended)
|
23 |
+
# You can lock these later with pip freeze if needed
|