File size: 6,246 Bytes
c93b21e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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

def load_json_file(json_file):
    if json_file is None:
        return "⚠️ لطفاً یک فایل JSON معتبر انتخاب کنید."

    try:
        with open(json_file.name, "r", encoding="utf-8") as f:
            content = json.load(f)
        with open(JSON_PATH, "w", encoding="utf-8") as f2:
            json.dump(content, f2, indent=2, ensure_ascii=False)
        return f"✅ فایل JSON بارگذاری و جایگزین شد."
    except Exception as e:
        return f"❌ خطا در خواندن یا ذخیره فایل JSON: {str(e)}"

def show_all_projects(keyword=""):
    if not os.path.exists(JSON_PATH):
        return "⚠️ فایل JSON موجود نیست."

    try:
        with open(JSON_PATH, "r", encoding="utf-8") as f:
            content = json.load(f)

        keyword = keyword.strip().lower()
        result = ""
        for i, project in enumerate(content):
            full_text = project["project_description"] + " " + " ".join([item["description"] for item in project["items"]])
            if keyword and keyword not in full_text.lower():
                continue

            result += f"\n📁 پروژه {i+1}: {project['project_description']}\n"
            for item in project["items"]:
                result += f"- {item['description']} ({item['quantity']} {item['unit']})\n"
        return result.strip() or "❌ پروژه‌ای با این کلیدواژه پیدا نشد."
    except Exception as e:
        return f"❌ خطا در خواندن فایل JSON: {str(e)}"

with gr.Blocks(title="مدیریت مواد پروژه - نسخه 0.1.2") as demo:
    with gr.Tab("📤 بارگذاری اکسل و ثبت پروژه"):
        gr.Markdown("## آپلود فایل اکسل و وارد کردن توضیح پروژه")

        with gr.Row():
            file_input = gr.File(label="آپلود فایل اکسل")
            project_desc = gr.Textbox(label="📝 توضیح پروژه")

        upload_btn = gr.Button("📤 بارگذاری و ثبت")
        status_output = gr.Textbox(label="وضعیت", lines=2)
        constraints_output = gr.Textbox(label="🔍 اقلام استخراج‌شده", lines=10)
        json_file_output = gr.File(label="📁 فایل JSON خروجی", visible=True)
        download_btn = gr.Button("📥 دانلود فایل JSON")

        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)

    with gr.Tab("📚 پروژه‌های ثبت‌شده و بارگذاری JSON"):
        gr.Markdown("## جستجو و مشاهده پروژه‌های ذخیره‌شده")

        with gr.Row():
            search_box = gr.Textbox(label="", placeholder="🔍 جستجو بر اساس کلیدواژه", scale=4)
            search_btn = gr.Button(value="🔎", scale=1)
        json_content_output = gr.Textbox(label="📑 نتایج پروژه‌ها", lines=20, interactive=False)

        search_btn.click(show_all_projects, inputs=search_box, outputs=json_content_output)

        gr.Markdown("## نمایش همه پروژه‌ها")
        show_btn = gr.Button("📂 نمایش پروژه‌های ذخیره‌شده")
        show_btn.click(show_all_projects, outputs=json_content_output)

        gr.Markdown("## بارگذاری فایل JSON از سیستم شما")
        json_input_file = gr.File(label="📥 انتخاب فایل JSON جدید")
        load_json_btn = gr.Button("🔄 بارگذاری فایل JSON جدید")
        json_load_status = gr.Textbox(label="وضعیت بارگذاری فایل JSON")
        load_json_btn.click(load_json_file, inputs=json_input_file, outputs=json_load_status)

if __name__ == "__main__":
    demo.launch()