File size: 11,282 Bytes
bab4b63 44f9c40 bab4b63 44f9c40 bab4b63 44f9c40 bab4b63 44f9c40 bab4b63 44f9c40 bab4b63 44f9c40 bab4b63 44f9c40 bab4b63 44f9c40 bab4b63 44f9c40 bab4b63 44f9c40 bab4b63 44f9c40 bab4b63 |
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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 |
import gradio as gr
import numpy as np
import random
import re
from io import BytesIO
import mechanicalsoup
import pandas as pd
import requests
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
from reportlab.lib.units import cm
from reportlab.platypus import (
Image,
Paragraph,
SimpleDocTemplate,
Spacer,
Table,
TableStyle,
)
from unidecode import unidecode
class PDFPoster:
def __init__(self, deputy_name: str, vote_id_list: list[str]):
self.deputy_name = deputy_name
self.vote_id_list = [f"vote_{i}" for i in vote_id_list]
def retrieve_deputy_data(self):
self.deputy_data = self.get_deputy_votes_page()
self.votes = self.get_votes_from_politic_page()
self.img_url = self.get_politic_image()
self.party = self.get_politic_party()
def generate_poster(
self,
message_1: str = "Les votes de vos députés sont souvent différents de ce que les responsables de partis annoncent dans les médias. Les données de votes sont ouvertes!",
message_2: str = "Les 30 juin, et 7 juin, renseignez vous, et votez en connaissance de cause !",
):
self.retrieve_deputy_data()
df_subset = self.votes[self.votes["vote_id"].isin(self.vote_id_list)]
pdf_filename = f"{self.deputy_name}.pdf"
document = SimpleDocTemplate(pdf_filename, pagesize=A4)
# Set up the styles
styles = getSampleStyleSheet()
title_style = styles["Title"]
title_style.alignment = TA_CENTER
subtitle_style = styles["Heading2"]
subtitle_style.alignment = TA_CENTER
subtitle_style.fontName = "Helvetica-Bold"
normal_style = styles["Normal"]
normal_style.alignment = TA_CENTER
red_style = ParagraphStyle(
"red", parent=subtitle_style, textColor=colors.red, fontSize=20
)
# Add a title
title = Paragraph(
f"Les votes de votre député sortant : {self.deputy_name}", title_style
)
subtitle = Paragraph(f"Parti : {self.party} ", subtitle_style)
source = Paragraph(f"Source : {self.deputy_data['url']}", normal_style)
after_text = Paragraph(message_1, subtitle_style)
vote_text = Paragraph(message_2, red_style)
# Add an image
# Open the image URL with BytesIO
image_response = requests.get(self.img_url)
image_bytes = BytesIO(image_response.content)
image = Image(image_bytes)
image.drawHeight = 6 * cm
image.drawWidth = 5 * cm
# Create a list of sentences
sentences = df_subset["vote_topic"].tolist()
votes = df_subset["for_or_against"].tolist()
# Create the table data
table_data = [["Sujet", "Vote"]]
for vote, sentence in zip(sentences, votes):
row = [
Paragraph(vote, normal_style),
Paragraph(sentence, normal_style),
]
table_data.append(row)
# Create the table
table = Table(table_data)
table.setStyle(
TableStyle(
[
("BACKGROUND", (0, 0), (-1, 0), colors.white),
("TEXTCOLOR", (0, 0), (-1, 0), colors.black),
("ALIGN", (0, 0), (-1, -1), "CENTER"),
("FONTNAME", (0, 0), (-1, 1), "Helvetica-Bold"),
("FONTSIZE", (0, 0), (-1, 0), 14),
("BOTTOMPADDING", (0, 0), (-1, 0), 12),
("ALIGN", (0, 1), (-1, -1), "CENTER"),
("BACKGROUND", (0, 1), (-1, -1), colors.white),
("GRID", (0, 0), (-1, -1), 1, colors.black),
]
)
)
# Function to apply conditional formatting
def apply_conditional_styles(table, data):
style = TableStyle()
for row_idx, row in enumerate(data):
for col_idx, cell in enumerate(row):
if isinstance(cell, Paragraph):
if "POUR" in cell.text:
style.add(
"BACKGROUND",
(col_idx, row_idx),
(col_idx, row_idx),
colors.green,
)
elif "CONTRE" in cell.text:
style.add(
"BACKGROUND",
(col_idx, row_idx),
(col_idx, row_idx),
colors.red,
)
elif "ABSTENTION" in cell.text:
style.add(
"BACKGROUND",
(col_idx, row_idx),
(col_idx, row_idx),
colors.beige,
)
return style
table.setStyle(apply_conditional_styles(table, table_data))
# Build the PDF
elements = [
title,
Spacer(1, 6),
subtitle,
Spacer(1, 12),
image,
Spacer(1, 12),
table,
source,
Spacer(1, 8),
after_text,
Spacer(1, 8),
vote_text,
]
document.build(elements)
def get_deputy_votes_page(self):
"""Fetches the webpage containing the voting records of a specified deputy.
Args:
politic_name (str): Name of the deputy.
Returns:
politic_dict (dict): Dictionary containing the html page, the url and the
name of the deputy."""
politic_name = unidecode(self.deputy_name.lower()).replace(" ", "-")
browser = mechanicalsoup.StatefulBrowser()
url = "https://datan.fr/deputes"
research_page = browser.open(url)
research_html = research_page.soup
politic_card = research_html.select(f'a[href*="{politic_name}"]')
if politic_card:
url_politic = politic_card[0]["href"]
politic_page = browser.open(url_politic + "/votes")
politic_html = politic_page.soup
politic_dict = {
"html_page": politic_html,
"url": url_politic,
"name": politic_name,
}
return politic_dict
else:
raise ValueError(f"Politic {politic_name} not found")
def get_votes_from_politic_page(self):
"""Extracts the voting records from the html page of a deputy.
Args:
politic_dict (dict): Dictionary containing the html page, the url and the
name of the deputy.
Returns:
df (pd.DataFrame): DataFrame containing the voting records of the deputy."""
# <div class="col-md-6 sorting-item institutions" style="position: absolute; left: 0px; top: 0px;">
politic_html = self.deputy_data["html_page"]
politic_name = self.deputy_data["name"]
vote_elements = politic_html.find_all("div", class_="card card-vote")
vote_categories = politic_html.find_all(
class_=re.compile("col-md-6 sorting-item*")
)
votes = []
for i, vote_element in enumerate(vote_elements):
for_or_against = (
vote_element.find("div", class_="d-flex align-items-center")
.text.replace("\n", "")
.strip()
)
vote_topic = (
vote_element.find("a", class_="stretched-link underline no-decoration")
.text.replace("\n", "")
.strip()
)
vote_id = (
vote_element.find("a", class_="stretched-link underline no-decoration")[
"href"
]
.split("/")[-1]
.replace("\n", "")
.strip()
)
vote_date = (
vote_element.find("span", class_="date").text.replace("\n", "").strip()
)
vote_category = vote_categories[i]["class"][-1]
# color = "green" if for_or_against == "Pour" else "red"
votes.append(
[
vote_id,
for_or_against,
vote_topic,
vote_date,
politic_name,
vote_category,
]
)
df = pd.DataFrame(
votes,
columns=[
"vote_id",
"for_or_against",
"vote_topic",
"vote_date",
"politic_name",
"vote_category",
],
)
return df
def get_politic_image(self):
"""Fetches the image of a deputy.
Args:
politic_name (str): Name of the deputy.
Returns:
image (str): URL of the image of the deputy."""
image = self.deputy_data["html_page"].find("img", alt=self.deputy_name)
image_src = image.get("src")
return image_src
def get_politic_party(self):
party = (
self.deputy_data["html_page"]
.find("div", class_="link-group text-center mt-1")
.text.replace("\n", "")
.strip()
)
return party
def infer(deputy_name, message_1, message_2):
pdfposter = PDFPoster(deputy_name)
examples = [
"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
"An astronaut riding a green horse",
"A delicious ceviche cheesecake slice",
]
css="""
#col-container {
margin: 0 auto;
max-width: 520px;
}
"""
with gr.Blocks(css=css) as demo:
with gr.Column(elem_id="col-container"):
gr.Markdown(f"""
# Réalise une affiche des votes de ton député !
""")
with gr.Row():
deputy = gr.Text(
label="deputy_name",
show_label=False,
max_lines=1,
placeholder="Nom du député, si tu ne le connais pas RDV sur www.datan.fr ou www.nosdeputes.fr",
container=False,
)
run_button = gr.Button("Run", scale=0)
result = gr.File(label="Result", show_label=True)
message_1 = gr.Text(
label="message_1",
max_lines=1,
placeholder="Les votes de vos députés sont souvent différents de ce que les responsables de partis annoncent dans les médias. Les données de votes sont ouvertes!",
visible=False,
)
message_2 = gr.Text(
label="message_2",
max_lines=1,
placeholder="Les 30 juin, et 7 juin, renseignez vous, et votez en connaissance de cause !",
visible=False,
)
run_button.click(
fn = infer,
inputs = [deputy, message_1, message_2],
outputs = [result]
)
demo.queue().launch() |