File size: 3,499 Bytes
ae72e0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()