Mo-alaa commited on
Commit
166a787
·
verified ·
1 Parent(s): 90e0882

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +234 -81
app.py CHANGED
@@ -1,13 +1,17 @@
1
- from diffusers import StableDiffusionPipeline
2
- import torch
3
- from langchain.chains import LLMChain
4
- from langchain.llms import HuggingFaceHub
5
  from langchain.prompts import PromptTemplate
6
  import requests
7
- import base64
8
- import streamlit as st
 
 
9
  import json
 
10
 
 
 
 
 
11
  # Load existing ideas from a file
12
  def load_ideas():
13
  try:
@@ -22,73 +26,144 @@ def save_ideas(ideas):
22
  with open("ideas.json", "w") as file:
23
  json.dump(ideas, file)
24
 
25
-
26
- # Function to generate content
27
- @torch.no_grad()
 
 
 
 
28
  def generate_content(topic):
29
- hub_llm = HuggingFaceHub(repo_id="HuggingFaceH4/zephyr-7b-beta")
30
- prompt = PromptTemplate(
31
- input_variables=['keyword'],
32
- template="""
33
- Write a comprehensive article about {keyword} covering the following aspects:
34
- Introduction, History and Background, Key Concepts and Terminology, Use Cases and Applications, Benefits and Drawbacks, Future Outlook, Conclusion
35
- Ensure that the article is well-structured, informative, and at least 1500 words long. Use SEO best practices for content optimization.
36
- """
37
- )
38
- hub_chain = LLMChain(prompt=prompt, llm=hub_llm, verbose=True)
39
- content = hub_chain.run(topic)
40
-
41
- subheadings = [
42
- "Introduction",
43
- "History and Background",
44
- "Key Concepts and Terminology",
45
- "Use Cases and Applications",
46
- "Benefits and Drawbacks",
47
- "Future Outlook",
48
- "Conclusion",
49
- ]
50
-
51
- for subheading in subheadings:
52
- if (subheading + ":") in content:
53
- content = content.replace(subheading + ":", "## " + subheading + "\n")
54
- elif subheading in content:
55
- content = content.replace(subheading, "## " + subheading + "\n")
56
-
57
- return content
58
-
59
-
60
-
61
- # generate image
62
 
63
- import io
64
- from PIL import Image
65
- # Function to generate an image using the pre-created or newly created pipeline
66
- @torch.no_grad()
67
- def generate_image(topic):
68
- API_URL = "https://api-inference.huggingface.co/models/runwayml/stable-diffusion-v1-5"
69
- headers = {"Authorization": "Bearer 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"}
70
-
71
- def query(payload):
72
- response = requests.post(API_URL, headers=headers, json=payload)
73
- return response.content
74
- image_bytes = query({
75
- "inputs": f"A blog banner about {topic}",
76
- })
77
- # You can access the image with PIL.Image for example
78
-
79
- image = Image.open(io.BytesIO(image_bytes))
80
- image.save(f"{topic}.png")
81
- return image
82
-
83
- # Streamlit app
84
- st.title("Blog Generator")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  # Input and button
87
  topic = st.text_input("Enter Title for the blog")
88
- button_clicked = st.button("Create blog!")
89
- # Load existing ideas
90
- existing_ideas = load_ideas()
91
- st.sidebar.header("Previous Ideas:")
92
 
93
  # Display existing ideas in the sidebar
94
  keys = list(set([key for idea in existing_ideas for key in idea.keys()]))
@@ -97,21 +172,99 @@ if topic in keys:
97
  selected_idea = st.sidebar.selectbox("Select Idea", keys, key=f"selectbox{topic}", index=index)
98
  # Display content and image for the selected idea
99
  selected_idea_from_list = next((idea for idea in existing_ideas if selected_idea in idea), None)
100
- st.subheader(selected_idea)
101
- st.image(selected_idea_from_list[selected_idea]["image_path"])
102
- st.markdown(selected_idea_from_list[selected_idea]["content"])
103
  else:
104
  index = 0
105
- # Handle button click
106
- if button_clicked:
107
- # Generate content and update existing ideas
108
- content, image = generate_content(topic),generate_image(topic)
109
- if image:
110
- image_path = f"{topic}.png"
111
- existing_ideas.append({topic: {"content": content, "image_path": image_path}})
112
- save_ideas(existing_ideas)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  # Update keys and selected idea in the sidebar
114
  keys = list(set([key for idea in existing_ideas for key in idea.keys()]))
115
  selected_idea = st.sidebar.selectbox("Select Idea", keys, key=f"selectbox{topic}", index=keys.index(topic))
116
- st.image(image)
117
- st.markdown(content)
 
 
 
1
+ import streamlit as st
 
 
 
2
  from langchain.prompts import PromptTemplate
3
  import requests
4
+ from langchain.llms import HuggingFaceHub
5
+ from langchain.chains import LLMChain
6
+ import io
7
+ from PIL import Image
8
  import json
9
+ from model import create_model
10
 
11
+ api_key = st.secrets["API"]
12
+
13
+
14
+ model,tokenizer = create_model()
15
  # Load existing ideas from a file
16
  def load_ideas():
17
  try:
 
26
  with open("ideas.json", "w") as file:
27
  json.dump(ideas, file)
28
 
29
+ # Save image to a file
30
+ def save_image(image, image_path):
31
+ image.save(image_path)
32
+
33
+
34
+
35
+ # content generation
36
  def generate_content(topic):
37
+ keyword=topic
38
+ prompt = [{'role': 'user', 'content': f'''Write a comprehensive article about {keyword} covering the following aspects:
39
+ Introduction, History and Background, Key Concepts and Terminology, Use Cases and Applications, Benefits and Drawbacks, Future Outlook, Conclusion
40
+ Ensure that the article is well-structured, informative, and at least 2000 words long. Use SEO best practices for content optimization.
41
+ Add ## before section headers
42
+ '''}]
43
+ inputs = tokenizer.apply_chat_template(
44
+ prompt,
45
+ add_generation_prompt=True,
46
+ return_tensors='pt'
47
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ tokens = model.generate(
50
+ inputs.to(model.device),
51
+ max_new_tokens=10024,
52
+ temperature=0.8,
53
+ do_sample=True
54
+ )
55
+
56
+ content = tokenizer.decode(tokens[0], skip_special_tokens=False)
57
+ # print(content)
58
+ return content
59
+
60
+ def divide_content(text):
61
+ sections = {}
62
+ lines = text.split('\n')
63
+
64
+ current_section = None
65
+
66
+ for line in lines:
67
+ line = line.strip() # Remove leading and trailing whitespaces
68
+ if line.startswith("##"):
69
+ # Found a new section marker
70
+ current_section = line[2:]
71
+ sections[current_section] = ""
72
+ elif current_section is not None and line:
73
+ # Append the line to the current section if it's not empty
74
+ sections[current_section] += line + " "
75
+
76
+ # Remove trailing whitespaces from each section
77
+ for section_name, section_content in sections.items():
78
+ sections[section_name] = section_content.rstrip()
79
+
80
+ return sections
81
+
82
+
83
+ # Image Generation
84
+ API_URL = "https://api-inference.huggingface.co/models/goofyai/3d_render_style_xl"
85
+ headers = {"Authorization": f"Bearer {api_key}"}
86
+
87
+ def query(payload):
88
+ response = requests.post(API_URL, headers=headers, json=payload)
89
+ return response.content
90
+
91
+ def generat_image(image_prompt,name):
92
+ image_bytes = query({
93
+ "inputs": image_prompt,
94
+ })
95
+ image = Image.open(io.BytesIO(image_bytes))
96
+ image.save(f"{name}.png")
97
+ return image
98
+
99
+ # st.title('AI Blog Content Generator')
100
+
101
+ # st.header('What is the topic of your blog post?')
102
+ # topic_text = st.text_input('Topic:', placeholder='Example: Generative AI')
103
+ # submitted = st.button('Submit')
104
+
105
+ def display_content_with_images(blog):
106
+ # Streamlit Display
107
+ st.header(blog['title'])
108
+
109
+ # Introduction
110
+ col1, col2 = st.columns(2, gap='medium')
111
+ with col1:
112
+ st.header('Introduction')
113
+ st.write(blog['Introduction'])
114
+ with col2:
115
+ st.image(blog['introduction_image'], use_column_width=True)
116
+
117
+ # History
118
+ st.header('History and Background')
119
+ st.write(blog['History and Background'])
120
+ st.image(blog['History and Background_image'], use_column_width=True)
121
+
122
+ # Content
123
+ col1, col2 = st.columns(2, gap='medium')
124
+ with col1:
125
+ st.header('Key Concepts and Terminology')
126
+ st.write(blog['Key Concepts and Terminology'])
127
+ with col2:
128
+ st.image(blog['Key Concepts and Terminology_image'], use_column_width=True)
129
+
130
+ # Use Cases and Applications
131
+ st.header('Use Cases and Applications')
132
+ st.write(blog['Use Cases and Applications'])
133
+
134
+ # Benefits and Drawbacks
135
+ st.header('Benefits and Drawbacks')
136
+ st.write(blog['Benefits and Drawbacks'])
137
+
138
+ # Future Outlook
139
+ st.header('Future Outlook')
140
+ st.write(blog['Future Outlook'])
141
+
142
+ # Conclusion
143
+ col1, col2 = st.columns(2, gap='medium')
144
+ with col1:
145
+ st.header('Conclusion')
146
+ st.write(blog['Conclusion'])
147
+ with col2:
148
+ st.image(blog['Conclusion_image'])
149
+
150
+
151
+
152
+ # Streamlit App
153
+
154
+ # Title
155
+ st.sidebar.title('📝 Previous Ideas')
156
+ st.title("AI Blog Content Generator 😊")
157
+ # Main Page
158
+ col1, col2, col3 = st.columns((1, 3, 1), gap='large')
159
+
160
+
161
+ existing_ideas = load_ideas()
162
 
163
  # Input and button
164
  topic = st.text_input("Enter Title for the blog")
165
+ button_clicked = st.button("Create blog!❤️")
166
+
 
 
167
 
168
  # Display existing ideas in the sidebar
169
  keys = list(set([key for idea in existing_ideas for key in idea.keys()]))
 
172
  selected_idea = st.sidebar.selectbox("Select Idea", keys, key=f"selectbox{topic}", index=index)
173
  # Display content and image for the selected idea
174
  selected_idea_from_list = next((idea for idea in existing_ideas if selected_idea in idea), None)
175
+ st.subheader(topic)
176
+ display_content_with_images(selected_idea_from_list[selected_idea])
 
177
  else:
178
  index = 0
179
+
180
+ # Check if the topic exists in previous ideas before generating
181
+ if button_clicked and topic not in keys:
182
+ st.write('Generating blog post about', topic, '...')
183
+ st.write('This may take a few minutes.')
184
+
185
+ topic_query = topic
186
+
187
+ content = generate_content(topic)
188
+ # st.write(content)
189
+ blog = divide_content(content)
190
+ print(blog)
191
+ st.header(topic)
192
+ # Introduction
193
+ col1, col2 = st.columns(2, gap='medium')
194
+ with col1:
195
+ st.subheader('Introduction')
196
+ st.write(blog[' Introduction'])
197
+ with col2:
198
+ image_prompt = blog[' Introduction'].splitlines()[0]
199
+ introduction_image = generat_image(image_prompt,f" Introduction{topic}")
200
+ st.image(introduction_image, use_column_width=True)
201
+
202
+ st.divider()
203
+
204
+ # History
205
+ st.subheader('History and Background')
206
+ st.write(blog[' History and Background'])
207
+ image_prompt = blog[' History and Background'].splitlines()[0]
208
+ history_image =generat_image(image_prompt,f" History and Background{topic}")
209
+ st.image(history_image, use_column_width=True)
210
+ st.divider()
211
+
212
+ # Key Concepts and Terminology
213
+ col1, col2 = st.columns(2, gap='medium')
214
+ with col1:
215
+ st.subheader('Key Concepts and Terminology')
216
+ st.write(blog[' Key Concepts and Terminology'])
217
+ with col2:
218
+ image_prompt = blog[' Key Concepts and Terminology'].splitlines()[0]
219
+ key_concepts_image = generat_image(image_prompt,f" Key Concepts and Terminology{topic}")
220
+ st.image(key_concepts_image, use_column_width=True)
221
+ st.divider()
222
+
223
+ # Use Cases and Applications
224
+ st.subheader('Use Cases and Applications')
225
+ st.write(blog[' Use Cases and Applications'])
226
+
227
+ # Benefits and Drawbacks
228
+ st.subheader('Benefits and Drawbacks')
229
+ st.write(blog[' Benefits and Drawbacks'])
230
+
231
+ # Future Outlook
232
+ st.subheader('Future Outlook')
233
+ st.write(blog[' Future Outlook'])
234
+
235
+ # Conclusion
236
+ col1, col2 = st.columns(2, gap='medium')
237
+ with col1:
238
+ st.subheader('Conclusion')
239
+ st.write(blog[' Conclusion'])
240
+ with col2:
241
+ image_prompt = blog[' Conclusion'].splitlines()[0]
242
+ conclusion_image = generat_image(image_prompt,f" Conclusion{topic}")
243
+ st.image(conclusion_image, use_column_width=True)
244
+
245
+
246
+ # Blog Data
247
+ blog_data = {
248
+ 'title': topic,
249
+ 'Introduction': blog[' Introduction'],
250
+ 'introduction_image': f" Introduction{topic}.png",
251
+ 'History and Background': blog[' History and Background'],
252
+ 'History and Background_image': f" History and Background{topic}.png",
253
+ 'Key Concepts and Terminology': blog[' Key Concepts and Terminology'],
254
+ 'Key Concepts and Terminology_image': f" Key Concepts and Terminology{topic}.png",
255
+ 'Use Cases and Applications': blog[' Use Cases and Applications'],
256
+ 'Benefits and Drawbacks': blog[' Benefits and Drawbacks'],
257
+ 'Future Outlook': blog[' Future Outlook'],
258
+ 'Conclusion': blog[' Conclusion'],
259
+ 'Conclusion_image': f" Conclusion{topic}.png"
260
+ }
261
+
262
+ # Save blog with images
263
+ existing_ideas.append({topic: blog_data})
264
  # Update keys and selected idea in the sidebar
265
  keys = list(set([key for idea in existing_ideas for key in idea.keys()]))
266
  selected_idea = st.sidebar.selectbox("Select Idea", keys, key=f"selectbox{topic}", index=keys.index(topic))
267
+
268
+ save_ideas(existing_ideas)
269
+
270
+