Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
881 lines (803 loc) · 36 KB
/
Copy pathapp.py
File metadata and controls
881 lines (803 loc) · 36 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
import streamlit as st
import google.generativeai as genai
from dotenv import load_dotenv
import os
import yaml
from yaml.loader import SafeLoader
import streamlit_authenticator as stauth
import time
from utils.generators import generate_blog_from_input
from utils.notifications import send_feedback_sms
from utils.ui import render_step_container, render_blog_output
# RAG & Agent — graceful degradation if chromadb not installed
try:
import utils.rag as rag
from utils.agent import run_agent
RAG_ENABLED = rag.is_available()
except ImportError:
rag = None
run_agent = None
RAG_ENABLED = False
# ── Page config (must be first Streamlit call) ─────────────────────────────────
st.set_page_config(page_title="Blog Generator", page_icon="📝", layout="wide")
# ── Environment & model ────────────────────────────────────────────────────────
load_dotenv()
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
genai.configure(api_key=GEMINI_API_KEY)
try:
model = genai.GenerativeModel("gemini-1.5-flash")
except Exception as e:
st.error(f"Error initializing Gemini model: {str(e)}")
model = None
# ── Authentication ─────────────────────────────────────────────────────────────
with open("config.yaml") as file:
config = yaml.load(file, Loader=SafeLoader)
authenticator = stauth.Authenticate(
config["credentials"],
config["cookie"]["name"],
config["cookie"]["key"],
config["cookie"]["expiry_days"],
auto_hash=True,
)
# ── Custom CSS ─────────────────────────────────────────────────────────────────
custom_css = """
<style>
body {
font-family: 'Poppins', sans-serif;
background: #F5F5F5;
color: #333333;
}
h1, h2, h3, h4, h5, h6 { color: #6C63FF; }
.header { text-align: center; margin-bottom: 40px; }
.section {
background: #FFFFFF;
padding: 40px;
border-radius: 16px;
margin-bottom: 40px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.container {
background: linear-gradient(135deg, #6C63FF, #FF6584);
color: white;
padding: 20px;
border-radius: 12px;
text-align: center;
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.container.agent-card {
background: linear-gradient(135deg, #1a1a2e, #16213e, #0f3460);
}
.container.kb-card {
background: linear-gradient(135deg, #00b09b, #96c93d);
}
.container:hover {
transform: translateY(-5px);
box-shadow: 0 8px 24px rgba(108, 99, 255, 0.5);
}
.container h2 { color: white; font-size: 1.5em; margin-bottom: 10px; }
.container p { color: rgba(255, 255, 255, 0.9); font-size: 1em; }
.footer {
text-align: center;
padding: 20px;
background: #FFFFFF;
border-top: 1px solid #E0E0E0;
margin-top: 40px;
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.footer a { color: #6C63FF; text-decoration: none; margin: 0 10px; }
.footer a:hover { color: #FF6584; }
.spinner { text-align: center; }
.spinner div {
width: 40px;
height: 40px;
border: 4px solid #6C63FF;
border-top: 4px solid transparent;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.share-btn {
background: linear-gradient(135deg, #6C63FF, #FF6584);
color: white;
border: none;
padding: 12px 24px;
border-radius: 8px;
cursor: pointer;
font-size: 1.1em;
font-weight: 600;
transition: transform 0.3s ease, box-shadow 0.3s ease;
}
.share-btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(108, 99, 255, 0.5);
}
.agent-step-done { border-left: 4px solid #00C4B4; padding-left: 12px; margin-bottom: 12px; }
.agent-step-error { border-left: 4px solid #FF6584; padding-left: 12px; margin-bottom: 12px; }
.agent-step-running{ border-left: 4px solid #6C63FF; padding-left: 12px; margin-bottom: 12px; }
.rag-badge {
display: inline-block;
background: linear-gradient(90deg, #00b09b, #96c93d);
color: white;
font-size: 0.78em;
font-weight: 600;
padding: 3px 10px;
border-radius: 20px;
margin-left: 8px;
vertical-align: middle;
}
.faq-item { margin-bottom: 20px; }
.faq-item h3 {
color: #6C63FF;
font-size: 1.2em;
margin-bottom: 10px;
display: flex;
align-items: center;
cursor: pointer;
}
.faq-item h3 i { margin-right: 10px; color: #FF6584; }
.faq-item .faq-answer {
color: #333333;
margin-top: 10px;
font-size: 1em;
font-weight: 300;
margin-left: 20px;
}
.landing {
position: relative;
background: linear-gradient(135deg, #6C63FF, #FF6584);
padding: 60px 20px;
border-radius: 16px;
text-align: center;
color: white;
margin: 40px 0;
overflow: hidden;
}
.landing h1 { font-size: 3.5em; font-weight: 700; color: white; margin-bottom: 10px; }
.landing p { font-size: 1.2em; font-weight: 300; color: white; margin-bottom: 20px; }
.landing-btn {
background: white;
color: #333333;
border: none;
padding: 12px 24px;
border-radius: 8px;
cursor: pointer;
font-size: 1.1em;
font-weight: 600;
transition: background 0.3s ease, color 0.3s ease;
}
.landing-btn:hover { background: #F5F5F5; color: #6C63FF; }
.logo { position: absolute; top: 20px; left: 20px; font-size: 1.5em; font-weight: 700; color: #333333; }
.auth-container {
background: #FFFFFF;
padding: 40px;
border-radius: 16px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
max-width: 500px;
margin: 40px auto;
}
.auth-container h1 { color: #6C63FF; text-align: center; margin-bottom: 20px; }
.auth-container p { color: #333333; text-align: center; margin-bottom: 20px; }
.auth-link { color: #6C63FF; text-decoration: none; font-weight: 600; }
.auth-link:hover { color: #FF6584; text-decoration: underline; }
.step-container {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
width: 100%;
}
.step { text-align: center; flex: 1; }
.step:not(:last-child) { border-right: 2px solid #000000; padding-right: 20px; margin-right: 20px; }
.step span {
display: block;
width: 30px;
height: 30px;
color: white;
border-radius: 50%;
line-height: 30px;
margin: 0 auto 5px;
}
.step p { color: #333333; font-size: 0.9em; margin: 0; }
</style>
"""
st.markdown(
"""
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
""",
unsafe_allow_html=True,
)
st.markdown(custom_css, unsafe_allow_html=True)
st.markdown(
"""<script>
function scrollToContainers() {
const el = document.getElementById('containers-section');
if (el) el.scrollIntoView({ behavior: 'smooth' });
}
</script>""",
unsafe_allow_html=True,
)
# ── Session state defaults ─────────────────────────────────────────────────────
_defaults = {
"authentication_status": None,
"username": None,
"name": None,
"blog_title": "",
"blog_content": "",
"current_page": "login",
"user_type": "Common Students",
}
for k, v in _defaults.items():
if k not in st.session_state:
st.session_state[k] = v
# ── Routing ────────────────────────────────────────────────────────────────────
query_params = st.query_params
page_from_url = query_params.get("page", "login")
if st.session_state.authentication_status is True and page_from_url == "login":
st.session_state.current_page = "home"
st.query_params["page"] = "home"
else:
st.session_state.current_page = page_from_url
page = st.session_state.current_page
# ── Helpers ────────────────────────────────────────────────────────────────────
AUDIENCE_OPTIONS = ["Researchers", "Common Students", "Data Scientists"]
def audience_selector(key: str) -> str:
st.markdown("### Options")
user_type = st.selectbox(
"Target Audience",
AUDIENCE_OPTIONS,
index=AUDIENCE_OPTIONS.index(st.session_state.user_type),
key=key,
)
st.session_state.user_type = user_type
return user_type
def go_to(page_name: str) -> None:
st.session_state.current_page = page_name
st.query_params["page"] = page_name
st.rerun()
def logout() -> None:
authenticator.logout(location="unrendered")
st.session_state.authentication_status = None
st.session_state.username = None
st.session_state.name = None
go_to("login")
def _do_rag_retrieval(query: str) -> list[str]:
"""Retrieve RAG context and show an expander widget. Returns list of snippet strings."""
if not RAG_ENABLED:
return []
try:
similar = rag.retrieve_similar(str(query), n=3)
if not similar:
return []
with st.expander(
f"📚 Knowledge Base — {len(similar)} similar blog(s) found (click to preview)",
expanded=False,
):
for s in similar:
st.markdown(
f"**{s['title']}** <span class='rag-badge'>similarity {s['similarity']}</span>",
unsafe_allow_html=True,
)
st.caption(s["snippet"][:200] + "…")
st.divider()
return [f"Title: {s['title']}\n{s['snippet']}" for s in similar]
except Exception:
return []
def _save_to_rag(title: str, body: str, user_type: str, input_type: str) -> None:
"""Store a generated blog in the knowledge base, silently skipping on error."""
if not RAG_ENABLED or not body or body.startswith("Error"):
return
try:
rag.add_blog(title, body, user_type, input_type)
st.toast("📚 Blog saved to your Knowledge Base!", icon="✅")
except Exception:
pass # Don't surface RAG storage errors to the user
# ── Registration page ──────────────────────────────────────────────────────────
if page == "register":
st.markdown(
"""<div class="auth-container">
<h1>Register</h1>
<p>Create a new account to access the Blog Generator</p>
</div>""",
unsafe_allow_html=True,
)
try:
email_of_registered_user, username_of_registered_user, name_of_registered_user = (
authenticator.register_user(
location="main",
fields={
"Form name": "Register",
"Email": "Email",
"Username": "Username",
"Password": "Password",
"Repeat password": "Repeat Password",
"Register": "Register",
},
)
)
if email_of_registered_user:
st.success("User registered successfully! Please log in.")
with open("config.yaml", "w") as file:
yaml.dump(config, file, default_flow_style=False, allow_unicode=True)
time.sleep(1)
go_to("login")
except Exception as e:
st.error(f"Registration failed: {str(e)}")
st.markdown(
'<div class="auth-container"><p>Already have an account? <a href="?page=login" class="auth-link">Log In</a></p></div>',
unsafe_allow_html=True,
)
# ── Login page ─────────────────────────────────────────────────────────────────
elif page == "login" and st.session_state.authentication_status is not True:
st.markdown(
"""<div class="auth-container">
<h1>Login</h1>
<p>Access your Blog Generator account</p>
</div>""",
unsafe_allow_html=True,
)
try:
authenticator.login(
location="main",
fields={
"Form name": "Login",
"Username": "Username",
"Password": "Password",
"Login": "Login",
},
)
except Exception as e:
st.error(e)
status = st.session_state.get("authentication_status")
if status is True:
st.success(f"Welcome {st.session_state.get('name')}")
time.sleep(1)
go_to("home")
elif status is False:
st.error("Username/password is incorrect")
else:
st.warning("Please enter your username and password")
st.markdown(
'<div class="auth-container"><p>Don\'t have an account? <a href="?page=register" class="auth-link">Register</a></p></div>',
unsafe_allow_html=True,
)
# ── Sidebar (authenticated only) ───────────────────────────────────────────────
if st.session_state.authentication_status:
st.sidebar.title(f"Welcome, {st.session_state.name}!")
st.sidebar.markdown("---")
st.sidebar.markdown("**Navigation**")
if st.sidebar.button("🏠 Home", key="nav_home"):
go_to("home")
if st.sidebar.button("🤖 Agent Mode", key="nav_agent"):
go_to("agent")
if RAG_ENABLED:
kb_count = rag.kb_count()
if st.sidebar.button(f"📚 Knowledge Base ({kb_count})", key="nav_kb"):
go_to("knowledge")
else:
st.sidebar.caption("📚 Knowledge Base — install chromadb to enable")
st.sidebar.markdown("---")
if st.sidebar.button("Logout", key="logout_btn"):
logout()
# ── Auth guard ─────────────────────────────────────────────────────────────────
if not st.session_state.authentication_status and page not in ("login", "register"):
st.warning("Please log in to access this page.")
go_to("login")
# ══════════════════════════════════════════════════════════════════════════════
# HOME PAGE
# ══════════════════════════════════════════════════════════════════════════════
if st.session_state.authentication_status and page == "home":
st.markdown(
"""<div class="landing">
<div class="logo">TIMEX</div>
<h1>Blog Generator</h1>
<p>AI-powered content creation with RAG & Agentic intelligence</p>
<button class="landing-btn" aria-label="Get Started" onclick="scrollToContainers()">Get Started</button>
</div>""",
unsafe_allow_html=True,
)
st.markdown(
"""<div class="section">
<h2>About</h2>
<p>Our Blog Generator combines three powerful AI paradigms:
<strong>Generative AI</strong> (Gemini 1.5 Flash) for high-quality text,
<strong>RAG</strong> (Retrieval-Augmented Generation) to ground new blogs in
your personal knowledge base of past posts, and
<strong>Agentic AI</strong> — an autonomous multi-step agent that plans,
researches, writes, critiques, and refines your blog without you lifting a finger.
</p>
</div>""",
unsafe_allow_html=True,
)
st.markdown(
'<div class="section" id="containers-section"><h2>Choose Your Generation Mode</h2></div>',
unsafe_allow_html=True,
)
col1, col2, col3, col4 = st.columns(4)
with col1:
st.markdown(
"""<div class="container">
<h2><i class="fas fa-file-alt" style="margin-right:8px;"></i>Text</h2>
<p>Generate from a text prompt or idea.</p>
</div>""",
unsafe_allow_html=True,
)
if st.button("Start with Text", key="text_btn"):
go_to("text")
with col2:
st.markdown(
"""<div class="container">
<h2><i class="fas fa-link" style="margin-right:8px;"></i>URL</h2>
<p>Turn any webpage or YouTube video into a blog.</p>
</div>""",
unsafe_allow_html=True,
)
if st.button("Start with URL", key="url_btn"):
go_to("url")
with col3:
st.markdown(
"""<div class="container">
<h2><i class="fas fa-image" style="margin-right:8px;"></i>Image</h2>
<p>Create a blog post inspired by an image.</p>
</div>""",
unsafe_allow_html=True,
)
if st.button("Start with Image", key="image_btn"):
go_to("image")
with col4:
st.markdown(
"""<div class="container agent-card">
<h2><i class="fas fa-robot" style="margin-right:8px;"></i>Agent Mode</h2>
<p>AI autonomously plans, researches, writes & refines your blog.</p>
</div>""",
unsafe_allow_html=True,
)
if st.button("Launch Agent", key="agent_btn"):
go_to("agent")
# FAQ
st.markdown(
"""<div class="section">
<h2>Frequently Asked Questions</h2>
<div class="faq-item">
<h3><i class="fas fa-lightbulb"></i> What is RAG and how does it help?</h3>
<p class="faq-answer">RAG (Retrieval-Augmented Generation) stores all your
generated blogs in a local vector database. When you generate a new blog, the
system retrieves your most semantically similar past posts and feeds them as
context to the AI — so the output is grounded in your own style and knowledge.</p>
</div>
<div class="faq-item">
<h3><i class="fas fa-robot"></i> What does Agent Mode do differently?</h3>
<p class="faq-answer">Instead of a single-shot generation, the Agent autonomously
runs a 5-step reasoning loop: it plans an outline, fetches research (optional),
writes each section individually, self-critiques the draft, then refines it.
You can watch every step happen in real time.</p>
</div>
<div class="faq-item">
<h3><i class="fas fa-database"></i> Where is my knowledge base stored?</h3>
<p class="faq-answer">Locally in a <code>rag_store/</code> folder inside the
project directory using ChromaDB. Nothing is sent to external servers beyond
the Gemini embedding API.</p>
</div>
<div class="faq-item">
<h3><i class="fas fa-heading"></i> Does the AI generate titles automatically?</h3>
<p class="faq-answer">Yes — Gemini generates a compelling title as the first
line of every response. You can see it in the Preview tab after generation.</p>
</div>
</div>""",
unsafe_allow_html=True,
)
# ══════════════════════════════════════════════════════════════════════════════
# TEXT GENERATOR PAGE
# ══════════════════════════════════════════════════════════════════════════════
elif st.session_state.authentication_status and page == "text":
st.markdown(
"""<div class="header">
<h1><i class="fas fa-file-alt" style="margin-right:10px;"></i>Text Blog Generator</h1>
<p>Turn your ideas into a blog post</p>
</div>""",
unsafe_allow_html=True,
)
render_step_container(["Enter Text", "Generate Blog", "Share / Download"])
user_type = audience_selector("text_audience")
input_data = st.text_area("Blog Content", placeholder="Enter the text to inspire your blog post…", height=200)
word_count = st.slider("Approximate Word Count", min_value=100, max_value=1000, value=300, step=50)
if st.button("Generate Blog", key="generate_text"):
if not input_data:
st.error("Please provide text input!")
else:
rag_context = _do_rag_retrieval(input_data)
with st.spinner("Generating your blog post…"):
title, body = generate_blog_from_input(
model, "Text", input_data, user_type, word_count, rag_context=rag_context
)
st.session_state.blog_title = title
st.session_state.blog_content = body
st.subheader("Generated Blog Post")
render_blog_output(title, body, "Text", input_data)
_save_to_rag(title, body, user_type, "Text")
if st.button("Back to Home", key="back_text"):
go_to("home")
# ══════════════════════════════════════════════════════════════════════════════
# URL GENERATOR PAGE
# ══════════════════════════════════════════════════════════════════════════════
elif st.session_state.authentication_status and page == "url":
st.markdown(
"""<div class="header">
<h1><i class="fas fa-link" style="margin-right:10px;"></i>URL Blog Generator</h1>
<p>Generate a blog post from a URL</p>
</div>""",
unsafe_allow_html=True,
)
render_step_container(["Enter URL", "Generate Blog", "Share / Download"])
user_type = audience_selector("url_audience")
input_data = st.text_input("URL", placeholder="Enter a URL (webpage, YouTube video, or image)…")
word_count = st.slider("Approximate Word Count", min_value=100, max_value=1000, value=300, step=50)
if st.button("Generate Blog", key="generate_url"):
if not input_data:
st.error("Please provide a URL!")
else:
rag_context = _do_rag_retrieval(input_data)
with st.spinner("Generating your blog post…"):
title, body = generate_blog_from_input(
model, "URL", input_data, user_type, word_count, rag_context=rag_context
)
st.session_state.blog_title = title
st.session_state.blog_content = body
st.subheader("Generated Blog Post")
render_blog_output(title, body, "URL", input_data)
_save_to_rag(title, body, user_type, "URL")
if st.button("Back to Home", key="back_url"):
go_to("home")
# ══════════════════════════════════════════════════════════════════════════════
# IMAGE GENERATOR PAGE
# ══════════════════════════════════════════════════════════════════════════════
elif st.session_state.authentication_status and page == "image":
st.markdown(
"""<div class="header">
<h1><i class="fas fa-image" style="margin-right:10px;"></i>Image Blog Generator</h1>
<p>Turn an image into a blog post</p>
</div>""",
unsafe_allow_html=True,
)
render_step_container(["Upload Image", "Generate Blog", "Share / Download"])
user_type = audience_selector("image_audience")
input_data = st.file_uploader("Upload Image", type=["jpg", "jpeg", "png", "gif"])
word_count = st.slider("Approximate Word Count", min_value=100, max_value=1000, value=300, step=50)
if st.button("Generate Blog", key="generate_image"):
if not input_data:
st.error("Please upload an image!")
else:
rag_context = _do_rag_retrieval(input_data.name)
with st.spinner("Generating your blog post…"):
title, body = generate_blog_from_input(
model, "Image File", input_data, user_type, word_count, rag_context=rag_context
)
st.session_state.blog_title = title
st.session_state.blog_content = body
st.subheader("Generated Blog Post")
render_blog_output(title, body, "Image File", input_data)
_save_to_rag(title, body, user_type, "Image")
if st.button("Back to Home", key="back_image"):
go_to("home")
# ══════════════════════════════════════════════════════════════════════════════
# AGENT MODE PAGE
# ══════════════════════════════════════════════════════════════════════════════
elif st.session_state.authentication_status and page == "agent":
st.markdown(
"""<div class="header">
<h1><i class="fas fa-robot" style="margin-right:10px;"></i>Agent Mode</h1>
<p>Watch the AI autonomously plan, research, write, critique & refine your blog</p>
</div>""",
unsafe_allow_html=True,
)
if not RAG_ENABLED:
st.warning(
"⚠️ ChromaDB is not installed — RAG context will not be used in Agent Mode. "
"Run `pip install chromadb` to enable the full experience."
)
# How it works callout
with st.expander("ℹ️ How Agent Mode works", expanded=False):
st.markdown(
"""
| Step | What the Agent does |
|---|---|
| 🧠 **Planning** | Reasons about the topic and generates a structured multi-section outline (JSON) |
| 🔍 **Researching** | (Optional) Fetches a URL you provide for factual grounding |
| ✍️ **Writing** | Writes each section of the outline independently with the right tone |
| 🔎 **Critiquing** | Self-evaluates the draft and scores it on clarity, depth, and engagement |
| ✨ **Refining** | Applies its own critique to produce a polished final blog post |
Each step is displayed live as the agent works. RAG context from your Knowledge Base is
automatically injected into planning and refinement if available.
"""
)
st.markdown("### Configure Your Blog")
topic = st.text_input(
"Blog Topic",
placeholder="e.g. 'The future of quantum computing in healthcare'",
key="agent_topic",
)
research_url = st.text_input(
"Research URL (optional)",
placeholder="Paste a URL for the agent to read as research material…",
key="agent_url",
)
user_type = audience_selector("agent_audience")
word_count = st.slider(
"Target Word Count", min_value=200, max_value=1500, value=600, step=100, key="agent_wc"
)
if st.button("🚀 Run Agent", key="run_agent_btn", type="primary"):
if not topic.strip():
st.error("Please enter a blog topic!")
elif not model:
st.error("Gemini model is not initialized. Check your API key.")
else:
st.markdown("---")
st.markdown("### 🤖 Agent is working…")
# Fetch RAG context before starting
rag_context = []
if RAG_ENABLED:
with st.spinner("📚 Checking knowledge base…"):
rag_context = _do_rag_retrieval(topic)
final_title = ""
final_body = ""
step_containers = {}
with st.status("Running agent pipeline…", expanded=True) as agent_status:
for step_data in run_agent(
model=model,
topic=topic,
user_type=user_type,
word_count=word_count,
research_url=research_url,
rag_context=rag_context,
):
step_name = step_data["step"]
detail = step_data["detail"]
result = step_data.get("result", "")
status_flag = step_data.get("status", "done")
is_final = step_data.get("final", False)
if is_final:
final_title = step_data.get("title", "")
final_body = step_data.get("body", "")
st.write(f"✅ **{step_name}** — {detail}")
continue
icon = "✅" if status_flag == "done" else ("❌" if status_flag == "error" else "⏳")
st.write(f"{icon} **{step_name}** — {detail}")
if result:
with st.expander(f"View details: {step_name}", expanded=False):
if result.strip().startswith("{"):
st.json(result)
else:
st.markdown(result)
if final_body:
agent_status.update(label="✅ Agent complete!", state="complete")
else:
agent_status.update(label="⚠️ Agent encountered an error", state="error")
# Show final output
if final_body:
st.markdown("---")
st.success("🎉 Your blog post is ready!")
st.session_state.blog_title = final_title
st.session_state.blog_content = final_body
render_blog_output(final_title, final_body, "Text", topic)
_save_to_rag(final_title, final_body, user_type, "Agent")
if st.button("Back to Home", key="back_agent"):
go_to("home")
# ══════════════════════════════════════════════════════════════════════════════
# KNOWLEDGE BASE PAGE
# ══════════════════════════════════════════════════════════════════════════════
elif st.session_state.authentication_status and page == "knowledge":
st.markdown(
"""<div class="header">
<h1><i class="fas fa-database" style="margin-right:10px;"></i>Knowledge Base</h1>
<p>All your generated blogs, semantically indexed and searchable</p>
</div>""",
unsafe_allow_html=True,
)
if not RAG_ENABLED:
st.error(
"ChromaDB is not installed. Run `pip install chromadb` and restart the app "
"to use the Knowledge Base."
)
if st.button("Back to Home", key="back_kb_na"):
go_to("home")
else:
count = rag.kb_count()
col_a, col_b, col_c = st.columns(3)
col_a.metric("📄 Blogs Stored", count)
col_b.metric("🔍 Semantic Search", "Active" if count > 0 else "Empty")
col_c.metric("💾 Storage", "Local ChromaDB")
st.markdown("---")
# Semantic search
st.markdown("### 🔍 Semantic Search")
search_query = st.text_input(
"Search your knowledge base",
placeholder="e.g. 'machine learning for beginners'",
key="kb_search",
)
if st.button("Search", key="kb_search_btn") and search_query:
with st.spinner("Searching…"):
results = rag.search_blogs(search_query, n=5)
if results:
st.success(f"Found {len(results)} relevant blog(s):")
for r in results:
with st.expander(
f"**{r['title']}** — similarity: {r['similarity']} | {r['timestamp'][:10]}",
expanded=False,
):
st.caption(f"Audience: {r['user_type']} | Source: {r['input_type']}")
st.markdown(r["snippet"])
else:
st.info("No matching blogs found. Generate some blogs first!")
st.markdown("---")
# Browse all blogs
st.markdown("### 📋 All Stored Blogs")
if count == 0:
st.info(
"Your knowledge base is empty. Generate blog posts using any mode "
"and they will automatically appear here."
)
else:
try:
all_blogs = rag.get_all_blogs()
for blog in all_blogs:
col_title, col_meta, col_del = st.columns([5, 3, 1])
with col_title:
with st.expander(f"📄 {blog['title']}", expanded=False):
st.caption(
f"Generated: {blog['timestamp'][:19].replace('T', ' ')} | "
f"Audience: {blog['user_type']} | Source: {blog['input_type']}"
)
st.markdown(blog["body"][:1000] + ("…" if len(blog["body"]) > 1000 else ""))
with col_meta:
st.caption(
f"{blog['timestamp'][:10]} · {blog['user_type']} · {blog['input_type']}"
)
with col_del:
if st.button("🗑️", key=f"del_{blog['id']}", help="Delete this entry"):
rag.delete_blog(blog["id"])
st.rerun()
except Exception as e:
st.error(f"Error loading knowledge base: {e}")
if st.button("Back to Home", key="back_kb"):
go_to("home")
# ══════════════════════════════════════════════════════════════════════════════
# FOOTER (authenticated, all pages)
# ══════════════════════════════════════════════════════════════════════════════
if st.session_state.authentication_status:
st.markdown(
"""<div class="footer">
<div style="margin-bottom: 20px;">
<h3 style="color: #6C63FF;">Feedback</h3>""",
unsafe_allow_html=True,
)
feedback_text = st.text_area(
"Feedback",
placeholder="Let us know how we can improve…",
height=100,
key="feedback_input",
help="Your feedback helps us improve!",
)
if st.button("Submit Feedback", key="submit_feedback"):
if feedback_text:
result = send_feedback_sms(feedback_text)
if result is True or (isinstance(result, tuple) and result[0]):
st.success("Feedback sent! Thank you.")
else:
err = result[1] if isinstance(result, tuple) else "Unknown error"
st.error(f"Failed to send feedback: {err}")
else:
st.warning("Please enter feedback before submitting.")
st.markdown(
""" </div>
<p style="text-align:center;">© 2025 Blog Generator | Powered by Streamlit, Google Gemini & ChromaDB</p>
<p style="text-align:center;"><a href="#">Privacy Policy</a> | <a href="#">Terms of Service</a> | <a href="#">Contact Us</a></p>
</div>""",
unsafe_allow_html=True,
)