raannakasturi commited on
Commit
f9bd988
·
1 Parent(s): ea7c078

Refactor image generation and upload process, improve error handling, and add base64 padding fix

Browse files
Files changed (2) hide show
  1. image.py +59 -37
  2. post_blog.py +6 -5
image.py CHANGED
@@ -1,77 +1,99 @@
1
  import base64
2
- import os
3
- import pollinations as ai
4
- from PIL import Image
5
  import io
 
6
  import re
7
  import requests
 
 
 
 
 
8
 
9
  def extract_summary(text):
10
  text = text.replace("#", "").strip().lower()
11
- match = re.search(r"summary(.*?)highlights", text.replace("#", ""), re.DOTALL)
12
  if match:
13
- return match.group(1).replace("#", "").replace("\n", "").strip()
14
- return None
 
 
 
 
 
 
15
 
16
  def generate_image(title, summary):
17
  try:
18
  extracted_summary = extract_summary(summary)
19
- if not extracted_summary:
20
- extracted_summary = summary
21
- data = r"{}: {}".format(title.replace("{", "").replace("}","").replace("\n", ""), extracted_summary).strip().replace("&", "&").replace("{", "").replace("}","").replace("\n", "")
22
  model_obj = ai.ImageModel(
23
- model=ai.turbo,
24
  width=1280,
25
  height=720,
26
  seed=2342342340,
27
  enhance=True,
28
  nologo=True
29
  )
30
- model_obj.generate(
31
- prompt=r"{}".format(data),
32
- negative=("a bad image, low res, low quality, pixelated, blurry, bad lighting, bad angle, bad composition, bad focus, bad exposure, bad white balance, bad color, bad contrast, bad saturation, bad sharpness, bad noise, bad artifacts, bad framing, bad cropping, bad editing, bad filter, bad lens, bad camera, bad sensor, bad settings, bad post-processing, bad retouching, bad enhancement, bad manipulation, bad distortion, bad watermark, bad logo, bad text, bad overlay, bad background"),
33
  save=True,
34
  file="image.png"
35
  )
36
- with open("image.png", "rb") as image_file:
37
- image_data = image_file.read()
38
- base64_encoded = base64.b64encode(image_data).decode('utf-8')
39
- data_uri = f"data:image/png;base64,{base64_encoded}"
40
- return r"{}".format(data_uri).strip()
 
 
 
 
41
  except Exception as e:
42
- return f"An error occurred: {e}"
 
43
 
44
  def verify_image(image_data):
45
  try:
46
  image_stream = io.BytesIO(image_data)
47
- image = Image.open(image_stream)
48
- image.verify()
49
- image_stream.seek(0)
50
- image = Image.open(image_stream)
51
  return True
52
  except Exception as e:
53
  print(f"Error verifying image: {e}")
54
  return False
55
 
56
  def upload_image(data_uri, api_key):
 
57
  try:
58
- base64_image = data_uri.split(",")[1]
59
- url = f'https://api.imgbb.com/1/upload?key={api_key}'
60
- response = requests.post(url, data={'image': base64_image}).json()
61
- if response.get('status') == 200:
62
- return response['data']['url']
63
  else:
64
- return "https://i.ibb.co/qdC1nSx/landscape-placeholder-e1608289113759.png"
 
65
  except Exception as e:
66
  print(f"Error uploading image: {e}")
67
- return "https://i.ibb.co/qdC1nSx/landscape-placeholder-e1608289113759.png"
 
 
68
 
69
  def fetch_image(title, summary, api_key):
70
  image_url = "https://i.ibb.co/qdC1nSx/landscape-placeholder-e1608289113759.png"
71
- data_uri = generate_image(title, summary)
72
- image_data = base64.b64decode(data_uri.split(",")[1])
73
- if verify_image(image_data):
74
- image_url = upload_image(data_uri, api_key)
75
- os.remove("image.png")
76
- return image_url
77
-
 
 
 
 
 
 
 
 
 
1
  import base64
 
 
 
2
  import io
3
+ import os
4
  import re
5
  import requests
6
+ import dotenv
7
+ from PIL import Image
8
+ import pollinations as ai
9
+
10
+ dotenv.load_dotenv()
11
 
12
  def extract_summary(text):
13
  text = text.replace("#", "").strip().lower()
14
+ match = re.search(r"summary(.*?)highlights", text, re.DOTALL)
15
  if match:
16
+ return match.group(1).strip()
17
+ return text
18
+
19
+ def fix_base64_padding(data):
20
+ missing_padding = len(data) % 4
21
+ if missing_padding:
22
+ data += "=" * (4 - missing_padding)
23
+ return data
24
 
25
  def generate_image(title, summary):
26
  try:
27
  extracted_summary = extract_summary(summary)
28
+ prompt = f"{title.strip()}: {extracted_summary.strip()}"
 
 
29
  model_obj = ai.ImageModel(
30
+ model=ai.flux_pro,
31
  width=1280,
32
  height=720,
33
  seed=2342342340,
34
  enhance=True,
35
  nologo=True
36
  )
37
+ image = model_obj.generate(
38
+ prompt=prompt,
39
+ negative="low quality, blurry, pixelated",
40
  save=True,
41
  file="image.png"
42
  )
43
+ if type(image) == str:
44
+ print(f"An error occurred during image generation: {image}")
45
+ return None
46
+ image_url = image.params.get("url")
47
+ if image_url:
48
+ img_data = requests.get(image_url).content
49
+ base64_encoded = base64.b64encode(img_data).decode("utf-8")
50
+ return f"data:image/png;base64,{base64_encoded}"
51
+ return None
52
  except Exception as e:
53
+ print(f"An error occurred during image generation: {e}")
54
+ return None
55
 
56
  def verify_image(image_data):
57
  try:
58
  image_stream = io.BytesIO(image_data)
59
+ img = Image.open(image_stream)
60
+ img.verify()
 
 
61
  return True
62
  except Exception as e:
63
  print(f"Error verifying image: {e}")
64
  return False
65
 
66
  def upload_image(data_uri, api_key):
67
+ image_url = "https://i.ibb.co/qdC1nSx/landscape-placeholder-e1608289113759.png"
68
  try:
69
+ base64_image = fix_base64_padding(data_uri.split(",")[1])
70
+ url = f"https://api.imgbb.com/1/upload?key={api_key}"
71
+ response = requests.post(url, data={"image": base64_image}).json()
72
+ if response.get("status") == 200:
73
+ image_url = response["data"]["display_url"]
74
  else:
75
+ print(f"Error uploading image: {response}")
76
+ image_url = "https://i.ibb.co/qdC1nSx/landscape-placeholder-e1608289113759.png"
77
  except Exception as e:
78
  print(f"Error uploading image: {e}")
79
+ image_url = "https://i.ibb.co/qdC1nSx/landscape-placeholder-e1608289113759.png"
80
+ finally:
81
+ return image_url
82
 
83
  def fetch_image(title, summary, api_key):
84
  image_url = "https://i.ibb.co/qdC1nSx/landscape-placeholder-e1608289113759.png"
85
+ try:
86
+ data_uri = generate_image(title, summary)
87
+ if data_uri:
88
+ base64_image = fix_base64_padding(data_uri.split(",")[1])
89
+ image_data = base64.b64decode(base64_image)
90
+ if verify_image(image_data):
91
+ image_url = upload_image(data_uri, api_key)
92
+ else:
93
+ image_url = "https://i.ibb.co/qdC1nSx/landscape-placeholder-e1608289113759.png"
94
+ except Exception as e:
95
+ print(f"Error fetching image: {e}")
96
+ image_url = "https://i.ibb.co/qdC1nSx/landscape-placeholder-e1608289113759.png"
97
+ finally:
98
+ os.remove("image.png")
99
+ return image_url
post_blog.py CHANGED
@@ -12,13 +12,14 @@ 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 generate_post_html(title, summary, mindmap, citation):
17
  title = title.replace("{", r'{').replace("}", r'}')
18
  summary = summary.replace("{", r'{').replace("}", r'}')
19
  mindmap = mindmap.replace("{", r'{').replace("}", r'}')
20
  citation = citation.replace("{", r'{').replace("}", r'}')
21
- image = fetch_image(title, summary, os.getenv('IMGBB_API_KEY'))
22
  html_summary = mistune.html(summary)
23
  post = f"""
24
  <div>
@@ -105,9 +106,9 @@ def post_blog(title, category, summary, mindmap, citation, uaccess_key, wait_tim
105
  else:
106
  status = True
107
  post_title, post_category, post_body, post_image = create_post(title, category, summary, mindmap, citation)
108
- status = post_post(post_title, post_category, post_body, post_image)
109
  print(f"Waiting for {wait_time*60} seconds...")
110
- time.sleep(wait_time*60)
111
  if status:
112
  print('Post created successfully')
113
  return True
@@ -122,10 +123,10 @@ def test(access_key):
122
  "2412.16344": {
123
  "id": "2412.16344",
124
  "doi": "https://doi.org/10.48550/arXiv.2412.16344",
125
- "title": "Analytic 3D vector non-uniform Fourier crystal optics in arbitrary $\bar{\bar{\varepsilon}}$ dielectric",
126
  "category": "Astrophysics",
127
  "citation": "Grant, C. E., Bautz, M. W., Miller, E. D., Foster, R. F., LaMarr, B., Malonis, A., Prigozhin, G., Schneider, B., Leitz, C., &amp; Falcone, A. D. (2024). Focal Plane of the Arcus Probe X-Ray Spectrograph. ArXiv. https://doi.org/10.48550/ARXIV.2412.16344",
128
- "summary": "## Summary\nThe Arcus Probe mission concept provides high-resolution soft X-ray and UV spectroscopy to study the universe. The X-ray Spectrograph (XRS) uses two CCD focal planes to detect and record X-ray photons. Laboratory performance results meet observatory requirements.\n\n## Highlights\n- The Arcus Probe mission concept explores the formation and evolution of clusters, galaxies, and stars.\n- The XRS instrument includes four parallel optical channels and two detector focal plane arrays.\n- The CCDs are designed and manufactured by MIT Lincoln Laboratory (MIT/LL).\n- The XRS focal plane utilizes high heritage MIT/LL CCDs with proven technologies.\n- Laboratory testing confirms CCID-94 performance meets required spectral resolution and readout noise.\n- The Arcus mission includes two co-aligned instruments working simultaneously.\n- The XRS Instrument Control Unit (XICU) controls the activities of the XRS.\n\n## Key Insights\n- The Arcus Probe mission concept provides a significant improvement in sensitivity and resolution over previous missions, enabling breakthrough science in understanding the universe.\n- The XRS instrument's design, including the use of two CCD focal planes and four parallel optical channels, allows for high-resolution spectroscopy and efficient detection of X-ray photons.\n- The CCDs used in the XRS instrument are designed and manufactured by MIT Lincoln Laboratory (MIT/LL), which has a proven track record of producing high-quality CCDs for space missions.\n- The laboratory performance results of the CCID-94 device demonstrate that it meets the required spectral resolution and readout noise for the Arcus mission, indicating that the instrument is capable of achieving its scientific goals.\n- The XRS Instrument Control Unit (XICU) plays a crucial role in controlling the activities of the XRS, including gathering and storing data, and processing event recognition.\n- The Arcus mission's use of two co-aligned instruments working simultaneously allows for a wide range of scientific investigations, including the study of time-domain science and the physics of time-dependent phenomena.\n- The high heritage MIT/LL CCDs used in the XRS focal plane provide a reliable and efficient means of detecting X-ray photons, enabling the instrument to achieve its scientific goals.",
129
  "mindmap": "## Arcus Probe Mission Concept\n- Explores formation and evolution of clusters, galaxies, stars\n- High-resolution soft X-ray and UV spectroscopy\n- Agile response capability for time-domain science\n\n## X-Ray Spectrograph (XRS) Instrument\n- Two nearly identical CCD focal planes\n- Detects and records X-ray photons from dispersed spectra\n- Zero-order of critical angle transmission gratings\n\n## XRS Focal Plane Characteristics\n- Frametransfer X-ray CCDs\n- 8-CCD array per Detector Assembly\n- FWHM < 70 eV @ 0.5 keV\n- System read noise ≤ 4 e- RMS @ 625 kpixels/sec\n\n## Detector Assembly\n- Eight CCDs in a linear array\n- Tilted to match curved focal surface\n- Gaps minimized between CCDs\n- Alignment optimized with XRS optics\n\n## Detector Electronics\n- Programmable analog clock waveforms and biases\n- Low-noise analog signal processing and digitization\n- 1 second frame time for negligible pileup\n\n## XRS Instrument Control Unit (XICU)\n- Controls XRS activities and data transfer\n- Event Recognition Processor (ERP) extracts X-ray events\n- Reduces data rate by many orders of magnitude\n\n## CCD X-Ray Performance\n- Measured readout noise 2-3 e- RMS\n- Spectral resolution meets Arcus requirements\n- FWHM < 70 eV at 0.5 keV\n\n## CCID-94 Characteristics\n- Back-illuminated frame-transfer CCDs\n- 2048 × 1024 pixel imaging array\n- 24 × 24 µm image area pixel size\n- 50 µm detector thickness\n\n## Contamination Blocking Filter (CBF)\n- Protects detectors from molecular contamination\n- 45 nm polyimide + 30 nm Al\n- Maintained above +20°C by heater control\n\n## Optical Blocking Filter (OBF)\n- Attenuates visible/IR stray light\n- 40 nm Al on-chip filter\n- Works in conjunction with CBF"
130
  }
131
  }
 
12
  client_secret = os.getenv('CLIENT_SECRET')
13
  refresh_token = os.getenv('REFRESH_TOKEN')
14
  blog_id = os.getenv('BLOG_ID')
15
+ imgbb_api_key = os.getenv('IMGBB_API_KEY')
16
 
17
  def generate_post_html(title, summary, mindmap, citation):
18
  title = title.replace("{", r'{').replace("}", r'}')
19
  summary = summary.replace("{", r'{').replace("}", r'}')
20
  mindmap = mindmap.replace("{", r'{').replace("}", r'}')
21
  citation = citation.replace("{", r'{').replace("}", r'}')
22
+ image = fetch_image(title, summary, imgbb_api_key)
23
  html_summary = mistune.html(summary)
24
  post = f"""
25
  <div>
 
106
  else:
107
  status = True
108
  post_title, post_category, post_body, post_image = create_post(title, category, summary, mindmap, citation)
109
+ # status = post_post(post_title, post_category, post_body, post_image)
110
  print(f"Waiting for {wait_time*60} seconds...")
111
+ # time.sleep(wait_time*60)
112
  if status:
113
  print('Post created successfully')
114
  return True
 
123
  "2412.16344": {
124
  "id": "2412.16344",
125
  "doi": "https://doi.org/10.48550/arXiv.2412.16344",
126
+ "title": "Gravitational algebras and applications to nonequilibrium physics",
127
  "category": "Astrophysics",
128
  "citation": "Grant, C. E., Bautz, M. W., Miller, E. D., Foster, R. F., LaMarr, B., Malonis, A., Prigozhin, G., Schneider, B., Leitz, C., &amp; Falcone, A. D. (2024). Focal Plane of the Arcus Probe X-Ray Spectrograph. ArXiv. https://doi.org/10.48550/ARXIV.2412.16344",
129
+ "summary": "## Summary\nThe text discusses gravitational algebras and their applications in nonequilibrium physics, specifically in the context of black holes and de Sitter spacetime. It explores the concept of type III and type II von Neumann algebras and their role in understanding the thermodynamic properties of gravitational systems.\n\n## Highlights\n- The Arcus Probe mission concept explores the formation and evolution of clusters, galaxies, and stars.\n- The XRS instrument includes four parallel optical channels and two detector focal plane arrays.\n- The CCDs are designed and manufactured by MIT Lincoln Laboratory (MIT/LL).\n- The XRS focal plane utilizes high heritage MIT/LL CCDs with proven technologies.\n- Laboratory testing confirms CCID-94 performance meets required spectral resolution and readout noise.\n- The Arcus mission includes two co-aligned instruments working simultaneously.\n- The XRS Instrument Control Unit (XICU) controls the activities of the XRS.\n\n## Key Insights\n- The Arcus Probe mission concept provides a significant improvement in sensitivity and resolution over previous missions, enabling breakthrough science in understanding the universe.\n- The XRS instrument's design, including the use of two CCD focal planes and four parallel optical channels, allows for high-resolution spectroscopy and efficient detection of X-ray photons.\n- The CCDs used in the XRS instrument are designed and manufactured by MIT Lincoln Laboratory (MIT/LL), which has a proven track record of producing high-quality CCDs for space missions.\n- The laboratory performance results of the CCID-94 device demonstrate that it meets the required spectral resolution and readout noise for the Arcus mission, indicating that the instrument is capable of achieving its scientific goals.\n- The XRS Instrument Control Unit (XICU) plays a crucial role in controlling the activities of the XRS, including gathering and storing data, and processing event recognition.\n- The Arcus mission's use of two co-aligned instruments working simultaneously allows for a wide range of scientific investigations, including the study of time-domain science and the physics of time-dependent phenomena.\n- The high heritage MIT/LL CCDs used in the XRS focal plane provide a reliable and efficient means of detecting X-ray photons, enabling the instrument to achieve its scientific goals.",
130
  "mindmap": "## Arcus Probe Mission Concept\n- Explores formation and evolution of clusters, galaxies, stars\n- High-resolution soft X-ray and UV spectroscopy\n- Agile response capability for time-domain science\n\n## X-Ray Spectrograph (XRS) Instrument\n- Two nearly identical CCD focal planes\n- Detects and records X-ray photons from dispersed spectra\n- Zero-order of critical angle transmission gratings\n\n## XRS Focal Plane Characteristics\n- Frametransfer X-ray CCDs\n- 8-CCD array per Detector Assembly\n- FWHM < 70 eV @ 0.5 keV\n- System read noise ≤ 4 e- RMS @ 625 kpixels/sec\n\n## Detector Assembly\n- Eight CCDs in a linear array\n- Tilted to match curved focal surface\n- Gaps minimized between CCDs\n- Alignment optimized with XRS optics\n\n## Detector Electronics\n- Programmable analog clock waveforms and biases\n- Low-noise analog signal processing and digitization\n- 1 second frame time for negligible pileup\n\n## XRS Instrument Control Unit (XICU)\n- Controls XRS activities and data transfer\n- Event Recognition Processor (ERP) extracts X-ray events\n- Reduces data rate by many orders of magnitude\n\n## CCD X-Ray Performance\n- Measured readout noise 2-3 e- RMS\n- Spectral resolution meets Arcus requirements\n- FWHM < 70 eV at 0.5 keV\n\n## CCID-94 Characteristics\n- Back-illuminated frame-transfer CCDs\n- 2048 × 1024 pixel imaging array\n- 24 × 24 µm image area pixel size\n- 50 µm detector thickness\n\n## Contamination Blocking Filter (CBF)\n- Protects detectors from molecular contamination\n- 45 nm polyimide + 30 nm Al\n- Maintained above +20°C by heater control\n\n## Optical Blocking Filter (OBF)\n- Attenuates visible/IR stray light\n- 40 nm Al on-chip filter\n- Works in conjunction with CBF"
131
  }
132
  }