forked from troglodytelabs/bookmARC
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1245 lines (1089 loc) · 47.9 KB
/
app.py
File metadata and controls
1245 lines (1089 loc) · 47.9 KB
1
2
3
4
5
6
7
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Streamlit app for EmoArc - Emotion Trajectory Analysis and Recommendation System
"""
import sys
import os
import streamlit as st
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from pyspark.sql.functions import col
# Add src to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "src"))
from core import (
create_spark_session,
load_trajectories,
load_metadata,
get_input_trajectory,
find_books_by_emotion_preferences,
)
from recommender import recommend, WEIGHT_PRESETS, get_weight_preset
# Page config
st.set_page_config(
page_title="EmoArc - Emotion Trajectory Analysis",
page_icon="📚",
layout="wide",
initial_sidebar_state="expanded",
)
# Initialize session state
if "spark" not in st.session_state:
st.session_state.spark = None
if "emotion_lexicon" not in st.session_state:
st.session_state.emotion_lexicon = None
if "vad_lexicon" not in st.session_state:
st.session_state.vad_lexicon = None
if "metadata_df" not in st.session_state:
st.session_state.metadata_df = None
@st.cache_resource
def get_spark_session():
"""Create and cache Spark session."""
return create_spark_session("EmoArc Streamlit")
def search_books_by_title(title_query, metadata_df, limit=20):
"""Search books by title."""
if not title_query:
return None
# Case-insensitive search
results = (
metadata_df.filter(col("Title").like(f"%{title_query}%"))
.select(
col("Etext Number").alias("book_id"),
col("Title").alias("title"),
col("Authors").alias("author"),
)
.limit(limit)
)
return results
def plot_mini_trajectory(emotion_trajectory, title, height=200):
"""Plot a mini emotion trajectory for a book (used in recommendations)."""
try:
if emotion_trajectory is None or len(emotion_trajectory) == 0:
return None
# emotion_trajectory is array of [chunk_idx, anger, anticipation, disgust, fear, joy, sadness, surprise, trust]
# Indices: [0, 1, 2, 3, 4, 5, 6, 7, 8 ]
# Extract data - handle both list and numpy array
chunks = list(range(len(emotion_trajectory)))
fig = go.Figure()
# Plot main emotions (Joy, Sadness, Fear) for a cleaner look
# Joy=5, Sadness=6, Fear=4 in the array
main_emotions = [
(5, "Joy", "#f1c40f"),
(6, "Sadness", "#3498db"),
(4, "Fear", "#2c3e50"),
]
for idx, name, color in main_emotions:
try:
values = [float(row[idx]) for row in emotion_trajectory]
fig.add_trace(
go.Scatter(
x=chunks,
y=values,
mode="lines",
name=name,
line=dict(color=color, width=2),
opacity=0.7,
)
)
except (IndexError, TypeError):
# Skip this emotion if data is malformed
continue
if len(fig.data) == 0:
return None
fig.update_layout(
title=dict(
text=f"📈 {title[:30]}..." if len(title) > 30 else f"📈 {title}",
font=dict(size=12),
),
height=height,
margin=dict(l=10, r=10, t=30, b=10),
showlegend=True,
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1,
font=dict(size=9),
),
xaxis=dict(showticklabels=False, title=""),
yaxis=dict(showticklabels=False, title=""),
template="plotly_white",
)
return fig
except Exception:
# Return None if anything fails - don't crash the app
return None
def interpret_similarity(similarity, rec_trajectory, input_trajectory):
"""Generate human-readable interpretation of why books are similar."""
if similarity > 0.9:
strength = "very similar"
elif similarity > 0.8:
strength = "similar"
elif similarity > 0.7:
strength = "somewhat similar"
else:
strength = "loosely related"
return f"This book has a **{strength}** emotional arc to your selected book."
def plot_topic_distribution(book_topics_pd, book_title, num_topics=10):
"""Plot topic distribution for a book using Plotly."""
if book_topics_pd is None or len(book_topics_pd) == 0:
return None
topics = book_topics_pd.iloc[0]["book_topics"]
if topics is None:
return None
# Create bar chart
fig = go.Figure()
topic_labels = [f"Topic {i + 1}" for i in range(len(topics))]
fig.add_trace(
go.Bar(
x=topic_labels,
y=topics,
marker=dict(color="steelblue", line=dict(color="navy", width=1)),
text=[f"{t:.3f}" for t in topics],
textposition="outside",
)
)
fig.update_layout(
title=f"Topic Distribution: {book_title}",
xaxis_title="Topic",
yaxis_title="Probability",
height=400,
template="plotly_white",
showlegend=False,
)
return fig
def plot_emotion_trajectory(chunk_scores_pd, book_title):
"""Plot emotion trajectory for a book using Plotly."""
# Create subplots
fig = make_subplots(
rows=2,
cols=1,
subplot_titles=(
f"Emotion Trajectory: {book_title}",
"Valence-Arousal-Dominance Trajectory",
),
vertical_spacing=0.12,
row_heights=[0.5, 0.5],
)
emotions = [
"anger",
"anticipation",
"disgust",
"fear",
"joy",
"sadness",
"surprise",
"trust",
]
colors = [
"red",
"orange",
"brown",
"black",
"gold",
"blue",
"purple",
"green",
]
# Plot emotions
has_data = False
for emotion, color in zip(emotions, colors):
if emotion in chunk_scores_pd.columns:
if chunk_scores_pd[emotion].any():
has_data = True
fig.add_trace(
go.Scatter(
x=chunk_scores_pd["chunk_index"],
y=chunk_scores_pd[emotion],
mode="lines+markers",
name=emotion.capitalize(),
line=dict(color=color, width=2),
marker=dict(size=4),
opacity=0.7,
),
row=1,
col=1,
)
if not has_data:
fig.add_annotation(
text="No Emotion Data Available",
xref="x domain",
yref="y domain",
x=0.5,
y=0.5,
showarrow=False,
row=1,
col=1,
)
# Plot VAD scores
vad_has_data = False
if "avg_valence" in chunk_scores_pd.columns:
if chunk_scores_pd["avg_valence"].any():
vad_has_data = True
fig.add_trace(
go.Scatter(
x=chunk_scores_pd["chunk_index"],
y=chunk_scores_pd["avg_valence"],
mode="lines+markers",
name="Valence",
line=dict(color="purple", width=2),
marker=dict(size=4),
),
row=2,
col=1,
)
if "avg_arousal" in chunk_scores_pd.columns:
if chunk_scores_pd["avg_arousal"].any():
vad_has_data = True
fig.add_trace(
go.Scatter(
x=chunk_scores_pd["chunk_index"],
y=chunk_scores_pd["avg_arousal"],
mode="lines+markers",
name="Arousal",
line=dict(color="orange", width=2, dash="dash"),
marker=dict(size=4),
),
row=2,
col=1,
)
if "avg_dominance" in chunk_scores_pd.columns:
if chunk_scores_pd["avg_dominance"].any():
vad_has_data = True
fig.add_trace(
go.Scatter(
x=chunk_scores_pd["chunk_index"],
y=chunk_scores_pd["avg_dominance"],
mode="lines+markers",
name="Dominance",
line=dict(color="green", width=2, dash="dot"),
marker=dict(size=4),
),
row=2,
col=1,
)
if not vad_has_data:
fig.add_annotation(
text="No VAD Data Available",
xref="x domain",
yref="y domain",
x=0.5,
y=0.5,
showarrow=False,
row=2,
col=1,
)
# Update x-axis properties
fig.update_xaxes(title_text="Chunk Index", row=1, col=1)
fig.update_xaxes(title_text="Chunk Index", row=2, col=1)
# Update y-axis properties
fig.update_yaxes(title_text="Emotion Score", row=1, col=1)
fig.update_yaxes(title_text="VAD Score", row=2, col=1)
# Update layout
fig.update_layout(
height=800,
showlegend=True,
legend=dict(orientation="v", yanchor="top", y=1, xanchor="left", x=1.02),
hovermode="x unified",
template="plotly_white",
)
return fig
def main():
"""Main Streamlit app."""
st.title("📚 EmoArc - Emotion Trajectory Analysis")
st.markdown(
"Analyze emotion trajectories in books and get recommendations based on emotional story arcs"
)
# Sidebar
st.sidebar.title("Navigation")
page = st.sidebar.radio(
"Choose a page",
[
"Book Analysis & Recommendations",
"Explore Books",
"Find Books by Emotion Preferences",
"About",
],
)
# Initialize Spark session
if st.session_state.spark is None:
with st.spinner("Initializing Spark session..."):
st.session_state.spark = get_spark_session()
# Page routing
if page == "Book Analysis & Recommendations":
show_book_analysis_and_recommendations()
elif page == "Explore Books":
show_explore_books()
elif page == "Find Books by Emotion Preferences":
show_find_books_by_emotions()
elif page == "About":
show_about()
def show_book_analysis_and_recommendations():
"""Show combined book analysis and recommendations page."""
st.header("Book Analysis & Recommendations")
st.markdown("Analyze emotion trajectories and get book recommendations")
# Output directory (default, not shown to user)
output_dir = "output"
trajectories_path = f"{output_dir}/trajectories"
trajectories_available = os.path.exists(trajectories_path)
if not trajectories_available:
st.info(
"💡 Tip: Run `python main.py` first to generate trajectories for recommendations."
)
else:
# Show how many books are available for comparison
try:
spark = st.session_state.spark
trajectories = load_trajectories(spark, output_dir)
if trajectories is not None:
total_books = trajectories.count()
has_embeddings = "book_embedding" in trajectories.columns
has_topics = "book_topics" in trajectories.columns
features_info = []
if has_embeddings:
features_info.append("embeddings")
if has_topics:
features_info.append("topics")
features_str = (
f" (includes {', '.join(features_info)})" if features_info else ""
)
st.info(
f"📚 **{total_books}** books available in trajectory database for recommendations{features_str}. "
f"(Recommendations will compare against these {total_books} books)"
)
except Exception:
# If we can't load trajectories, just show basic info
st.info(
"💡 Trajectories found. Recommendations will compare against books in the trajectory database."
)
# Input method selection
input_method = st.radio(
"Select input method",
["Search by Title", "Enter Book ID", "Upload Text File"],
horizontal=True,
)
book_id = None
text_file = None
if input_method == "Search by Title":
title_query = st.text_input(
"Enter book title (partial match supported)", key="title_search_input"
)
if title_query:
with st.spinner("Searching books..."):
spark = st.session_state.spark
metadata_df = load_metadata(spark)
results = search_books_by_title(title_query, metadata_df, limit=20)
if results:
results_pd = results.toPandas()
st.success(f"Found {len(results_pd)} books")
# Display results in a selectbox
book_options = [
f"{row['title']} by {row['author']} (ID: {row['book_id']})"
for _, row in results_pd.iterrows()
]
selected = st.selectbox(
"Select a book", book_options, key="book_selectbox"
)
# Store the selected book ID in session state (but don't use it until button is clicked)
if selected:
selected_idx = book_options.index(selected)
st.session_state.selected_book_id = results_pd.iloc[
selected_idx
]["book_id"]
else:
st.warning("No books found matching your query")
# Clear selected book if search fails
if "selected_book_id" in st.session_state:
del st.session_state.selected_book_id
else:
# Clear selected book when query is cleared
if "selected_book_id" in st.session_state:
del st.session_state.selected_book_id
elif input_method == "Enter Book ID":
book_id = st.text_input("Enter Gutenberg Book ID (e.g., 11)")
elif input_method == "Upload Text File":
uploaded_file = st.file_uploader("Upload a text file", type=["txt"])
if uploaded_file:
# Save uploaded file temporarily
temp_path = f"/tmp/{uploaded_file.name}"
with open(temp_path, "wb") as f:
f.write(uploaded_file.getbuffer())
text_file = temp_path
# Number of recommendations slider (shown if trajectories are available)
top_n = 10
rec_preset = "balanced"
if trajectories_available:
top_n = st.slider("Number of recommendations", 5, 20, 10, key="rec_slider")
# Recommendation preset selector
preset_options = {
"similar_experience": "📖 Similar Reading Experience (default)",
"balanced": "🎯 Balanced",
"similar_themes": "💡 Similar Themes & Topics",
"similar_style": "✍️ Similar Writing Style",
"genre_focused": "📚 Same Genre/Category",
}
rec_preset = st.selectbox(
"Recommendation focus",
options=list(preset_options.keys()),
format_func=lambda x: preset_options[x],
index=0,
key="rec_preset",
help="Choose what aspect of similarity to emphasize",
)
# Option to compute topics
compute_topics = st.checkbox(
"Compute topic modeling (slower but provides topic analysis)",
value=False,
key="compute_topics",
)
num_topics = 10
if compute_topics:
num_topics = st.slider("Number of topics", 5, 20, 10, key="num_topics_slider")
# Single button that does both analysis and recommendations
if st.button("Analyze Book & Get Recommendations", type="primary"):
# Get book_id from selected option if using title search
if input_method == "Search by Title" and "selected_book_id" in st.session_state:
book_id = st.session_state.selected_book_id
if book_id or text_file:
with st.spinner("Processing book (this may take a minute)..."):
spark = st.session_state.spark
try:
trajectory, chunk_scores, title, author, book_topics = (
get_input_trajectory(
spark,
book_id=book_id,
text_file=text_file,
output_dir=output_dir,
compute_topics=compute_topics,
num_topics=num_topics,
)
)
except Exception as e:
st.error(f"Error processing book: {e}")
trajectory = None
chunk_scores = None
title = None
author = None
book_topics = None
if trajectory is not None and chunk_scores is not None:
# Store in session state for recommendations
st.session_state.current_trajectory = trajectory
st.session_state.current_chunk_scores = chunk_scores
st.session_state.current_title = title
st.session_state.current_author = author
st.session_state.current_book_id = (
book_id if book_id else "text_file"
)
st.success("Analysis complete!")
# Display book info
col1, col2 = st.columns(2)
with col1:
st.subheader("Book Information")
st.write(f"**Title:** {title}")
st.write(f"**Author:** {author}")
if book_id:
st.write(f"**Book ID:** {book_id}")
# Display trajectory plot
st.subheader("Emotion Trajectory")
chunk_scores_pd = chunk_scores.orderBy("chunk_index").toPandas()
fig = plot_emotion_trajectory(chunk_scores_pd, title)
st.plotly_chart(fig, width="stretch")
# Display statistics
st.subheader("Emotion Statistics")
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Average Joy", f"{chunk_scores_pd['joy'].mean():.4f}")
st.metric(
"Average Sadness",
f"{chunk_scores_pd['sadness'].mean():.4f}",
)
with col2:
st.metric(
"Average Fear", f"{chunk_scores_pd['fear'].mean():.4f}"
)
st.metric(
"Average Anger", f"{chunk_scores_pd['anger'].mean():.4f}"
)
with col3:
st.metric(
"Average Valence",
f"{chunk_scores_pd['avg_valence'].mean():.4f}",
)
st.metric(
"Average Arousal",
f"{chunk_scores_pd['avg_arousal'].mean():.4f}",
)
with col4:
st.metric(
"Average Dominance",
f"{chunk_scores_pd['avg_dominance'].mean():.4f}",
)
st.metric("Number of Chunks", f"{len(chunk_scores_pd)}")
# Show emotional profile with interpretation
trajectory_pd = trajectory.toPandas().iloc[0]
st.subheader("📊 Emotional Profile")
# Calculate emotion ratios for interpretation
avg_emotions = {
"Joy": trajectory_pd.get("avg_joy", 0),
"Trust": trajectory_pd.get("avg_trust", 0),
"Anticipation": trajectory_pd.get("avg_anticipation", 0),
"Surprise": trajectory_pd.get("avg_surprise", 0),
"Sadness": trajectory_pd.get("avg_sadness", 0),
"Fear": trajectory_pd.get("avg_fear", 0),
"Anger": trajectory_pd.get("avg_anger", 0),
"Disgust": trajectory_pd.get("avg_disgust", 0),
}
total_emotion = sum(avg_emotions.values()) or 1
# Get dominant emotions
sorted_emotions = sorted(
avg_emotions.items(), key=lambda x: x[1], reverse=True
)
dominant = [e for e, v in sorted_emotions[:3] if v > 0]
# Interpret the emotional tone
valence = chunk_scores_pd["avg_valence"].mean()
arousal = chunk_scores_pd["avg_arousal"].mean()
# Generate interpretation
tone_desc = (
"positive"
if valence > 0.05
else ("negative" if valence < -0.05 else "neutral")
)
energy_desc = (
"high-energy"
if arousal > 0.05
else ("calm" if arousal < -0.05 else "moderate-paced")
)
st.markdown(f"""
**Overall Tone:** This book has a **{tone_desc}** emotional tone with **{energy_desc}** narrative.
**Dominant Emotions:** {", ".join(dominant) if dominant else "Balanced"}
""")
# Show emotion breakdown as progress bars
st.write("**Emotion Breakdown:**")
col1, col2 = st.columns(2)
emotions_list = list(avg_emotions.items())
for i, (emotion, value) in enumerate(emotions_list):
ratio = value / total_emotion if total_emotion > 0 else 0
with col1 if i < 4 else col2:
st.progress(
min(ratio * 2, 1.0),
text=f"{emotion}: {ratio * 100:.1f}%",
)
# Display topic modeling if available
if book_topics is not None:
st.divider()
st.subheader("📊 Topic Modeling")
book_topics_pd = book_topics.toPandas()
topic_fig = plot_topic_distribution(
book_topics_pd, title, num_topics
)
if topic_fig:
st.plotly_chart(topic_fig, width="stretch")
# Show top topics
topics = book_topics_pd.iloc[0]["book_topics"]
if topics:
# Get top 5 topics
topic_scores = [
(i, topics[i]) for i in range(len(topics))
]
topic_scores.sort(key=lambda x: x[1], reverse=True)
st.write("**Top Topics:**")
for rank, (topic_idx, score) in enumerate(
topic_scores[:5], 1
):
st.write(
f"{rank}. Topic {topic_idx + 1}: {score:.4f}"
)
else:
st.info("Topic distribution not available")
elif compute_topics:
st.info("💡 Topic modeling is being computed...")
# Automatically show recommendations if trajectories are available
if trajectories_available:
st.divider()
st.subheader("📚 Recommendations")
with st.spinner("Computing recommendations..."):
# Load trajectories for comparison
trajectories = load_trajectories(spark, output_dir)
if trajectories is None:
st.error("Could not load trajectories")
return
# Count total books available for comparison
total_books_count = trajectories.count()
# Get liked book ID
liked_id = trajectory.select("book_id").first()["book_id"]
# Check if the current book is already in the trajectories
current_book_in_trajectories = (
trajectories.filter(col("book_id") == liked_id).count()
> 0
)
# Display comparison info
if current_book_in_trajectories:
st.info(
f"📊 Comparing against **{total_books_count}** books from the trajectory database. "
f"(Note: The current book is included in this database)"
)
else:
st.info(
f"📊 Comparing against **{total_books_count}** books from the trajectory database."
)
# Combine trajectories
try:
all_trajectories = trajectories.unionByName(
trajectory, allowMissingColumns=True
)
except Exception:
trajectories_cols = set(trajectories.columns)
liked_cols = set(trajectory.columns)
common_cols = sorted(
list(trajectories_cols & liked_cols)
)
trajectories_aligned = trajectories.select(*common_cols)
liked_trajectory_aligned = trajectory.select(
*common_cols
)
all_trajectories = trajectories_aligned.union(
liked_trajectory_aligned
)
# Get recommendations with preset and metadata for genre similarity
metadata_df = load_metadata(spark)
recommendations = recommend(
spark,
all_trajectories,
liked_id,
top_n=top_n,
metadata_df=metadata_df,
preset=rec_preset,
)
# Display recommendations
st.success(
f"Top {top_n} recommendations for: **{title}** by {author}"
)
st.markdown("""
> 📖 **How to read this:** Books are ranked by how similar their emotional journey is to your selected book.
> Higher similarity = more similar emotional arc throughout the narrative.
""")
recs_pd = recommendations.toPandas()
# Get input book's trajectory for comparison
input_traj = (
trajectory.toPandas()
.iloc[0]
.get("emotion_trajectory", None)
)
for idx, row in recs_pd.iterrows():
similarity = row["similarity"]
# Determine similarity badge
if similarity > 0.9:
badge = "🎯 Very Similar"
elif similarity > 0.8:
badge = "✨ Similar"
elif similarity > 0.7:
badge = "📚 Related"
else:
badge = "🔗 Loosely Related"
with st.expander(
f"{idx + 1}. {row['title']} by {row['author']} — {badge} ({similarity:.0%})"
):
# Interpretation
rec_traj = row.get("emotion_trajectory", None)
st.markdown(
interpret_similarity(
similarity, rec_traj, input_traj
)
)
# Show mini trajectory if available
if rec_traj is not None and len(rec_traj) > 0:
fig = plot_mini_trajectory(
rec_traj, row["title"]
)
if fig:
st.plotly_chart(fig, width="stretch")
# Emotion profile summary
col1, col2 = st.columns(2)
with col1:
st.write("**Emotional Tone:**")
valence = row.get("avg_valence", 0)
arousal = row.get("avg_arousal", 0)
tone = (
"Positive"
if valence > 0.05
else (
"Negative"
if valence < -0.05
else "Neutral"
)
)
energy = (
"High-energy"
if arousal > 0.05
else (
"Calm"
if arousal < -0.05
else "Moderate"
)
)
st.write(f"• Tone: {tone}")
st.write(f"• Energy: {energy}")
with col2:
st.write("**Dominant Emotions:**")
emotions = {
"Joy": row.get("avg_joy", 0),
"Trust": row.get("avg_trust", 0),
"Fear": row.get("avg_fear", 0),
"Sadness": row.get("avg_sadness", 0),
}
sorted_emo = sorted(
emotions.items(),
key=lambda x: x[1],
reverse=True,
)
for emo, val in sorted_emo[:3]:
if val > 0:
st.write(f"• {emo}")
# Download button
csv = recs_pd.to_csv(index=False)
st.download_button(
label="Download Recommendations as CSV",
data=csv,
file_name=f"recommendations_{liked_id}.csv",
mime="text/csv",
)
else:
st.info(
"💡 Recommendations require trajectories. Run `python main.py` first."
)
else:
st.error(
"Failed to analyze book. Please check if the book exists and try again."
)
else:
st.warning("Please provide a book ID or upload a text file")
def show_explore_books():
"""Show explore books page."""
st.header("Explore Books")
st.markdown("Discover books by emotion characteristics")
# Output directory (default, not shown to user)
output_dir = "output"
trajectories_path = f"{output_dir}/trajectories"
if not os.path.exists(trajectories_path):
st.warning(
f"⚠️ Trajectories not found in {trajectories_path}. "
"Please run `python main.py` first to generate trajectories."
)
return
emotion_type = st.selectbox(
"Explore by emotion",
[
"Joy",
"Sadness",
"Fear",
"Anger",
"Anticipation",
"Disgust",
"Surprise",
"Trust",
],
)
top_n = st.slider("Number of books to show", 10, 50, 20)
if st.button("Show Top Books", type="primary"):
with st.spinner("Loading trajectories..."):
spark = st.session_state.spark
trajectories = load_trajectories(spark, output_dir)
if trajectories is None:
st.error("Could not load trajectories")
return
emotion_col = f"avg_{emotion_type.lower()}"
if emotion_col in trajectories.columns:
# Select columns, avoiding duplicates
select_cols = ["book_id", "title", "author", emotion_col]
additional_cols = [
"avg_joy",
"avg_sadness",
"avg_fear",
"avg_anger",
"avg_valence",
"avg_arousal",
]
# Only add additional cols if they're not already selected
for col_name in additional_cols:
if col_name not in select_cols:
select_cols.append(col_name)
top_books = (
trajectories.orderBy(col(emotion_col).desc())
.select(*select_cols)
.limit(top_n)
)
top_books_pd = top_books.toPandas()
st.success(f"Top {top_n} books by {emotion_type}")
for idx, row in top_books_pd.iterrows():
# Get emotion value safely
emotion_val = row[emotion_col]
# Handle case where it might be a Series (if duplicate columns exist)
if hasattr(emotion_val, "iloc"):
emotion_val = (
emotion_val.iloc[0] if len(emotion_val) > 0 else 0.0
)
emotion_val = float(emotion_val) if emotion_val is not None else 0.0
st.write(f"**{idx + 1}. {row['title']}** by {row['author']}")
st.write(f" {emotion_type}: {emotion_val:.4f}")
st.write("---")
def show_find_books_by_emotions():
"""Show page for finding books by emotion preferences."""
st.header("Find Books by Emotion Preferences")
st.markdown("Pick a vibe in one click, optionally fine-tune, then get matches.")
# Output directory
output_dir = "output"
trajectories_path = f"{output_dir}/trajectories"
if not os.path.exists(trajectories_path):
st.warning(
f"⚠️ Trajectories not found in {trajectories_path}. "
"Please run `python main.py` first to generate trajectories."
)
return
# Simple presets to reduce friction; sliders are now optional fine-tuning
st.subheader("Choose a vibe")
presets = {
"Balanced": {
"joy": 0.5,
"anticipation": 0.5,
"surprise": 0.3,
"trust": 0.5,
"sadness": 0.0,
"fear": 0.0,
"anger": 0.0,
"disgust": 0.0,
},
"Cozy & Uplifting": {
"joy": 0.7,
"anticipation": 0.6,
"surprise": 0.2,
"trust": 0.6,
"sadness": 0.0,
"fear": 0.0,
"anger": 0.0,
"disgust": 0.0,
},
"Adventurous": {
"joy": 0.5,
"anticipation": 0.7,
"surprise": 0.5,
"trust": 0.4,
"sadness": 0.1,
"fear": 0.2,
"anger": 0.0,
"disgust": 0.0,
},
"Dark & Tense": {
"joy": 0.1,
"anticipation": 0.4,
"surprise": 0.3,