File size: 6,711 Bytes
3bc4b9c
166a787
f5a396a
3776948
166a787
 
 
abe333e
166a787
717fa5f
3bc4b9c
166a787
8015ffa
717fa5f
 
 
 
 
 
 
 
 
 
 
 
 
2bd2884
166a787
 
 
 
 
 
 
3776948
166a787
 
 
 
 
 
 
 
 
 
 
3776948
166a787
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bc4b9c
166a787
 
 
 
 
 
 
 
 
 
 
 
 
 
3bc4b9c
166a787
 
3bc4b9c
166a787
 
 
 
 
 
3bc4b9c
 
166a787
 
 
 
3bc4b9c
 
166a787
 
 
 
 
 
3bc4b9c
 
166a787
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bc4b9c
 
166a787
 
 
 
 
 
 
 
 
 
 
 
35bafe7
06696c4
 
166a787
 
2bd2884
06696c4
 
 
 
8f9f452
 
06696c4
166a787
 
06696c4
 
166a787
 
 
 
 
 
 
 
 
 
 
cfbaf66
166a787
3bc4b9c
 
 
 
 
 
 
 
 
 
166a787
 
 
 
 
 
 
 
 
 
 
 
3bc4b9c
 
 
 
 
166a787
 
 
6cf25d0
 
8f9f452
166a787
 
 
 
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

import streamlit as st
from langchain.prompts import PromptTemplate
import requests
from langchain.llms import HuggingFaceHub
from langchain.chains import LLMChain
import io
import os
from PIL import Image
import json
from model import model,tokenizer

API = os.environ.get("HUGGINGFACEHUB_API_TOKEN")
# Load existing ideas from a file
def load_ideas():
    try:
        with open("ideas.json", "r") as file:
            ideas = json.load(file)
    except FileNotFoundError:
        ideas = []
    return ideas

# Save ideas to a file
def save_ideas(ideas):
    with open("ideas.json", "w") as file:
        json.dump(ideas, file)

# Save image to a file
def save_image(image, image_path):
    image.save(image_path)



# content generation
def generate_content(topic):
  keyword=topic
  prompt = [{'role': 'user', 'content': f'''Write a comprehensive article about {keyword} covering the following aspects:
          Introduction, History and Background, Key Concepts and Terminology, Use Cases and Applications, Benefits and Drawbacks, Future Outlook, Conclusion
          Ensure that the article is well-structured, informative, and at least 2000 words long. Use SEO best practices for content optimization.
          Add ## before section headers
  '''}]
  inputs = tokenizer.apply_chat_template(
      prompt,
      add_generation_prompt=True,
      return_tensors='pt'
  )

  tokens = model.generate(
      inputs.to(model.device),
      max_new_tokens=10024,
      temperature=0.8,
      do_sample=True
  )

  content = tokenizer.decode(tokens[0], skip_special_tokens=False)
  # print(content)
  return content

def divide_content(text):
    sections = {}
    lines = text.split('\n')

    current_section = None

    for line in lines:
        line = line.strip()  # Remove leading and trailing whitespaces
        if line.startswith("##"):
            # Found a new section marker
            current_section = line[2:]
            sections[current_section] = ""
        elif current_section is not None and line:
            # Append the line to the current section if it's not empty
            sections[current_section] += line + " "

    # Remove trailing whitespaces from each section
    for section_name, section_content in sections.items():
        sections[section_name] = section_content.rstrip()

    return sections


# Image Generation
API_URL = "https://api-inference.huggingface.co/models/goofyai/3d_render_style_xl"
headers = {"Authorization": "Bearer API"}

def query(payload):
	response = requests.post(API_URL, headers=headers, json=payload)
	return response.content

def generat_image(image_prompt,name):
      image_bytes = query({
          "inputs": image_prompt,
      })
      image = Image.open(io.BytesIO(image_bytes))
      image.save(f"{name}.png")
      return image

def display_content_with_images(blog):
    blog_images = [key for key in list(blog.keys()) if "_image" in key]
    # Streamlit Display
    st.header(blog['title'])
    i = 0
    # Introduction
    col1, col2 = st.columns(2, gap='medium')
    with col1:
      st.header('Introduction')
      st.write(blog['Introduction'])
    with col2:
      st.image(blog[blog_images[i]], use_column_width=True)
      i+=1

    # History
    st.header('History and Background')
    st.write(blog['History and Background'])
    st.image(blog[blog_images[i]], use_column_width=True)
    i+=1
    # Content
    col1, col2 = st.columns(2, gap='medium')
    with col1:
      st.header('Key Concepts and Terminology')
      st.write(blog['Key Concepts and Terminology'])
    with col2:
      st.image(blog[blog_images[i]], use_column_width=True)
      i+=1
    # Use Cases and Applications
    st.header('Use Cases and Applications')
    st.write(blog['Use Cases and Applications'])

    # Benefits and Drawbacks
    st.header('Benefits and Drawbacks')
    st.write(blog['Benefits and Drawbacks'])

    # Future Outlook
    st.header('Future Outlook')
    st.write(blog['Future Outlook'])

    # Conclusion
    col1, col2 = st.columns(2, gap='medium')
    with col1:
      st.header('Conclusion')
      st.write(blog['Conclusion'])
    with col2:
      st.image(blog[blog_images[i]], use_column_width=True)
      i+=1


# Streamlit App

# Title
st.sidebar.title('📝 Previous Ideas')
st.title("AI Blog Content Generator 😊")
# Main Page
col1, col2, col3 = st.columns((1, 3, 1), gap='large')


existing_ideas = load_ideas()

# Input and button
topic = st.text_input("Enter Title for the blog")
button_clicked = st.button("Create blog!❤️")


# Display existing ideas in the sidebar
keys = list(set([key for idea in existing_ideas for key in idea.keys()]))
if topic in keys:
    index = keys.index(topic)
    selected_idea = st.sidebar.selectbox("Select Idea", keys, key=f"selectbox{topic}", index=index)
    # Display content and image for the selected idea
    selected_idea_from_list = next((idea for idea in existing_ideas if selected_idea in idea), None)
    st.subheader(topic)
    display_content_with_images(selected_idea_from_list[selected_idea])
else:
    index = 0

# Check if the topic exists in previous ideas before generating
if button_clicked and topic not in keys:
    st.write('Generating blog post about', topic, '...')
    st.write('This may take a few minutes.')

    topic_query = topic

    content = generate_content(topic)
    # st.write(content)
    blog = divide_content(content)
    st.write(blog)
    st.header(topic)
    keyss = list(blog.keys())
    image_prompts = []
    i=0
    while len(image_prompts)<4:
      try:
        image_prompts.append((keyss[i],blog[keyss[i]].splitlines()[0]))
        i+=1
      except Exception as e:
        print(e)
        i+=1

    # Blog Data
    blog_data = {
        'title': topic,
        'Introduction': blog[' Introduction'],
        'History and Background': blog[' History and Background'],
        'Key Concepts and Terminology': blog[' Key Concepts and Terminology'],
        'Use Cases and Applications': blog[' Use Cases and Applications'],
        'Benefits and Drawbacks': blog[' Benefits and Drawbacks'],
        'Future Outlook': blog[' Future Outlook'],
        'Conclusion': blog[' Conclusion'],
    }
    for k,image in image_prompts:
      img = generat_image(image,f" {k}{topic}")
      blog_data[f'{k}_image'] = f" {k}{topic}.png"
    
    display_content_with_images(blog_data)

    # Save blog with images
    existing_ideas.append({topic: blog_data})
    # Update keys and selected idea in the sidebar
    keys = list(set([key for idea in existing_ideas for key in idea.keys()]))
    selected_idea = st.sidebar.selectbox("Select Idea", keys, key=f"selectbox{topic}", index=keys.index(topic))

    save_ideas(existing_ideas)