Hadeeratef91's picture
Update app.py
77998fe verified
import pandas as pd
from PIL import Image, ImageDraw, ImageFont
import os
import shutil
import requests
import qrcode
from arabic_reshaper import reshape
import gradio as gr
# تحميل خط من الإنترنت
font_url = "https://github.com/google/fonts/blob/main/ofl/amiri/Amiri-Regular.ttf?raw=true"
font_path = "Amiri-Regular.ttf"
response = requests.get(font_url)
with open(font_path, 'wb') as f:
f.write(response.content)
def process_files(file1, file2):
# قراءة البيانات من ملفات Excel
data1 = pd.read_excel(file1.name, engine="openpyxl").rename(columns=lambda x: x.strip())
data2 = pd.read_excel(file2.name, engine="openpyxl").rename(columns=lambda x: x.strip())
# دمج البيانات
merged_data = pd.concat([data1, data2], ignore_index=True)
# التحقق من وجود الأعمدة المطلوبة
required_columns = ['Asset-Code', 'Location', 'Unit', 'Description', 'Supplier Name']
for column in required_columns:
if column not in merged_data.columns:
return f"العمود {column} غير موجود في الملفات!"
# تنظيف النصوص
def clean_text(text):
if pd.isna(text):
return "غير متوفر"
return str(text).strip()
merged_data["Description"] = merged_data["Description"].apply(clean_text)
merged_data["Supplier Name"] = merged_data["Supplier Name"].apply(clean_text)
# إعداد مجلدات الإخراج
qr_folder = "qr_codes_with_units"
output_folder = "labels_output"
zip_output_path = "Labels_with_QRCodes.zip"
os.makedirs(qr_folder, exist_ok=True)
os.makedirs(output_folder, exist_ok=True)
# إعداد الخط
try:
font = ImageFont.truetype(font_path, 14)
except OSError:
font = ImageFont.load_default()
# إعداد أبعاد الملصق
label_width = 400
label_height = 300
qr_size = 155
# قائمة لتخزين بيانات QR Code
qr_data_list = []
# إنشاء QR Codes وملصقات
for _, row in merged_data.iterrows():
asset_code = str(row["Asset-Code"])
location = clean_text(row["Location"])
description = reshape(clean_text(row["Description"]))
supplier_name = reshape(clean_text(row["Supplier Name"]))
# معالجة القيم الفارغة في Unit
unit_count = int(row["Unit"]) if pd.notna(row["Unit"]) else 1
for i in range(1, unit_count + 1):
# إنشاء نص QR
qr_info = f"Asset-Code: {asset_code}, Location: {location}, Unit: {i}"
# إنشاء QR Code
qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=5, border=1)
qr.add_data(qr_info)
qr.make(fit=True)
# حفظ QR Code كصورة
qr_file_name = f"{asset_code}-{i}.png"
qr_file_path = os.path.join(qr_folder, qr_file_name)
qr_image = qr.make_image(fill_color="black", back_color="white")
qr_image.save(qr_file_path)
# إنشاء الملصق
label = Image.new("RGB", (label_width, label_height), "white")
draw = ImageDraw.Draw(label)
# لصق QR Code
qr_x = 20
qr_y = (label_height - qr_size) // 2
label.paste(qr_image.resize((qr_size, qr_size)), (qr_x, qr_y))
# إضافة النصوص بجانب QR Code
text_x = qr_x + qr_size + 15
text_y = 50
line_spacing = 40
draw.text((text_x, text_y), f"اسم الصنف: {description}", font=font, fill="black")
draw.text((text_x, text_y + line_spacing), f"اسم المورد: {supplier_name}", font=font, fill="black")
draw.text((text_x, text_y + 2 * line_spacing), f"كود الصنف: {asset_code}", font=font, fill="black")
# حفظ الملصق
label_file_name = f"{asset_code}-{i}_label.png"
label.save(os.path.join(output_folder, label_file_name))
# إضافة البيانات إلى القائمة
qr_data_list.append({
"Asset-Code": asset_code,
"Location": location,
"Unit": i,
"Description": row["Description"],
"Supplier Name": row["Supplier Name"]
})
# ضغط الملفات إلى ملف ZIP
shutil.make_archive("labels_with_qr", 'zip', output_folder)
shutil.move("labels_with_qr.zip", zip_output_path)
# حفظ بيانات QR Code في ملف Excel
output_excel = "qr_data_output.xlsx"
qr_data_df = pd.DataFrame(qr_data_list)
qr_data_df.to_excel(output_excel, index=False, engine='openpyxl')
# حفظ البيانات في ملف CSV
output_csv = "qr_data_output.csv"
qr_data_df.to_csv(output_csv, index=False)
# إرجاع روابط التنزيل
return zip_output_path, output_excel, output_csv
# واجهة Gradio
interface = gr.Interface(
fn=process_files,
inputs=[
gr.File(label="اختر ملف Excel الأول"),
gr.File(label="اختر ملف Excel الثاني")
],
outputs=[
gr.File(label="تحميل ملف ZIP الناتج"),
gr.File(label="تحميل ملف Excel الناتج"),
gr.File(label="تحميل ملف CSV الناتج")
],
title="QR code generator",
description="for generating QR codes with labels and saving results"
)
if __name__ == "__main__":
interface.launch(share=True)