Abbas0786 commited on
Commit
f9db5a1
·
verified ·
1 Parent(s): 1effa6b
Files changed (1) hide show
  1. app.py +186 -0
app.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ from datetime import datetime
4
+ from newspaper import Article
5
+ from groq import Groq
6
+ from diffusers import DiffusionPipeline
7
+ from IPython.display import display
8
+
9
+ # Your News API key and Groq API setup
10
+ API_KEY = '446dc1fa183e4e859a7fb0daf64a6f2c'
11
+ BASE_URL = 'https://newsapi.org/v2/everything'
12
+ client = Groq(api_key="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")
13
+
14
+ # Function to fetch news based on topic
15
+ def get_news_by_topic(topic):
16
+ params = {
17
+ 'q': topic,
18
+ 'apiKey': API_KEY,
19
+ 'language': 'en',
20
+ 'sortBy': 'publishedAt',
21
+ 'pageSize': 5
22
+ }
23
+
24
+ response = requests.get(BASE_URL, params=params)
25
+ news_list = []
26
+
27
+ if response.status_code == 200:
28
+ data = response.json()
29
+
30
+ if 'articles' in data:
31
+ for article in data['articles']:
32
+ title = article['title']
33
+ description = article['description']
34
+ published_at = article['publishedAt']
35
+ content = article.get('content', 'No full content available.')
36
+ url = article['url']
37
+
38
+ published_at = datetime.strptime(published_at, '%Y-%m-%dT%H:%M:%SZ')
39
+ formatted_time = published_at.strftime('%Y-%m-%d %H:%M:%S')
40
+
41
+ article_data = {
42
+ 'title': title,
43
+ 'description': description,
44
+ 'publishedAt': formatted_time,
45
+ 'content': content,
46
+ 'url': url
47
+ }
48
+
49
+ news_list.append(article_data)
50
+
51
+ return news_list
52
+
53
+ # Function to fetch full article using Newspaper
54
+ def fetch_full_article_with_newspaper(url):
55
+ try:
56
+ article = Article(url)
57
+ article.download()
58
+ article.parse()
59
+ return article.text
60
+ except Exception as e:
61
+ return f"Error occurred during parsing: {str(e)}"
62
+
63
+ # Function to summarize an article using Groq's Llama 3 model
64
+ def summarize_article(client, article_content, tone):
65
+ prompt = f"""
66
+ You are a professional News Summarizer.
67
+ Your task is to summarize the provided news article while retaining all key details.
68
+ Adjust the tone and style of the summary based on the user input (e.g., "formal," "conversational," or "humorous").
69
+
70
+ # News Article:
71
+ {article_content}
72
+
73
+ # Tone/Style:
74
+ {tone}
75
+
76
+ Remove unwanted sentences in summary like "article not found" or anything unrelated to the user query.
77
+ """
78
+
79
+ try:
80
+ chat_completion = client.chat.completions.create(
81
+ messages=[{"role": "user", "content": prompt}],
82
+ model="llama-3.1-8b-instant"
83
+ )
84
+
85
+ summary = chat_completion.choices[0].message.content.strip()
86
+ return summary
87
+ except Exception as e:
88
+ return f"An error occurred: {e}"
89
+
90
+ # Function to generate social media post content
91
+ def generate_social_media_post(summary, tone):
92
+ prompt = f"""
93
+ You are a professional social media content creator.
94
+ Your task is to create an engaging text post based on the provided news article summary while retaining all key details.
95
+ Ensure the tone matches the specified style provided.
96
+
97
+ News Article:
98
+ {summary}
99
+
100
+ Provide the text post below:
101
+ """
102
+
103
+ try:
104
+ chat_completion = client.chat.completions.create(
105
+ messages=[{"role": "user", "content": prompt}],
106
+ model="llama-3.1-8b-instant"
107
+ )
108
+
109
+ social_media_post = chat_completion.choices[0].message.content.strip()
110
+ return social_media_post
111
+ except Exception as e:
112
+ return f"Error occurred while generating the post: {e}"
113
+
114
+ # Generate an image from news summary description using Stable Diffusion
115
+ def generate_image_from_description(description):
116
+ # Load the DiffusionPipeline for Stable Diffusion from the diffusers library
117
+ generator = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5")
118
+ generator.to("cuda")
119
+
120
+ # Generate the image
121
+ image = generator(description).images[0]
122
+ return image
123
+
124
+ # Streamlit UI
125
+ def main():
126
+ st.title("News Summarizer and Social Media Post Generator")
127
+ st.subheader("Generate a social media post based on the latest news summary")
128
+
129
+ # Input fields for topic and tone
130
+ topic = st.text_input("Enter the topic you want news for:")
131
+ tone = st.selectbox("Select the tone of the summary:", ["formal", "conversational", "humorous"])
132
+
133
+ if st.button("Generate Social Media Post"):
134
+ if topic:
135
+ st.write(f"Fetching news about: {topic} in {tone} tone...")
136
+
137
+ # Fetch the latest news based on the topic
138
+ news_data = get_news_by_topic(topic)
139
+
140
+ if news_data:
141
+ combined_content = ""
142
+ for article in news_data:
143
+ article_content = fetch_full_article_with_newspaper(article['url'])
144
+ summary = summarize_article(client, article_content, tone)
145
+ combined_content += summary
146
+
147
+ # Generate the enhanced description for image generation
148
+ enhanced_prompt = f"""
149
+ You are a professional artist. Given the following news summary, create a detailed and vivid description that can be used to generate an image:
150
+ {combined_content}
151
+
152
+ The description should capture the mood, setting, actions, and emotions in a way that a model can visually interpret. Include details such as time of day, character appearance, atmosphere, and background elements.
153
+ """
154
+
155
+ chat_completion = client.chat.completions.create(
156
+ messages=[{"role": "user", "content": enhanced_prompt}],
157
+ model="llama3-8b-8192"
158
+ )
159
+
160
+ enhanced_description = chat_completion.choices[0].message.content
161
+ st.write("### Enhanced Description for Image Generation:")
162
+ st.write(enhanced_description)
163
+
164
+ # Generate an image based on the enhanced description
165
+ image = generate_image_from_description(enhanced_description)
166
+
167
+ # Display the generated image
168
+ st.image(image, caption="Generated Image based on News Summary")
169
+
170
+ # Generate a social media post based on the summary
171
+ social_media_post = generate_social_media_post(combined_content, tone)
172
+
173
+ st.write("### Generated Social Media Post:")
174
+ st.write(social_media_post)
175
+
176
+ # Allow user to download the post as a text file
177
+ post_filename = f"news_summary_{topic.replace(' ', '_')}.txt"
178
+ st.download_button("Download Post as Text File", data=social_media_post, file_name=post_filename)
179
+
180
+ else:
181
+ st.write("No news articles found for this topic.")
182
+ else:
183
+ st.write("Please enter a topic to search for news.")
184
+
185
+ if __name__ == "__main__":
186
+ main()