File size: 9,996 Bytes
f4ae53e
 
 
 
 
 
 
 
 
 
 
756a034
 
 
 
f4ae53e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
756a034
f4ae53e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
756a034
 
f4ae53e
 
 
 
 
 
 
 
 
 
756a034
f4ae53e
756a034
f4ae53e
 
756a034
f4ae53e
 
756a034
 
 
f4ae53e
 
 
 
 
 
 
 
 
 
756a034
f4ae53e
 
756a034
f4ae53e
 
756a034
 
 
 
f4ae53e
 
 
 
 
 
 
 
 
 
 
 
 
756a034
f4ae53e
 
756a034
 
 
f4ae53e
 
 
 
 
 
 
 
 
 
 
 
 
 
756a034
f4ae53e
 
 
756a034
f4ae53e
 
 
756a034
f4ae53e
756a034
f4ae53e
 
 
 
 
 
756a034
f4ae53e
 
 
 
756a034
f4ae53e
756a034
 
f4ae53e
 
 
 
756a034
 
 
f4ae53e
 
756a034
f4ae53e
 
756a034
f4ae53e
756a034
f4ae53e
 
 
756a034
f4ae53e
756a034
 
f4ae53e
 
756a034
f4ae53e
756a034
f4ae53e
756a034
 
f4ae53e
756a034
f4ae53e
756a034
f4ae53e
756a034
 
f4ae53e
756a034
f4ae53e
756a034
 
f4ae53e
 
 
756a034
 
f4ae53e
756a034
f4ae53e
756a034
f4ae53e
756a034
f4ae53e
 
 
756a034
f4ae53e
756a034
 
f4ae53e
 
 
756a034
f4ae53e
 
756a034
f4ae53e
756a034
 
f4ae53e
 
756a034
 
f4ae53e
756a034
f4ae53e
 
756a034
f4ae53e
 
 
 
 
 
756a034
f4ae53e
 
756a034
 
f4ae53e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
756a034
f4ae53e
 
 
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
import os
import openai
import requests
import streamlit as st
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Configure OpenAI
openai.api_key = os.getenv("OPENAI_API_KEY")
model_name = os.getenv("OPENAI_VERSION", "gpt-4o-mini")  # ✅ Fallback model

if not openai.api_key:
    st.error("⚠️ OpenAI API key not found. Please set OPENAI_API_KEY in your environment variables.")

# Page configuration
st.set_page_config(
    page_title="Caveman Article Agent",
    page_icon="🧠",
    layout="wide"
)

# Initialize session state
if 'generated_content' not in st.session_state:
    st.session_state.generated_content = None


def get_freepik_image(title):
    """Attempt to get an image from Freepik API."""
    try:
        api_key = os.getenv("FREEPIK_API_KEY")
        if not api_key:
            return None

        headers = {"Authorization": f"Bearer {api_key}"}
        params = {
            "term": title,
            "limit": 1,
            "filters[content_type]": "photo"
        }
        response = requests.get(
            "https://api.freepik.com/v1/resources",
            headers=headers,
            params=params,
            timeout=10
        )
        if response.status_code == 200:
            data = response.json()
            if data.get("data") and len(data["data"]) > 0:
                item = data["data"][0]
                if "attributes" in item and "preview" in item["attributes"]:
                    return item["attributes"]["preview"].get("url")
                elif "images" in item and "preview" in item["images"]:
                    return item["images"]["preview"].get("url")
        return None
    except Exception as e:
        st.warning(f"Freepik API error: {str(e)}")
        return None


def generate_dalle_image(title):
    """Generate an image using DALL-E as fallback."""
    try:
        response = openai.images.generate(
            model="dall-e-3",
            prompt=f"Create a modern, professional header image for an article titled '{title}'. "
                   f"The image should be visually appealing and relevant to the topic.",
            size="1024x1024",
            quality="standard",
            n=1
        )
        return response.data[0].url
    except Exception as e:
        st.error(f"DALL-E generation error: {str(e)}")
        return None


# ✅ All OpenAI calls now use model_name safely
def generate_outline(title, word_range):
    """Generate article outline using ChatGPT model."""
    try:
        response = openai.chat.completions.create(
            model=model_name,
            messages=[{
                "role": "user",
                "content": f"Create a detailed, structured outline for an article titled '{title}' "
                           f"that should be approximately {word_range} words. Format it as a clear, hierarchical outline "
                           f"with main sections and subsections."
            }],
            temperature=0.7
        )
        return response.choices[0].message.content
    except Exception as e:
        st.error(f"Outline generation error: {str(e)}")
        return None


def write_article(title, outline, word_range):
    """Write full article using the outline and target word range."""
    try:
        response = openai.chat.completions.create(
            model=model_name,
            messages=[{
                "role": "user",
                "content": f"Write a complete, well-researched article titled '{title}' using this outline:\n\n"
                           f"{outline}\n\nThe article should be around {word_range} words. "
                           f"Make it engaging, informative, and professional. Include an introduction, "
                           f"structured body, and a conclusion."
            }],
            temperature=0.8
        )
        return response.choices[0].message.content
    except Exception as e:
        st.error(f"Article writing error: {str(e)}")
        return None


def suggest_resources(title):
    """Suggest authoritative resources related to the article topic."""
    try:
        response = openai.chat.completions.create(
            model=model_name,
            messages=[{
                "role": "user",
                "content": f"Provide 5 authoritative online resources (websites, articles, studies, or references) "
                           f"related to '{title}'. Format each as a clear title and description. "
                           f"Include why each resource is valuable."
            }],
            temperature=0.7
        )
        return response.choices[0].message.content
    except Exception as e:
        st.error(f"Resource suggestion error: {str(e)}")
        return None


def generate_header_image(title):
    """Generate header image with Freepik first, DALL-E fallback."""
    freepik_image = get_freepik_image(title)
    if freepik_image:
        return freepik_image, "Freepik"

    dalle_image = generate_dalle_image(title)
    if dalle_image:
        return dalle_image, "DALL-E"

    return None, None


# 🧠 Streamlit UI
st.title("🧠 Caveman Article Agent")
st.markdown("Generate professional, AI-assisted articles complete with outlines, images, and sources.")

with st.sidebar:
    st.header("📝 Article Settings")
    title = st.text_input(
        "Article Title:",
        placeholder="e.g., The Future of Artificial Intelligence",
        help="Enter the article's main topic"
    )
    word_range = st.text_input(
        "Word Range:",
        placeholder="e.g., 800-1000",
        help="Specify target word count"
    )
    generate_button = st.button("🚀 Generate Article", type="primary", use_container_width=True)

    st.markdown("---")
    st.markdown("### 💡 Tips")
    st.markdown("""

    - Be specific with your title for better results  

    - Use a clear word range to control article size  

    - Images are fetched from Freepik, then DALL·E if needed  

    - Powered by OpenAI (GPT‑4 or fallback model)

    """)

# 🧩 Main Generation Flow
if generate_button:
    if not title or not word_range:
        st.error("⚠️ Please fill both the title and word range fields.")
    elif not openai.api_key:
        st.error("⚠️ OpenAI API key missing. Set it in the environment variables.")
    else:
        progress_bar = st.progress(0)
        status_text = st.empty()

        generated_content = {}

        status_text.info("📋 Generating outline...")
        progress_bar.progress(20)
        outline = generate_outline(title, word_range)

        if outline:
            generated_content["outline"] = outline
            progress_bar.progress(40)

            status_text.info("✍️ Writing article...")
            article = write_article(title, outline, word_range)

            if article:
                generated_content["article"] = article
                progress_bar.progress(60)

                status_text.info("🖼️ Generating header image...")
                image_url, image_source = generate_header_image(title)

                if image_url:
                    generated_content["image_url"] = image_url
                    generated_content["image_source"] = image_source
                    progress_bar.progress(80)
                else:
                    st.warning("⚠️ Could not generate header image.")

                status_text.info("📚 Gathering resources...")
                resources = suggest_resources(title)

                if resources:
                    generated_content["resources"] = resources
                    progress_bar.progress(100)

                st.session_state.generated_content = generated_content
                status_text.success("✅ Article generation complete!")
            else:
                st.error("❌ Failed to write article. Please try again.")
        else:
            st.error("❌ Outline generation failed. Please try again.")

        progress_bar.empty()
        status_text.empty()

# 📝 Display Generated Content
if st.session_state.generated_content:
    content = st.session_state.generated_content

    with st.expander("📋 Article Outline", expanded=True):
        st.markdown(content.get("outline", "No outline generated."))

    st.markdown("---")
    st.markdown("### 📝 Complete Article")
    st.markdown(content.get("article", "No article generated."))

    st.markdown("---")
    if content.get("image_url"):
        st.markdown("### 🖼️ Header Image")
        st.image(
            content["image_url"],
            caption=f"Header Image (Source: {content.get('image_source', 'Unknown')})",
            width=700
        )
    else:
        st.markdown("### 🖼️ Header Image")
        st.info("No header image available.")

    st.markdown("---")
    st.markdown("### 📚 Additional Resources")
    st.markdown(content.get("resources", "No resources generated."))

    st.markdown("---")
    col1, col2 = st.columns(2)
    with col1:
        if st.button("📥 Download as Markdown"):
            markdown_content = f"""# {title}



## Outline

{content.get('outline', '')}



## Article

{content.get('article', '')}



## Resources

{content.get('resources', '')}

"""
            st.download_button(
                label="Download Markdown File",
                data=markdown_content,
                file_name=f"{title.replace(' ', '_')}.md",
                mime="text/markdown"
            )
    with col2:
        st.info("💡 PDF export coming soon!")

st.markdown("---")
st.markdown(
    "<div style='text-align: center; color: #666;'>"
    "Built with ❤️ by Caveman Productions | Powered by OpenAI"
    "</div>",
    unsafe_allow_html=True
)