cryogenic22 commited on
Commit
dad14a7
·
verified ·
1 Parent(s): 185113b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +159 -0
app.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import streamlit as st
3
+ import os
4
+ from datetime import datetime
5
+ import json
6
+ from crewai import Agent, Task, Crew
7
+ from langchain.tools import DuckDuckGoSearchRun
8
+ from langchain.llms import OpenAI
9
+
10
+ # Set up OpenAI API key from Streamlit secrets
11
+ def setup_api_keys():
12
+ """Setup API keys from Hugging Face Spaces secrets"""
13
+ try:
14
+ if 'OPENAI_API_KEY' in st.secrets:
15
+ os.environ['OPENAI_API_KEY'] = st.secrets['OPENAI_API_KEY']
16
+ return True
17
+ else:
18
+ st.error("OpenAI API key not found in secrets!")
19
+ return False
20
+ except Exception as e:
21
+ st.error(f"Error setting up API keys: {str(e)}")
22
+ return False
23
+
24
+ # Initialize agents with API key check
25
+ def initialize_agents():
26
+ """Initialize CrewAI agents with proper API key handling"""
27
+ if not os.environ.get('OPENAI_API_KEY'):
28
+ return None
29
+
30
+ search_tool = DuckDuckGoSearchRun()
31
+ llm = OpenAI(temperature=0.7)
32
+
33
+ quote_curator = Agent(
34
+ role='Quote Curator',
35
+ goal='Select meaningful spiritual quotes and validate their authenticity',
36
+ backstory="""You are an expert in world philosophies and spiritual traditions.""",
37
+ tools=[search_tool],
38
+ llm=llm,
39
+ verbose=True
40
+ )
41
+
42
+ content_creator = Agent(
43
+ role='Content Creator',
44
+ goal='Create engaging visual descriptions for spiritual quotes',
45
+ backstory="""You are a creative content specialist.""",
46
+ tools=[search_tool],
47
+ llm=llm,
48
+ verbose=True
49
+ )
50
+
51
+ content_validator = Agent(
52
+ role='Content Validator',
53
+ goal='Ensure content aligns with spiritual traditions',
54
+ backstory="""You are an expert in multiple spiritual traditions.""",
55
+ tools=[search_tool],
56
+ llm=llm,
57
+ verbose=True
58
+ )
59
+
60
+ return quote_curator, content_creator, content_validator
61
+
62
+ def main():
63
+ st.set_page_config(
64
+ page_title="Spiritual Content Generator",
65
+ page_icon="🕉️",
66
+ layout="wide"
67
+ )
68
+
69
+ # Setup API keys at startup
70
+ if not setup_api_keys():
71
+ st.warning("""
72
+ Please set up the OpenAI API key in your Hugging Face Space:
73
+ 1. Go to your Space Settings
74
+ 2. Click on 'Secrets'
75
+ 3. Add OPENAI_API_KEY
76
+ """)
77
+ st.stop()
78
+
79
+ # Initialize session state
80
+ if 'generated_content' not in st.session_state:
81
+ st.session_state.generated_content = None
82
+ if 'generation_history' not in st.session_state:
83
+ st.session_state.generation_history = []
84
+
85
+ # Header
86
+ st.title("🕉️ Spiritual Content Generator")
87
+ st.markdown("""
88
+ Generate inspiring spiritual content combining quotes and insights from various philosophical traditions.
89
+ """)
90
+
91
+ # Sidebar
92
+ with st.sidebar:
93
+ st.header("Controls")
94
+ generate_button = st.button("Generate New Content")
95
+
96
+ if generate_button:
97
+ with st.spinner("Initializing agents..."):
98
+ agents = initialize_agents()
99
+
100
+ if agents:
101
+ quote_curator, content_creator, content_validator = agents
102
+
103
+ try:
104
+ with st.spinner("Generating content..."):
105
+ # Create and run crew
106
+ crew = Crew(
107
+ agents=[quote_curator, content_creator, content_validator],
108
+ tasks=[
109
+ Task(
110
+ description="Select and validate a spiritual quote.",
111
+ agent=quote_curator
112
+ ),
113
+ Task(
114
+ description="Create a visual description for the quote.",
115
+ agent=content_creator
116
+ ),
117
+ Task(
118
+ description="Validate the content's appropriateness.",
119
+ agent=content_validator
120
+ )
121
+ ]
122
+ )
123
+
124
+ result = crew.kickoff()
125
+
126
+ # Store the result
127
+ st.session_state.generated_content = result
128
+ st.session_state.generation_history.append({
129
+ 'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
130
+ 'content': result
131
+ })
132
+
133
+ except Exception as e:
134
+ st.error(f"Error during content generation: {str(e)}")
135
+
136
+ # Main content area
137
+ col1, col2 = st.columns([2, 1])
138
+
139
+ with col1:
140
+ st.header("Latest Generated Content")
141
+ if st.session_state.generated_content:
142
+ st.json(st.session_state.generated_content)
143
+
144
+ with col2:
145
+ st.header("Generation History")
146
+ for entry in reversed(st.session_state.generation_history):
147
+ with st.expander(f"Generated at {entry['timestamp']}"):
148
+ st.json(entry['content'])
149
+
150
+ # Footer
151
+ st.markdown("---")
152
+ st.markdown("""
153
+ <div style='text-align: center'>
154
+ <p>Created with ❤️ using CrewAI and Streamlit</p>
155
+ </div>
156
+ """, unsafe_allow_html=True)
157
+
158
+ if __name__ == "__main__":
159
+ main()