Spaces:
Sleeping
Sleeping
File size: 8,620 Bytes
166a787 f5a396a 3776948 166a787 717fa5f 166a787 e51a2dc 166a787 2a0aac7 166a787 717fa5f 2bd2884 166a787 3776948 166a787 3776948 166a787 35bafe7 06696c4 166a787 2bd2884 06696c4 8f9f452 06696c4 166a787 06696c4 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 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 |
import streamlit as st
from langchain.prompts import PromptTemplate
import requests
from langchain.llms import HuggingFaceHub
from langchain.chains import LLMChain
import io
from PIL import Image
import json
from model import create_model
import torch
api_key = st.secrets["API"]
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model,tokenizer = create_model()
# 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": f"Bearer {api_key}"}
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
# st.title('AI Blog Content Generator')
# st.header('What is the topic of your blog post?')
# topic_text = st.text_input('Topic:', placeholder='Example: Generative AI')
# submitted = st.button('Submit')
def display_content_with_images(blog):
# Streamlit Display
st.header(blog['title'])
# Introduction
col1, col2 = st.columns(2, gap='medium')
with col1:
st.header('Introduction')
st.write(blog['Introduction'])
with col2:
st.image(blog['introduction_image'], use_column_width=True)
# History
st.header('History and Background')
st.write(blog['History and Background'])
st.image(blog['History and Background_image'], use_column_width=True)
# 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['Key Concepts and Terminology_image'], use_column_width=True)
# 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['Conclusion_image'])
# 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)
print(blog)
st.header(topic)
# Introduction
col1, col2 = st.columns(2, gap='medium')
with col1:
st.subheader('Introduction')
st.write(blog[' Introduction'])
with col2:
image_prompt = blog[' Introduction'].splitlines()[0]
introduction_image = generat_image(image_prompt,f" Introduction{topic}")
st.image(introduction_image, use_column_width=True)
st.divider()
# History
st.subheader('History and Background')
st.write(blog[' History and Background'])
image_prompt = blog[' History and Background'].splitlines()[0]
history_image =generat_image(image_prompt,f" History and Background{topic}")
st.image(history_image, use_column_width=True)
st.divider()
# Key Concepts and Terminology
col1, col2 = st.columns(2, gap='medium')
with col1:
st.subheader('Key Concepts and Terminology')
st.write(blog[' Key Concepts and Terminology'])
with col2:
image_prompt = blog[' Key Concepts and Terminology'].splitlines()[0]
key_concepts_image = generat_image(image_prompt,f" Key Concepts and Terminology{topic}")
st.image(key_concepts_image, use_column_width=True)
st.divider()
# Use Cases and Applications
st.subheader('Use Cases and Applications')
st.write(blog[' Use Cases and Applications'])
# Benefits and Drawbacks
st.subheader('Benefits and Drawbacks')
st.write(blog[' Benefits and Drawbacks'])
# Future Outlook
st.subheader('Future Outlook')
st.write(blog[' Future Outlook'])
# Conclusion
col1, col2 = st.columns(2, gap='medium')
with col1:
st.subheader('Conclusion')
st.write(blog[' Conclusion'])
with col2:
image_prompt = blog[' Conclusion'].splitlines()[0]
conclusion_image = generat_image(image_prompt,f" Conclusion{topic}")
st.image(conclusion_image, use_column_width=True)
# Blog Data
blog_data = {
'title': topic,
'Introduction': blog[' Introduction'],
'introduction_image': f" Introduction{topic}.png",
'History and Background': blog[' History and Background'],
'History and Background_image': f" History and Background{topic}.png",
'Key Concepts and Terminology': blog[' Key Concepts and Terminology'],
'Key Concepts and Terminology_image': f" Key Concepts and Terminology{topic}.png",
'Use Cases and Applications': blog[' Use Cases and Applications'],
'Benefits and Drawbacks': blog[' Benefits and Drawbacks'],
'Future Outlook': blog[' Future Outlook'],
'Conclusion': blog[' Conclusion'],
'Conclusion_image': f" Conclusion{topic}.png"
}
# 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)
|