raannakasturi commited on
Commit
e73bcbd
·
1 Parent(s): 0f87374

Refactor post_blog.py to improve image handling and update OAuth credentials management

Browse files
Files changed (3) hide show
  1. get_refresh_token.py +30 -0
  2. main.py +0 -1
  3. post_blog.py +32 -23
get_refresh_token.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import httplib2
2
+ from oauth2client.client import flow_from_clientsecrets
3
+ from oauth2client.file import Storage
4
+ from oauth2client.tools import run_flow
5
+ from googleapiclient import discovery
6
+
7
+ # Start the OAuth flow to retrieve credentials
8
+ def authorize_credentials():
9
+ CLIENT_SECRET = 'client_secret_6.json'
10
+ SCOPE = 'https://www.googleapis.com/auth/blogger'
11
+ STORAGE = Storage('credentials.storage.json')
12
+ credentials = STORAGE.get()
13
+ if credentials is None or credentials.invalid:
14
+ flow = flow_from_clientsecrets(CLIENT_SECRET, scope=SCOPE)
15
+ http = httplib2.Http()
16
+ credentials = run_flow(flow, STORAGE, http=http)
17
+ return credentials
18
+
19
+ def getBloggerService():
20
+ credentials = authorize_credentials()
21
+ http = credentials.authorize(httplib2.Http())
22
+ discoveryUrl = ('https://blogger.googleapis.com/$discovery/rest?version=v3')
23
+ service = discovery.build('blogger', 'v3', http=http, discoveryServiceUrl=discoveryUrl)
24
+ return service
25
+
26
+ if __name__ == '__main__':
27
+ try:
28
+ getBloggerService()
29
+ except Exception as e:
30
+ print(str(e))
main.py CHANGED
@@ -8,7 +8,6 @@ from post_blog import post_blog
8
  # Load environment variables
9
  dotenv.load_dotenv()
10
  summarizer_api_key = os.getenv("SUMMARIZER_API_KEY")
11
- mail_api = os.getenv("MAIL_API")
12
  access_key = os.getenv("ACCESS_KEY")
13
 
14
  def paper_data(paper_data):
 
8
  # Load environment variables
9
  dotenv.load_dotenv()
10
  summarizer_api_key = os.getenv("SUMMARIZER_API_KEY")
 
11
  access_key = os.getenv("ACCESS_KEY")
12
 
13
  def paper_data(paper_data):
post_blog.py CHANGED
@@ -8,27 +8,24 @@ import mistune
8
 
9
  dotenv.load_dotenv()
10
  access_key = os.getenv('ACCESS_KEY')
11
- client_id = os.getenv('CLIENT_ID')
12
- client_secret = os.getenv('CLIENT_SECRET')
13
- refresh_token = os.getenv('REFRESH_TOKEN')
14
  blog_id = os.getenv('BLOG_ID')
15
 
16
  def extract_summary(text):
17
- match = re.search(r"Summary\n(.*?)\nHighlights", text, re.DOTALL)
 
18
  if match:
19
  return match.group(1).replace("#", "").replace("\n", "").strip()
20
  return None
21
 
22
  def generate_image(title, summary, category):
23
  extracted_summary = extract_summary(summary)
24
- print(extracted_summary)
 
25
  url = f"https://image.pollinations.ai/prompt/(({category}))%20{title}%20%3A%20{extracted_summary}?width=1280&height=720&seed=623862700&nologo=true&model=turbo"
26
- data = requests.get(url).content
27
- with open("image.png", "wb") as file:
28
- file.write(data)
29
- encoded_image = base64.b64encode(data)
30
- image = f"data:image/png;base64,{encoded_image.decode('utf-8')}"
31
- return image
32
 
33
  def generate_post_html(title, summary, mindmap, category, citation):
34
  image = generate_image(title, summary, category)
@@ -67,7 +64,7 @@ def generate_post_html(title, summary, mindmap, category, citation):
67
  </p>
68
  </div>
69
  """
70
- return post
71
 
72
  def sanitize_citation(citation):
73
  pattern = r"(https://doi\.org/\S+)"
@@ -82,18 +79,18 @@ def sanitize_citation(citation):
82
  def create_post(title, category, summary, mindmap, citation):
83
  post_title = f"{title}"
84
  post_category = f"{category}"
85
- post_body = generate_post_html(title, summary, mindmap, category, sanitize_citation(citation))
86
- return post_title, post_category, post_body
87
 
88
- def post_post(title, category, body):
89
  try:
90
  data = requests.post(
91
  url='https://oauth2.googleapis.com/token',
92
  data={
93
  'grant_type': 'refresh_token',
94
- 'client_secret': client_secret,
95
- 'refresh_token': refresh_token,
96
- 'client_id': client_id,
97
  },
98
  ).json()
99
  url = f"https://blogger.googleapis.com/v3/blogs/{blog_id}/posts"
@@ -106,14 +103,21 @@ def post_post(title, category, body):
106
  "blog": {
107
  "id": blog_id
108
  },
 
 
 
 
 
109
  "title": title,
110
  "content": body,
111
  "labels": [category, "recent"]
112
  }
113
  data = requests.post(url, headers=headers, json=post_data).json()
114
- print(data)
115
- time.sleep(2 * 60)
116
- return True
 
 
117
  except Exception as e:
118
  print('An error occurred:', str(e))
119
  return False
@@ -122,8 +126,13 @@ def post_blog(title, category, summary, mindmap, citation, uaccess_key):
122
  if uaccess_key != access_key:
123
  return False
124
  try:
125
- post_title, post_category, post_body = create_post(title, category, summary, mindmap, citation)
126
- status = post_post(post_title, post_category, post_body)
 
 
 
 
 
127
  if status:
128
  print('Post created successfully')
129
  return True
 
8
 
9
  dotenv.load_dotenv()
10
  access_key = os.getenv('ACCESS_KEY')
11
+ client_id = os.getenv('CLIENT_ID_1')
12
+ client_secret = os.getenv('CLIENT_SECRET_1')
13
+ refresh_token = os.getenv('REFRESH_TOKEN_1')
14
  blog_id = os.getenv('BLOG_ID')
15
 
16
  def extract_summary(text):
17
+ text = text.replace("#", "").strip().lower()
18
+ match = re.search(r"summary(.*?)highlights", text.replace("#", ""), re.DOTALL)
19
  if match:
20
  return match.group(1).replace("#", "").replace("\n", "").strip()
21
  return None
22
 
23
  def generate_image(title, summary, category):
24
  extracted_summary = extract_summary(summary)
25
+ if extracted_summary is None:
26
+ extracted_summary = title
27
  url = f"https://image.pollinations.ai/prompt/(({category}))%20{title}%20%3A%20{extracted_summary}?width=1280&height=720&seed=623862700&nologo=true&model=turbo"
28
+ return url
 
 
 
 
 
29
 
30
  def generate_post_html(title, summary, mindmap, category, citation):
31
  image = generate_image(title, summary, category)
 
64
  </p>
65
  </div>
66
  """
67
+ return post, image
68
 
69
  def sanitize_citation(citation):
70
  pattern = r"(https://doi\.org/\S+)"
 
79
  def create_post(title, category, summary, mindmap, citation):
80
  post_title = f"{title}"
81
  post_category = f"{category}"
82
+ post_body, post_image = generate_post_html(title, summary, mindmap, category, sanitize_citation(citation))
83
+ return post_title, post_category, post_body, post_image
84
 
85
+ def post_post(title, category, body, image, i):
86
  try:
87
  data = requests.post(
88
  url='https://oauth2.googleapis.com/token',
89
  data={
90
  'grant_type': 'refresh_token',
91
+ 'client_secret': os.getenv(f'CLIENT_SECRET_{i}'),
92
+ 'refresh_token': os.getenv(f'REFRESH_TOKEN_{i}'),
93
+ 'client_id': os.getenv(f'CLIENT_ID_{i}'),
94
  },
95
  ).json()
96
  url = f"https://blogger.googleapis.com/v3/blogs/{blog_id}/posts"
 
103
  "blog": {
104
  "id": blog_id
105
  },
106
+ "images": [
107
+ {
108
+ "url": image
109
+ }
110
+ ],
111
  "title": title,
112
  "content": body,
113
  "labels": [category, "recent"]
114
  }
115
  data = requests.post(url, headers=headers, json=post_data).json()
116
+ print(data['status'])
117
+ if data['status'] == 'LIVE':
118
+ return True
119
+ else:
120
+ return False
121
  except Exception as e:
122
  print('An error occurred:', str(e))
123
  return False
 
126
  if uaccess_key != access_key:
127
  return False
128
  try:
129
+ post_title, post_category, post_body, post_image = create_post(title, category, summary, mindmap, citation)
130
+ i = 1
131
+ status = False
132
+ while (i <= 6 and not status):
133
+ print(f'Posting... Tries: {i}')
134
+ status = post_post(post_title, post_category, post_body, post_image, i)
135
+ i += 1
136
  if status:
137
  print('Post created successfully')
138
  return True