import gradio as gr import pandas as pd import os import json JSON_PATH = "/tmp/material_db.json" def parse_excel(file, description): if file is None or not description.strip(): return "", "", "⚠️ لطفاً فایل اکسل و توضیح پروژه را وارد کنید." try: df = pd.read_excel(file.name, header=2) except Exception as e: return "", "", f"❌ خطا در خواندن فایل اکسل: {str(e)}" column_mapping = { "code": ["کد", "کد فهرست بها"], "description": ["عنوان", "شرح کالا", "نام کالا"], "quantity": ["تعداد", "تعداد مورد نیاز"], "unit": ["واحد", "واحد شمارش", "نوع واحد"] } resolved = {} for key, options in column_mapping.items(): found = next((col for col in options if col in df.columns), None) if not found: return "", "", f"❌ ستون «{key}» در فایل پیدا نشد." resolved[key] = found materials = [] constraints = [] for _, row in df.iterrows(): try: qty = float(row[resolved["quantity"]]) if pd.isna(qty) or qty <= 0: continue except: continue material = { "code": str(row[resolved["code"]]).strip(), "description": str(row[resolved["description"]]).strip(), "quantity": qty, "unit": str(row[resolved["unit"]]).strip() } materials.append(material) constraints.append(f"{material['description']} ({material['quantity']} {material['unit']})") # ذخیره در فایل جیسان با توضیح پروژه try: if os.path.exists(JSON_PATH): with open(JSON_PATH, "r", encoding="utf-8") as f: existing = json.load(f) else: existing = [] new_record = { "project_description": description.strip(), "items": materials } existing.append(new_record) with open(JSON_PATH, "w", encoding="utf-8") as f: json.dump(existing, f, indent=2, ensure_ascii=False) except Exception as e: return "", "", f"❌ خطا در ذخیره فایل JSON: {str(e)}" return "\n".join(constraints), f"✅ {len(materials)} قلم ثبت شد.", JSON_PATH def download_json(): return JSON_PATH if os.path.exists(JSON_PATH) else None with gr.Blocks(title="مدیریت مواد پروژه") as demo: gr.Markdown("## 📋 بارگذاری فایل برآورد، توصیف پروژه و استخراج اقلام") with gr.Row(): file_input = gr.File(label="آپلود فایل اکسل") project_desc = gr.Textbox(label="📝 توضیح پروژه", placeholder="مثلاً: پروژه خط ۲۰ کیلوولت فاز دوم") upload_btn = gr.Button("📤 بارگذاری و ثبت") download_btn = gr.Button("📥 دانلود فایل JSON") status_output = gr.Textbox(label="وضعیت", lines=2) constraints_output = gr.Textbox(label="🔍 قیود استخراج‌شده", lines=10) json_file_output = gr.File(label="فایل JSON خروجی", visible=True) upload_btn.click(parse_excel, inputs=[file_input, project_desc], outputs=[constraints_output, status_output, json_file_output]) download_btn.click(download_json, outputs=json_file_output) if __name__ == "__main__": demo.launch()