Skip to content

Commit

Permalink
generator related changes + refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
birgovanandrei committed Oct 23, 2022
1 parent 3845052 commit 80a3cef
Show file tree
Hide file tree
Showing 15 changed files with 161 additions and 473 deletions.
5 changes: 3 additions & 2 deletions conf/api.conf
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
[Wine Info]
url = https://coop-dev.test.apimanagement.eu20.hana.ondemand.com/AZT-WeinattributeCAH-1/findByCodes
api_key = QPpI9dqbAYy0GGfGUCUQFbcD8TG25y5t
info_url=https://coop-dev.test.apimanagement.eu20.hana.ondemand.com/AZT-WeinattributeCAH-1/findByCodes
barcode_url=https://coop-dev.test.apimanagement.eu20.hana.ondemand.com/getProductByGTIN/AVE-PIMGetProduct-5
api_key=QPpI9dqbAYy0GGfGUCUQFbcD8TG25y5t
37 changes: 28 additions & 9 deletions coop_challenge/fetcher.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Fetcher module, this is where all the data fetch from Wine API happens
"""
import os

import requests
import configparser
Expand All @@ -13,18 +14,37 @@ class Fetcher:
def __init__(self) -> None:
# read api configuration (secret)
self.api_conf = configparser.RawConfigParser()
self.api_conf.read("../conf/api.conf")

ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
self.api_conf.read(f"{ROOT_DIR}/conf/api.conf")
api_details = dict(self.api_conf.items("Wine Info"))

self.url = api_details['url']
self.info_url = api_details['info_url']
self.barcode_url = api_details["barcode_url"]
self.api_key = api_details['api_key']

# read keys configuration for label and info sheet
self.keys_conf = configparser.RawConfigParser()
self.keys_conf.read("../conf/keys.conf")
self.keys_conf.read(f"{ROOT_DIR}/conf/keys.conf")
self.label_keys = ast.literal_eval(self.keys_conf.get("Keys", "label"))

def find_article_id_by_barcode(self, barcode: str) -> str:
return self.find_by_barcode(barcode=barcode)["code"]

def find_by_barcode(self, barcode: str) -> Dict:
"""
Fetch wine brief by a barcode
"""

params = {"lang": "de", "gtin": barcode}
headers = {"APIKey": self.api_key}

response = requests.get(
self.barcode_url,
params=params,
headers=headers
)

return response.json()

def find_for_labels(self, article_ids: List[str]) -> List[Dict]:
return self.find_by_article_ids(article_ids, self.label_keys)

Expand All @@ -37,7 +57,7 @@ def find_by_article_ids(self, article_ids: List[str], keys: List[str] = None) ->
headers = {"APIKey": self.api_key}

response = requests.get(
self.url,
self.info_url,
params=params,
headers=headers
)
Expand All @@ -50,7 +70,6 @@ def find_by_article_ids(self, article_ids: List[str], keys: List[str] = None) ->
return [{key: product[key] for key in keys} for product in products]


def fetchData(article_id):
if __name__ == "__main__":
fetcher = Fetcher()
items = fetcher.find_for_labels(article_ids=[article_id])
return items[0]
print(fetcher.find_article_id_by_barcode("3760126362587"))
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,32 @@
import os
from fpdf import FPDF

ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
pdf_output_filename = "info.pdf"
pdf_output_folder_path = f"{ROOT_DIR}/output/"
pdf_output_file_path = f"{ROOT_DIR}/output/{pdf_output_filename}"

if not os.path.exists(pdf_output_folder_path):
os.makedirs(pdf_output_file_path)


class InfoDoc(FPDF):

def __init__(self, data):
super().__init__()
self.add_page()
self.data = data['products'][0]
self.pdf_w=210
self.pdf_h=297
self.data = data
self.pdf_w = 210
self.pdf_h = 297
self.margin = 15
self.rec_width = 70
self.avail_width = 140
self.logo_width = self.avail_width - 2 * self.margin
self.logo_height = self.logo_width//3
self.logo_height = self.logo_width // 3
self.set_text_color(0)
self.set_auto_page_break(auto = False, margin = 0.0)
self.set_auto_page_break(auto=False, margin=0.0)
self.set_margins(left=0, top=0, right=0)
self.set_font("Arial", style = '', size = 12)
self.set_font("Arial", style='', size=12)
self.build_description()
self.build_rect()
self.add_coop_image()
Expand All @@ -27,76 +37,75 @@ def __init__(self, data):
self.add_qr()
self.add_name()
self.add_attributes()
def build_rect(self):
self.set_fill_color(255,168,0)
self.rect(x = self.pdf_w - self.rec_width, y = 0, w = self.rec_width, h = self.pdf_h, style = 'F')
def add_coop_image(self):

def build_rect(self):
self.set_fill_color(255, 168, 0)
self.rect(x=self.pdf_w - self.rec_width, y=0, w=self.rec_width, h=self.pdf_h, style='F')

def add_coop_image(self):
self.image("https://media.marktjagd.com/8763073_1200x409.png",
x=self.margin + 15, y=self.margin, w= self.logo_width - 15, h=self.logo_height - 5)
x=self.margin + 15, y=self.margin, w=self.logo_width - 15, h=self.logo_height - 5)

def add_wine_image(self):
img_url = "https:" + self.data['images'][0]['url'].replace("1200_630", "1474_1474")
img_data = requests.get(img_url).content
with open('.tmp.jpg', 'wb') as handler:
handler.write(img_data)
self.image(".tmp.jpg", x=self.margin,
y=self.pdf_h - 40 - self.margin - 110,
w= 110, h=110, type ='JPG')
os.remove(".tmp.jpg")
def add_description_text(self):
self.image(".tmp.jpg", x=self.margin,
y=self.pdf_h - 40 - self.margin - 110,
w=110, h=110, type='JPG')
os.remove(".tmp.jpg")

def add_description_text(self):
self.set_xy(self.margin, self.margin * 2 + self.logo_height)
self.multi_cell(w=self.logo_width, h=5, txt= self.desc1 + "\n \n" +self.desc2)
self.multi_cell(w=self.logo_width, h=5, txt=self.desc1 + "\n \n" + self.desc2)

def add_footer(self):
self.set_xy(5, self.pdf_h - 40)
self.set_font("Arial", style = 'I', size = 10)
self.set_font("Arial", style='I', size=10)
self.set_text_color(50)
self.multi_cell(w=130, h=5, txt= self.tasting_notes)
self.set_font("Arial", style = '', size = 12)
self.multi_cell(w=130, h=5, txt=self.tasting_notes)
self.set_font("Arial", style='', size=12)
self.set_text_color(0)

def add_attributes(self):
self.set_text_color(255)
price = str(self.data['allPrices'][0]['sellPrice']) + " CHF"
self.set_text_color(255)
price = str(self.data['allPrices'][0]['sellPrice']) + " CHF"
character = self.data['wineCharacter']
origin = self.data['wineOrigin']
maker = self.data['wineMaker']
origin = self.data['wineOrigin']
maker = self.data['wineMaker']
enjoyFrom = self.data["enjoyFrom"]
enjoyUntil = self.data["enjoyUntil"]
bottomTemp = self.data["servingTemperature"].split("-")[0]
topTemp = self.data["servingTemperature"].split("-")[1]
grapes = self.data['grapesText']
grapes = self.data['grapesText']
percent = self.data['alcohol']

text = f"{price}\n\n{character}\n{origin}\nWinzer - {maker} \n\nRebsorte - {grapes}\n{percent}% VOL\n\n"
text += f"Genussreife, {enjoyFrom}-{enjoyUntil}\nTrinktemperatur - {bottomTemp} - {topTemp} °C\n\nPrämierung - {self.data['averageRating']}"
text += f"Am besten, {enjoyFrom} - {enjoyUntil}\n {bottomTemp} - {topTemp} °C\n\nPrämierung - {self.data['averageRating']}"
text += f"\n\nFlaschenverschluss - {self.data['typeOfSeal']}\n\nAusbauart - {self.data['wineAgeing']}"
self.set_xy(self.pdf_w - self.rec_width + 5, 3 * self.margin)
self.multi_cell(w=60, h=5, txt=text,
align="C")
align="C")

def add_name(self):
self.set_xy(self.pdf_w - self.rec_width + self.margin, self.margin)
name = self.data['name_de']
self.set_text_color(255)
self.set_text_color(255)

vintage = self.data['yearOfVintage']
self.set_font("Arial", style = 'B', size = 14)

self.set_font("Arial", style='B', size=14)
self.set_xy(self.pdf_w - self.rec_width + 5, self.margin)
self.multi_cell(w=60, h=5, txt= name + "\n" + str(vintage), align="C")
self.set_font("Arial", style = '', size = 12)
self.set_text_color(0)
self.multi_cell(w=60, h=5, txt=name + "\n" + str(vintage), align="C")
self.set_font("Arial", style='', size=12)
self.set_text_color(0)

def add_qr(self):

pagelink = "https://www.coop.ch/de/p/" + self.data['code']
pagelink = "https://www.coop.ch/de/p/" + self.data['baseMaterialNumber']
img_url = self.generate_qr_link(pagelink)
self.image(img_url, x=self.pdf_w - self.rec_width + 10,
y=self.pdf_h-self.rec_width + 10, w= self.rec_width - 20, h=self.rec_width - 20, type ='PNG')
self.image(img_url, x=self.pdf_w - self.rec_width + 10,
y=self.pdf_h - self.rec_width + 10, w=self.rec_width - 20, h=self.rec_width - 20, type='PNG')

@staticmethod
def generate_qr_link(content):
Expand All @@ -110,23 +119,23 @@ def build_description(self):
enjoyFrom = self.data["enjoyFrom"]
enjoyUntil = self.data["enjoyUntil"]
bottomTemp = self.data["servingTemperature"].split("-")[0]
topTemp = self.data["servingTemperature"].split("-")[1]
topTemp = self.data["servingTemperature"].split("-")[1]
pairing = ""
pairing_split = self.data["goesWithText_de"].split(",")
for s in pairing_split[:-1]:
pairing += s
pairing += f", und {pairing_split[-1]}"
self.desc1 = f"{wineName}: der Wein aus {country} wurde {yearOfVintage} abgefüllt. Am besten geniesst man ihn zwischen {enjoyFrom} und {enjoyUntil}."
self.desc2 = f"Der Wein passt gut zu {pairing}, und wird am besten zwischen {bottomTemp} und {topTemp} °C genossen."
self.tasting_notes = self.data["tastingNotes_de"]
pairing += f", und {pairing_split[-1]}"

self.desc1 = f"{wineName}: der wein aus {country} wurde {yearOfVintage} abgefüllt. Am besten genießt man ihn zwischen {enjoyFrom} und {enjoyUntil}."
self.desc2 = f"Der Wein passt gut zu {pairing}, und wird am besten zwischen {bottomTemp} und {topTemp} °C genossen"
self.tasting_notes = self.data["tastingNotes_de"]

def save_doc(self, path):
self.output(path)
# self.output()


if __name__ == "__main__":
import pickle
with open('pdf_generator/test_data.pkl', 'rb') as handle:
data = pickle.load(handle)
doc = InfoDoc(data)
doc.save_doc("pdf_generator/test.pdf")
def tryInfo(product_dict):
doc = InfoDoc(product_dict)
doc.save_doc(pdf_output_file_path)
return pdf_output_file_path
Original file line number Diff line number Diff line change
@@ -1,6 +1,27 @@
from data_fetcher.fetcher import Fetcher
import os
import pdfkit
import subprocess

from coop_challenge.fetcher import Fetcher

ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
html_link = f"{ROOT_DIR}/generator/label_template/label_template.html"
css_link = f"{ROOT_DIR}/generator/label_template/style.css"
label_output_filename = "label.pdf"
label_output_folder_path = f"{ROOT_DIR}/output/"
label_output_file_path = f"{ROOT_DIR}/output/{label_output_filename}"

if not os.path.exists(label_output_folder_path):
os.makedirs(label_output_folder_path)


def tryLabel(product_dict):
product_dict['sellPrice'] = product_dict["allPrices"][0]['sellPrice']
product_dict['wineCharacter'] = product_dict["wineCharacter"].split(",")[0]
del product_dict['allPrices']
generate_html(product_dict)
label_name = create_label()

return label_name


def retrieve_wine_info():
Expand All @@ -13,7 +34,7 @@ def retrieve_wine_info():


def generate_html(product):
f = open("label_template/label_template.html", "w")
f = open(html_link, "w")

bottle_url = "https://svgsilh.com/png-512/150955.png"
logo_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/0/0a/Coop.svg/2000px-Coop.svg.png"
Expand All @@ -22,7 +43,7 @@ def generate_html(product):
message = f"""<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="{css_link}">
<meta charset="UTF-8">
<title>Label</title>
</head>
Expand All @@ -37,7 +58,7 @@ def generate_html(product):
<tr>
<td width="80">{product["yearOfVintage"]}</td>
<td width="190">{product["wineCharacter"]}</td>
<td ROWSPAN="5"><img src={qr_url} width="100"></td>
<td ROWSPAN="5"><img src={qr_url} width="100" align="center"></td>
</tr>
<tr>
<td><em>Origin:</em></td>
Expand Down Expand Up @@ -67,16 +88,10 @@ def generate_html(product):
f.close()


def create_label(prod):
path = "label_template/label_template.html"
pdfkit.from_file(path, "output/label1.pdf", css="label_template/style.css",
options={"enable-local-file-access": ""})

def create_label():
pdfkit.from_file(html_link, label_output_file_path, css=css_link, options={"enable-local-file-access": ""})

def create_label_shell_call(prod):
# with relative paths in HTML, but with a local shell run :(
path = "label_template/label_template.html"
subprocess.run(["wkhtmltopdf", "--enable-local-file-access", path, "output/label1.pdf"])
return label_output_file_path


def generate_qr_link(productId):
Expand All @@ -88,4 +103,4 @@ def generate_qr_link(productId):
if __name__ == "__main__":
product = retrieve_wine_info()
generate_html(product)
create_label(product)
create_label()
File renamed without changes.

0 comments on commit 80a3cef

Please sign in to comment.