caveprod commited on
Commit
f4ae53e
·
verified ·
1 Parent(s): 75bcd5c

Upload 12 files

Browse files
Files changed (12) hide show
  1. .env +8 -0
  2. .gitattributes +2 -35
  3. .gitignore +42 -0
  4. README.md +155 -13
  5. Sample.txt +0 -0
  6. app.py +288 -0
  7. app.py Archive +311 -0
  8. article_agent.py +148 -0
  9. env.example +9 -0
  10. procfile +1 -0
  11. procfile.txt +1 -0
  12. requirements.txt +5 -0
.env ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # OpenAI API Key
2
+ # Get your API key from: https://platform.openai.com/api-keys
3
+ OPENAI_API_KEY=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
4
+
5
+ # Freepik API Key (Optional but recommended for cost savings)
6
+ # Get your API key from: https://www.freepik.com/api
7
+ # If not provided, the app will use DALL-E for all images
8
+ FREEPIK_API_KEY=FPSX93b11d12b924bbc0cfd22b0b92773aab
.gitattributes CHANGED
@@ -1,35 +1,2 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Environment variables
2
+ .env
3
+
4
+ # Python
5
+ __pycache__/
6
+ *.py[cod]
7
+ *$py.class
8
+ *.so
9
+ .Python
10
+ env/
11
+ venv/
12
+ ENV/
13
+ build/
14
+ develop-eggs/
15
+ dist/
16
+ downloads/
17
+ eggs/
18
+ .eggs/
19
+ lib/
20
+ lib64/
21
+ parts/
22
+ sdist/
23
+ var/
24
+ wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+
29
+ # IDE
30
+ .vscode/
31
+ .idea/
32
+ *.swp
33
+ *.swo
34
+ *~
35
+
36
+ # OS
37
+ .DS_Store
38
+ Thumbs.db
39
+
40
+ # Streamlit
41
+ # .streamlit/
42
+
README.md CHANGED
@@ -1,13 +1,155 @@
1
- ---
2
- title: Article Agent
3
- emoji: 🔥
4
- colorFrom: blue
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 6.0.2
8
- app_file: app.py
9
- pinned: false
10
- short_description: Full article creation agent
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🧠 Caveman Article Agent
2
+
3
+ A powerful web application that generates professional articles with structured outlines, complete content, header images, and related resources using AI.
4
+
5
+ ## ✨ Features
6
+
7
+ - **Article Outline Generation**: Create detailed, structured outlines using GPT-4 Turbo
8
+ - **Full Article Writing**: Generate complete, well-researched articles based on your title and word range
9
+ - **Smart Image Sourcing**: Automatically tries Freepik API first (cost-efficient), falls back to DALL-E if needed
10
+ - **Resource Suggestions**: Get 5 authoritative resources related to your article topic
11
+ - **Export Options**: Download articles as Markdown files
12
+
13
+ ## 🚀 Quick Start
14
+
15
+ ### Prerequisites
16
+
17
+ - Python 3.11 or higher
18
+ - OpenAI API key ([Get one here](https://platform.openai.com/api-keys))
19
+ - Freepik API key (optional, but recommended for cost savings - [Get one here](https://www.freepik.com/api))
20
+
21
+ ### Installation
22
+
23
+ 1. **Clone or download this repository**
24
+
25
+ 2. **Install dependencies**:
26
+ ```bash
27
+ pip install -r requirements.txt
28
+ ```
29
+
30
+ 3. **Set up environment variables**:
31
+ - Copy `env.example` to `.env`
32
+ - Fill in your API keys:
33
+ ```env
34
+ OPENAI_API_KEY=your_openai_api_key_here
35
+ FREEPIK_API_KEY=your_freepik_api_key_here
36
+ ```
37
+
38
+ 4. **Run the application**:
39
+ ```bash
40
+ streamlit run app.py
41
+ ```
42
+
43
+ 5. **Open your browser** to `http://localhost:8501`
44
+
45
+ ## 📖 Usage
46
+
47
+ 1. Enter an **Article Title** in the sidebar
48
+ 2. Specify a **Word Range** (e.g., "800-1000")
49
+ 3. Click **"Generate Article"**
50
+ 4. Wait for the AI to generate:
51
+ - Article outline
52
+ - Complete article
53
+ - Header image
54
+ - Related resources
55
+ 5. Download the article as Markdown if desired
56
+
57
+ ## 💰 Cost Optimization
58
+
59
+ - **Primary cost**: GPT-4 Turbo API calls (~$0.01-0.03 per article)
60
+ - **Image costs**:
61
+ - Freepik API: Free (if you have API access)
62
+ - DALL-E fallback: ~$0.04 per image
63
+ - **Estimated total**: <$0.10 per article
64
+
65
+ The app prioritizes Freepik for images to minimize costs, only using DALL-E when Freepik doesn't return results.
66
+
67
+ ## ☁️ Deployment
68
+
69
+ ### Option 1: Streamlit Cloud (Recommended - Free)
70
+
71
+ 1. Push your code to GitHub
72
+ 2. Go to [Streamlit Cloud](https://streamlit.io/cloud)
73
+ 3. Connect your GitHub repository
74
+ 4. Add environment variables:
75
+ - `OPENAI_API_KEY`
76
+ - `FREEPIK_API_KEY` (optional)
77
+ 5. Deploy!
78
+
79
+ ### Option 2: Render
80
+
81
+ 1. Create a new **Web Service** on [Render](https://render.com)
82
+ 2. Connect your GitHub repository
83
+ 3. Configure:
84
+ - **Build Command**: `pip install -r requirements.txt`
85
+ - **Start Command**: `streamlit run app.py --server.port=$PORT --server.address=0.0.0.0`
86
+ - **Environment**: Python 3
87
+ 4. Add environment variables in the Render dashboard
88
+ 5. Deploy!
89
+
90
+ ### Option 3: Railway
91
+
92
+ 1. Create a new project on [Railway](https://railway.app)
93
+ 2. Connect your GitHub repository
94
+ 3. Railway will auto-detect Python
95
+ 4. Add environment variables in the Railway dashboard
96
+ 5. Deploy!
97
+
98
+ ### Option 4: Hugging Face Spaces
99
+
100
+ 1. Create a new Space on [Hugging Face](https://huggingface.co/spaces)
101
+ 2. Select **Streamlit** as the SDK
102
+ 3. Upload your files
103
+ 4. Add secrets (environment variables) in Space settings
104
+ 5. Deploy!
105
+
106
+ ## 📁 Project Structure
107
+
108
+ ```
109
+ .
110
+ ├── app.py # Main Streamlit application
111
+ ├── requirements.txt # Python dependencies
112
+ ├── .env.example # Environment variables template
113
+ └── README.md # This file
114
+ ```
115
+
116
+ ## 🔧 Configuration
117
+
118
+ ### Environment Variables
119
+
120
+ - `OPENAI_API_KEY` (Required): Your OpenAI API key for GPT-4 Turbo and DALL-E
121
+ - `FREEPIK_API_KEY` (Optional): Your Freepik API key for cost-efficient image sourcing
122
+
123
+ ### Model Settings
124
+
125
+ The app uses:
126
+ - **GPT-4 Turbo** (`gpt-3.5-turbo`) for text generation
127
+ - **DALL-E 3** (`dall-e-3`) for image generation fallback
128
+
129
+ You can modify these in `app.py` if needed.
130
+
131
+ ## 🎯 Future Enhancements
132
+
133
+ - [ ] PDF export functionality
134
+ - [ ] Adjustable tone/voice selection
135
+ - [ ] Batch article generation
136
+ - [ ] Article editing capabilities
137
+ - [ ] Custom image prompts
138
+ - [ ] Multiple language support
139
+
140
+ ## 📝 License
141
+
142
+ This project is open source and available for personal and commercial use.
143
+
144
+ ## 🤝 Contributing
145
+
146
+ Contributions are welcome! Feel free to submit issues or pull requests.
147
+
148
+ ## ⚠️ Disclaimer
149
+
150
+ This tool generates AI content. Always review and fact-check generated articles before publishing. The AI may occasionally produce inaccurate or biased content.
151
+
152
+ ---
153
+
154
+ **Built with ❤️ by Caveman Productions**
155
+
Sample.txt ADDED
The diff for this file is too large to render. See raw diff
 
app.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import openai
3
+ import requests
4
+ import streamlit as st
5
+ from dotenv import load_dotenv
6
+
7
+ # Load environment variables
8
+ load_dotenv()
9
+
10
+ # Configure OpenAI
11
+ openai.api_key = os.getenv("OPENAI_API_KEY")
12
+
13
+ # Page configuration
14
+ st.set_page_config(
15
+ page_title="Caveman Article Agent",
16
+ page_icon="🧠",
17
+ layout="wide"
18
+ )
19
+
20
+
21
+
22
+ # Initialize session state
23
+ if 'generated_content' not in st.session_state:
24
+ st.session_state.generated_content = None
25
+
26
+
27
+ def get_freepik_image(title):
28
+ """Attempt to get an image from Freepik API."""
29
+ try:
30
+ api_key = os.getenv("FREEPIK_API_KEY")
31
+ if not api_key:
32
+ return None
33
+
34
+ headers = {"Authorization": f"Bearer {api_key}"}
35
+ params = {
36
+ "term": title,
37
+ "limit": 1,
38
+ "filters[content_type]": "photo"
39
+ }
40
+
41
+ response = requests.get(
42
+ "https://api.freepik.com/v1/resources",
43
+ headers=headers,
44
+ params=params,
45
+ timeout=10
46
+ )
47
+
48
+ if response.status_code == 200:
49
+ data = response.json()
50
+ if data.get("data") and len(data["data"]) > 0:
51
+ item = data["data"][0]
52
+ if "attributes" in item and "preview" in item["attributes"]:
53
+ return item["attributes"]["preview"].get("url")
54
+ elif "images" in item and "preview" in item["images"]:
55
+ return item["images"]["preview"].get("url")
56
+ return None
57
+ except Exception as e:
58
+ st.warning(f"Freepik API error: {str(e)}")
59
+ return None
60
+
61
+
62
+ def generate_dalle_image(title):
63
+ """Generate an image using DALL-E as fallback."""
64
+ try:
65
+ response = openai.images.generate(
66
+ model="dall-e-3",
67
+ prompt=f"Create a modern, professional header image for an article titled '{title}'. The image should be visually appealing and relevant to the topic.",
68
+ size="1024x1024",
69
+ quality="standard",
70
+ n=1
71
+ )
72
+ return response.data[0].url
73
+ except Exception as e:
74
+ st.error(f"DALL-E generation error: {str(e)}")
75
+ return None
76
+
77
+
78
+ def generate_outline(title, word_range):
79
+ """Generate article outline using GPT-4 Turbo."""
80
+ try:
81
+ response = openai.chat.completions.create(
82
+ model=os.getenv("OPENAI_VERSION"),
83
+ messages=[{
84
+ "role": "user",
85
+ "content": f"Create a detailed, structured outline for an article titled '{title}' that should be approximately {word_range} words. Format it as a clear, hierarchical outline with main sections and subsections."
86
+ }],
87
+ temperature=0.7
88
+ )
89
+ return response.choices[0].message.content
90
+ except Exception as e:
91
+ st.error(f"Outline generation error: {str(e)}")
92
+ return None
93
+
94
+
95
+ def write_article(title, outline, word_range):
96
+ """Write full article using the outline and word range."""
97
+ try:
98
+ response = openai.chat.completions.create(
99
+ model=os.getenv("OPENAI_VERSION"),
100
+ messages=[{
101
+ "role": "user",
102
+ "content": f"Write a complete, well-researched article titled '{title}' using this outline:\n\n{outline}\n\nThe article should be approximately {word_range} words. Make it engaging, informative, and professional. Include an introduction, well-structured body paragraphs, and a conclusion."
103
+ }],
104
+ temperature=0.8
105
+ )
106
+ return response.choices[0].message.content
107
+ except Exception as e:
108
+ st.error(f"Article writing error: {str(e)}")
109
+ return None
110
+
111
+
112
+ def suggest_resources(title):
113
+ """Suggest authoritative resources related to the article topic."""
114
+ try:
115
+ response = openai.chat.completions.create(
116
+ model=os.getenv("OPENAI_VERSION"),
117
+ messages=[{
118
+ "role": "user",
119
+ "content": f"Provide 5 authoritative online resources (websites, articles, studies, or references) related to '{title}'. Format each as a clear title and description. Include why each resource is valuable."
120
+ }],
121
+ temperature=0.7
122
+ )
123
+ return response.choices[0].message.content
124
+ except Exception as e:
125
+ st.error(f"Resource suggestion error: {str(e)}")
126
+ return None
127
+
128
+
129
+ def generate_header_image(title):
130
+ """Generate header image with Freepik first, DALL-E fallback."""
131
+ freepik_image = get_freepik_image(title)
132
+ if freepik_image:
133
+ return freepik_image, "Freepik"
134
+
135
+ dalle_image = generate_dalle_image(title)
136
+ if dalle_image:
137
+ return dalle_image, "DALL-E"
138
+
139
+ return None, None
140
+
141
+
142
+ # Main UI
143
+ st.title("🧠 Caveman Article Agent")
144
+ st.markdown("Generate professional articles with outlines, images, and resources")
145
+
146
+ # Sidebar for inputs
147
+ with st.sidebar:
148
+ st.header("📝 Article Settings")
149
+ title = st.text_input(
150
+ "Article Title:",
151
+ placeholder="e.g., The Future of Artificial Intelligence",
152
+ help="Enter the title of the article you want to generate"
153
+ )
154
+ word_range = st.text_input(
155
+ "Word Range:",
156
+ placeholder="e.g., 800-1000",
157
+ help="Specify the target word count range for your article"
158
+ )
159
+
160
+ generate_button = st.button(
161
+ "🚀 Generate Article",
162
+ type="primary",
163
+ use_container_width=True
164
+ )
165
+
166
+ st.markdown("---")
167
+ st.markdown("### 💡 Tips")
168
+ st.markdown("""
169
+ - Be specific with your title for better results
170
+ - Word range helps control article length
171
+ - Images are sourced from Freepik first (free), then DALL-E
172
+ - All content is AI-generated using GPT-4 Turbo
173
+ """)
174
+
175
+ # Main content area
176
+ if generate_button:
177
+ if not title or not word_range:
178
+ st.error("⚠️ Please fill in both the title and word range fields.")
179
+ elif not openai.api_key:
180
+ st.error("⚠️ OpenAI API key not found. Please set OPENAI_API_KEY in your environment variables.")
181
+ else:
182
+ progress_bar = st.progress(0)
183
+ status_text = st.empty()
184
+
185
+ generated_content = {}
186
+
187
+ status_text.info("📋 Generating article outline...")
188
+ progress_bar.progress(20)
189
+ outline = generate_outline(title, word_range)
190
+
191
+ if outline:
192
+ generated_content['outline'] = outline
193
+ progress_bar.progress(40)
194
+
195
+ status_text.info("✍️ Writing full article...")
196
+ article = write_article(title, outline, word_range)
197
+
198
+ if article:
199
+ generated_content['article'] = article
200
+ progress_bar.progress(60)
201
+
202
+ status_text.info("🖼️ Searching for header image...")
203
+ image_url, image_source = generate_header_image(title)
204
+
205
+ if image_url:
206
+ generated_content['image_url'] = image_url
207
+ generated_content['image_source'] = image_source
208
+ progress_bar.progress(80)
209
+ else:
210
+ st.warning("⚠️ Could not generate header image.")
211
+ generated_content['image_url'] = None
212
+ generated_content['image_source'] = None
213
+
214
+ status_text.info("📚 Gathering related resources...")
215
+ resources = suggest_resources(title)
216
+
217
+ if resources:
218
+ generated_content['resources'] = resources
219
+ progress_bar.progress(100)
220
+
221
+ st.session_state.generated_content = generated_content
222
+ status_text.success("✅ Article generation complete!")
223
+ else:
224
+ st.error("❌ Failed to generate article. Please try again.")
225
+ else:
226
+ st.error("❌ Failed to generate outline. Please try again.")
227
+
228
+ progress_bar.empty()
229
+ status_text.empty()
230
+
231
+ # Display generated content
232
+ if st.session_state.generated_content:
233
+ content = st.session_state.generated_content
234
+
235
+ with st.expander("📋 Article Outline", expanded=True):
236
+ st.markdown(content.get('outline', 'No outline generated.'))
237
+
238
+ st.markdown("---")
239
+ st.markdown("### 📝 Complete Article")
240
+ st.markdown(content.get('article', 'No article generated.'))
241
+ st.markdown("---")
242
+
243
+ if content.get('image_url'):
244
+ st.markdown("### 🖼️ Header Image")
245
+ st.image(
246
+ content['image_url'],
247
+ caption=f"Header Image (Source: {content.get('image_source', 'Unknown')})",
248
+ width=700
249
+ )
250
+ else:
251
+ st.markdown("### 🖼️ Header Image")
252
+ st.info("No header image available.")
253
+
254
+ st.markdown("---")
255
+ st.markdown("### 📚 Additional Resources")
256
+ st.markdown(content.get('resources', 'No resources generated.'))
257
+ st.markdown("---")
258
+
259
+ col1, col2 = st.columns(2)
260
+ with col1:
261
+ if st.button("📥 Download as Markdown"):
262
+ markdown_content = f"""# {title}
263
+
264
+ ## Outline
265
+ {content.get('outline', '')}
266
+
267
+ ## Article
268
+ {content.get('article', '')}
269
+
270
+ ## Resources
271
+ {content.get('resources', '')}
272
+ """
273
+ st.download_button(
274
+ label="Download Markdown File",
275
+ data=markdown_content,
276
+ file_name=f"{title.replace(' ', '_')}.md",
277
+ mime="text/markdown"
278
+ )
279
+ with col2:
280
+ st.info("💡 PDF export coming soon!")
281
+
282
+ st.markdown("---")
283
+ st.markdown(
284
+ "<div style='text-align: center; color: #666;'>"
285
+ "Built with ❤️ by Caveman Productions | Powered by OpenAI GPT-4 Turbo"
286
+ "</div>",
287
+ unsafe_allow_html=True
288
+ )
app.py Archive ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import openai
3
+ import requests
4
+ import streamlit as st
5
+ from dotenv import load_dotenv
6
+
7
+ # Load environment variables
8
+ load_dotenv()
9
+
10
+ # Configure OpenAI
11
+ openai.api_key = os.getenv("OPENAI_API_KEY")
12
+
13
+ # Page configuration
14
+ st.set_page_config(
15
+ page_title="Caveman Article Agent",
16
+ page_icon="🧠",
17
+ layout="wide"
18
+ )
19
+
20
+ # Initialize session state
21
+ if 'generated_content' not in st.session_state:
22
+ st.session_state.generated_content = None
23
+
24
+
25
+ def get_freepik_image(title):
26
+ """Attempt to get an image from Freepik API."""
27
+ try:
28
+ api_key = os.getenv("FREEPIK_API_KEY")
29
+ if not api_key:
30
+ return None
31
+
32
+ headers = {"Authorization": f"Bearer {api_key}"}
33
+ params = {
34
+ "term": title,
35
+ "limit": 1,
36
+ "filters[content_type]": "photo"
37
+ }
38
+
39
+ response = requests.get(
40
+ "https://api.freepik.com/v1/resources",
41
+ headers=headers,
42
+ params=params,
43
+ timeout=10
44
+ )
45
+
46
+ if response.status_code == 200:
47
+ data = response.json()
48
+ if data.get("data") and len(data["data"]) > 0:
49
+ # Navigate through the response structure
50
+ item = data["data"][0]
51
+ if "attributes" in item and "preview" in item["attributes"]:
52
+ return item["attributes"]["preview"].get("url")
53
+ elif "images" in item and "preview" in item["images"]:
54
+ return item["images"]["preview"].get("url")
55
+ return None
56
+ except Exception as e:
57
+ st.warning(f"Freepik API error: {str(e)}")
58
+ return None
59
+
60
+
61
+ def generate_dalle_image(title):
62
+ """Generate an image using DALL-E as fallback."""
63
+ try:
64
+ response = openai.images.generate(
65
+ model="dall-e-3",
66
+ prompt=f"Create a modern, professional header image for an article titled '{title}'. The image should be visually appealing and relevant to the topic.",
67
+ size="1024x1024",
68
+ quality="standard",
69
+ n=1
70
+ )
71
+ return response.data[0].url
72
+ except Exception as e:
73
+ st.error(f"DALL-E generation error: {str(e)}")
74
+ return None
75
+
76
+
77
+ def generate_outline(title, word_range):
78
+ """Generate article outline using GPT-4 Turbo."""
79
+ try:
80
+ response = openai.chat.completions.create(
81
+ model=os.getenv("OPENAI_VERSION"),
82
+ messages=[{
83
+ "role": "user",
84
+ "content": f"Create a detailed, structured outline for an article titled '{title}' that should be approximately {word_range} words. Format it as a clear, hierarchical outline with main sections and subsections."
85
+ }],
86
+ temperature=0.7
87
+ )
88
+ return response.choices[0].message.content
89
+ except Exception as e:
90
+ st.error(f"Outline generation error: {str(e)}")
91
+ return None
92
+
93
+
94
+ def write_article(title, outline, word_range):
95
+ """Write full article using the outline and word range."""
96
+ try:
97
+ response = openai.chat.completions.create(
98
+ model=os.getenv("OPENAI_VERSION"),
99
+ messages=[{
100
+ "role": "user",
101
+ "content": f"Write a complete, well-researched article titled '{title}' using this outline:\n\n{outline}\n\nThe article should be approximately {word_range} words. Make it engaging, informative, and professional. Include an introduction, well-structured body paragraphs, and a conclusion."
102
+ }],
103
+ temperature=0.8
104
+ )
105
+ return response.choices[0].message.content
106
+ except Exception as e:
107
+ st.error(f"Article writing error: {str(e)}")
108
+ return None
109
+
110
+
111
+ def suggest_resources(title):
112
+ """Suggest authoritative resources related to the article topic."""
113
+ try:
114
+ response = openai.chat.completions.create(
115
+ model=os.getenv("OPENAI_VERSION"),
116
+ messages=[{
117
+ "role": "user",
118
+ "content": f"Provide 5 authoritative online resources (websites, articles, studies, or references) related to '{title}'. Format each as a clear title and description. Include why each resource is valuable."
119
+ }],
120
+ temperature=0.7
121
+ )
122
+ return response.choices[0].message.content
123
+ except Exception as e:
124
+ st.error(f"Resource suggestion error: {str(e)}")
125
+ return None
126
+
127
+
128
+ def generate_header_image(title):
129
+ """Generate header image with Freepik first, DALL-E fallback."""
130
+ # Try Freepik first
131
+ freepik_image = get_freepik_image(title)
132
+ if freepik_image:
133
+ return freepik_image, "Freepik"
134
+
135
+ # Fallback to DALL-E
136
+ dalle_image = generate_dalle_image(title)
137
+ if dalle_image:
138
+ return dalle_image, "DALL-E"
139
+
140
+ return None, None
141
+
142
+
143
+ # Main UI
144
+ st.title("🧠 Caveman Article Agent")
145
+ st.markdown("Generate professional articles with outlines, images, and resources")
146
+
147
+ # Sidebar for inputs
148
+ with st.sidebar:
149
+ st.header("📝 Article Settings")
150
+ title = st.text_input(
151
+ "Article Title:",
152
+ placeholder="e.g., The Future of Artificial Intelligence",
153
+ help="Enter the title of the article you want to generate"
154
+ )
155
+ word_range = st.text_input(
156
+ "Word Range:",
157
+ placeholder="e.g., 800-1000",
158
+ help="Specify the target word count range for your article"
159
+ )
160
+
161
+ generate_button = st.button(
162
+ "🚀 Generate Article",
163
+ type="primary",
164
+ use_container_width=True
165
+ )
166
+
167
+ st.markdown("---")
168
+ st.markdown("### 💡 Tips")
169
+ st.markdown("""
170
+ - Be specific with your title for better results
171
+ - Word range helps control article length
172
+ - Images are sourced from Freepik first (free), then DALL-E
173
+ - All content is AI-generated using GPT-4 Turbo
174
+ """)
175
+
176
+ # Main content area
177
+ if generate_button:
178
+ if not title or not word_range:
179
+ st.error("⚠️ Please fill in both the title and word range fields.")
180
+ elif not openai.api_key:
181
+ st.error("⚠️ OpenAI API key not found. Please set OPENAI_API_KEY in your environment variables.")
182
+ else:
183
+ # Initialize progress
184
+ progress_bar = st.progress(0)
185
+ status_text = st.empty()
186
+
187
+ generated_content = {}
188
+
189
+ # Step 1: Generate outline
190
+ status_text.info("📋 Generating article outline...")
191
+ progress_bar.progress(20)
192
+ outline = generate_outline(title, word_range)
193
+
194
+ if outline:
195
+ generated_content['outline'] = outline
196
+ progress_bar.progress(40)
197
+
198
+ # Step 2: Write article
199
+ status_text.info("✍️ Writing full article...")
200
+ article = write_article(title, outline, word_range)
201
+
202
+ if article:
203
+ generated_content['article'] = article
204
+ progress_bar.progress(60)
205
+
206
+ # Step 3: Generate header image
207
+ status_text.info("🖼️ Searching for header image...")
208
+ image_url, image_source = generate_header_image(title)
209
+
210
+ if image_url:
211
+ generated_content['image_url'] = image_url
212
+ generated_content['image_source'] = image_source
213
+ progress_bar.progress(80)
214
+ else:
215
+ st.warning("⚠️ Could not generate header image.")
216
+ generated_content['image_url'] = None
217
+ generated_content['image_source'] = None
218
+
219
+ # Step 4: Suggest resources
220
+ status_text.info("📚 Gathering related resources...")
221
+ resources = suggest_resources(title)
222
+
223
+ if resources:
224
+ generated_content['resources'] = resources
225
+ progress_bar.progress(100)
226
+
227
+ # Store in session state
228
+ st.session_state.generated_content = generated_content
229
+ status_text.success("✅ Article generation complete!")
230
+ else:
231
+ st.error("❌ Failed to generate article. Please try again.")
232
+ else:
233
+ st.error("❌ Failed to generate outline. Please try again.")
234
+
235
+ progress_bar.empty()
236
+ status_text.empty()
237
+
238
+ # Display generated content
239
+ if st.session_state.generated_content:
240
+ content = st.session_state.generated_content
241
+
242
+ # Outline section (expandable)
243
+ with st.expander("📋 Article Outline", expanded=True):
244
+ st.markdown(content.get('outline', 'No outline generated.'))
245
+
246
+ st.markdown("---")
247
+
248
+ # Article section
249
+ st.markdown("### 📝 Complete Article")
250
+ st.markdown(content.get('article', 'No article generated.'))
251
+
252
+ st.markdown("---")
253
+
254
+ # Header image section
255
+ if content.get('image_url'):
256
+ st.markdown("### 🖼️ Header Image")
257
+ image_source = content.get('image_source', 'Unknown')
258
+ st.image(
259
+ content['image_url'],
260
+ caption=f"Header Image (Source: {image_source})",
261
+ width=700 # Fixed width instead of use_container_width
262
+ )
263
+ else:
264
+ st.markdown("### 🖼️ Header Image")
265
+ st.info("No header image available.")
266
+
267
+ st.markdown("---")
268
+
269
+ # Resources section
270
+ st.markdown("### 📚 Additional Resources")
271
+ st.markdown(content.get('resources', 'No resources generated.'))
272
+
273
+ st.markdown("---")
274
+
275
+ # Download options
276
+ col1, col2 = st.columns(2)
277
+ with col1:
278
+ if st.button("📥 Download as Markdown"):
279
+ markdown_content = f"""# {title}
280
+
281
+ ## Outline
282
+
283
+ {content.get('outline', '')}
284
+
285
+ ## Article
286
+
287
+ {content.get('article', '')}
288
+
289
+ ## Resources
290
+
291
+ {content.get('resources', '')}
292
+ """
293
+ st.download_button(
294
+ label="Download Markdown File",
295
+ data=markdown_content,
296
+ file_name=f"{title.replace(' ', '_')}.md",
297
+ mime="text/markdown"
298
+ )
299
+
300
+ with col2:
301
+ st.info("💡 PDF export coming soon!")
302
+
303
+ # Footer
304
+ st.markdown("---")
305
+ st.markdown(
306
+ "<div style='text-align: center; color: #666;'>"
307
+ "Built with ❤️ by Caveman Productions | Powered by OpenAI GPT-4 Turbo"
308
+ "</div>",
309
+ unsafe_allow_html=True
310
+ )
311
+
article_agent.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import openai
3
+ import requests
4
+ import json
5
+ from openai import OpenAI
6
+ from dotenv import load_dotenv
7
+
8
+ # Load environment variables
9
+ load_dotenv()
10
+
11
+ # Initialize OpenAI client
12
+ client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
13
+
14
+ class ArticleAgent:
15
+ def __init__(self):
16
+ self.model = os.getenv("OPENAI_VERSION")
17
+ self.image_size = "1024x1024"
18
+
19
+ def generate_article(self, title):
20
+ """Generate a complete article from a title"""
21
+ try:
22
+ # Generate article outline
23
+ outline = self._generate_outline(title)
24
+
25
+ # Generate full article
26
+ article = self._generate_full_article(title, outline)
27
+
28
+ # Generate image
29
+ image_url = self._generate_image(title)
30
+
31
+ # Generate additional resources
32
+ resources = self._generate_resources(title)
33
+
34
+ return {
35
+ "title": title,
36
+ "outline": outline,
37
+ "article": article,
38
+ "image_url": image_url,
39
+ "additional_resources": resources
40
+ }
41
+
42
+ except Exception as e:
43
+ print(f"Error generating article: {str(e)}")
44
+ return None
45
+
46
+ def _generate_outline(self, title):
47
+ """Generate an outline for the article"""
48
+ prompt = f"""Create a detailed outline for an article titled: "{title}".
49
+ The outline should include an introduction, 3-5 main sections with 2-3 subsections each,
50
+ and a conclusion. Format the response in markdown."""
51
+
52
+ response = client.chat.completions.create(
53
+ model=self.model,
54
+ messages=[
55
+ {"role": "system", "content": "You are a professional content creator who creates well-structured article outlines."},
56
+ {"role": "user", "content": prompt}
57
+ ]
58
+ )
59
+
60
+ return response.choices[0].message.content
61
+
62
+ def _generate_full_article(self, title, outline):
63
+ """Generate the full article based on title and outline"""
64
+ prompt = f"""Write a comprehensive, well-researched article with the following details:
65
+ Title: {title}
66
+
67
+ Outline:
68
+ {outline}
69
+
70
+ The article should be well-structured, engaging, and informative. Include relevant examples and data where appropriate.
71
+ Format the response in markdown with proper headings, subheadings, and paragraphs."""
72
+
73
+ response = client.chat.completions.create(
74
+ model=self.model,
75
+ messages=[
76
+ {"role": "system", "content": "You are a professional writer who creates high-quality, engaging articles."},
77
+ {"role": "user", "content": prompt}
78
+ ]
79
+ )
80
+
81
+ return response.choices[0].message.content
82
+
83
+ def _generate_image(self, title):
84
+ """Generate an image for the article headline"""
85
+ try:
86
+ response = client.images.generate(
87
+ model="dall-e-3",
88
+ prompt=f"Create a professional, high-quality image that represents the following article title: {title}. The image should be suitable for a blog post header.",
89
+ size=self.image_size,
90
+ quality="standard",
91
+ n=1,
92
+ )
93
+ return response.data[0].url
94
+ except Exception as e:
95
+ print(f"Error generating image: {str(e)}")
96
+ return None
97
+
98
+ def _generate_resources(self, title):
99
+ """Generate additional resources related to the article topic"""
100
+ prompt = f"""Provide 3-5 high-quality, authoritative resources (websites, books, research papers)
101
+ for readers who want to learn more about: {title}.
102
+
103
+ Format the response as a markdown list with brief descriptions for each resource."""
104
+
105
+ response = client.chat.completions.create(
106
+ model=self.model,
107
+ messages=[
108
+ {"role": "system", "content": "You are a research assistant who provides valuable resources for further reading."},
109
+ {"role": "user", "content": prompt}
110
+ ]
111
+ )
112
+
113
+ return response.choices[0].message.content
114
+
115
+ # Example usage
116
+ if __name__ == "__main__":
117
+ agent = ArticleAgent()
118
+
119
+ # Example title - you can replace this with any title
120
+ example_title = "The Future of Artificial Intelligence in Healthcare"
121
+
122
+ print(f"Generating article for: {example_title}")
123
+ result = agent.generate_article(example_title)
124
+
125
+ if result:
126
+ # Save the results to files
127
+ os.makedirs("generated_articles", exist_ok=True)
128
+ base_filename = f"generated_articles/{example_title.lower().replace(' ', '_')[:50]}"
129
+
130
+ with open(f"{base_filename}_article.md", "w") as f:
131
+ f.write(f"# {result['title']}\n\n")
132
+ f.write("## Outline\n\n")
133
+ f.write(result['outline'])
134
+ f.write("\n\n## Article\n\n")
135
+ f.write(result['article'])
136
+ f.write("\n\n## Additional Resources\n\n")
137
+ f.write(result['additional_resources'])
138
+
139
+ # Save image URL
140
+ with open(f"{base_filename}_image.txt", "w") as f:
141
+ f.write(f"Image URL: {result['image_url']}")
142
+
143
+ print(f"\nArticle generated successfully!")
144
+ print(f"- Article saved to: {base_filename}_article.md")
145
+ print(f"- Image URL saved to: {base_filename}_image.txt")
146
+ print(f"\nImage URL: {result['image_url']}")
147
+ else:
148
+ print("Failed to generate article. Please check your API key and try again.")
env.example ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # OpenAI API Key
2
+ # Get your API key from: https://platform.openai.com/api-keys
3
+ OPENAI_API_KEY=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
4
+
5
+ # Freepik API Key (Optional but recommended for cost savings)
6
+ # Get your API key from: https://www.freepik.com/api
7
+ # If not provided, the app will use DALL-E for all images
8
+ FREEPIK_API_KEY=FPSX93b11d12b924bbc0cfd22b0b92773aab
9
+
procfile ADDED
@@ -0,0 +1 @@
 
 
1
+ web: streamlit run app.py --server.port=$PORT --server.address=0.0.0.0
procfile.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ web: streamlit run app.py --server.port=$PORT --server.address=0.0.0.0
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ streamlit>=1.28.0
2
+ openai>=1.12.0
3
+ requests>=2.31.0
4
+ python-dotenv>=1.0.0
5
+