Spaces:
Sleeping
Sleeping
Download app.py from MohammadJMH/program_v1: direct link, hf CLI and curl.
- Browser
- Download file 18.6 kB
-
https://huggingface.co/spaces/MohammadJMH/program_v1/resolve/main/app.py
- Command line
-
hf download hf://spaces/MohammadJMH/program_v1/app.py
-
curl -L -o app.py https://huggingface.co/spaces/MohammadJMH/program_v1/resolve/main/app.py
18.6 kB
| import pandas as pd | |
| import gradio as gr | |
| import os | |
| import matplotlib.pyplot as plt | |
| # إعداد الرسم في الخلفية | |
| plt.switch_backend('agg') | |
| # --- 1. دالة تحميل وتنظيف البيانات من الملفات المرفوعة --- | |
| def load_pro(file, col): | |
| # التأكد من وجود الملف المرفوع | |
| if not os.path.exists(file): | |
| print(f" الملف {file} غير موجود في المستودع!") | |
| return pd.DataFrame() | |
| try: | |
| # قراءة الملف (استخدمنا latin1 لتفادي أخطاء الترميز المشهورة في ملفات القطع) | |
| df = pd.read_csv(file, encoding='latin1') | |
| # البحث عن عمود السعر (سواء كان اسمه Price أو MRP) | |
| p_col = next((c for c in df.columns if c.lower() in ['mrp', 'price']), None) | |
| if p_col: | |
| # تنظيف السعر: إزالة العملات والرموز وتحويله لرقم | |
| df['Price'] = df[p_col].astype(str).str.replace(r'[^\d.]', '', regex=True) | |
| df['Price'] = pd.to_numeric(df['Price'], errors='coerce') | |
| df = df.dropna(subset=['Price']) | |
| # إعادة تسمية عمود الاسم لتوحيد التعامل | |
| df = df.rename(columns={col: 'Name'}) | |
| return df[['Name', 'Price']] | |
| except Exception as e: | |
| print(f" خطأ في قراءة {file}: {e}") | |
| return pd.DataFrame() | |
| # --- 2. دالة بناء التجميعة الذكية --- | |
| def ultimate_builder(budget, env_type): | |
| # خريطة الملفات والنسب المئوية المقترحة لكل قطعة | |
| config = { | |
| "CPU": ("CPU.csv", "CPU", 0.20), | |
| "GPU": ("GPU.csv", "GPU", 0.30), | |
| "Motherboard": ("MotherBoard.csv", "motherBoard", 0.10), | |
| "RAM": ("RAM.csv", "Ram", 0.08), | |
| "SSD": ("StorageSSD.csv", "SSD", 0.07), | |
| "PowerSupply": ("PowerSupply.csv", "PowerSupply", 0.07), | |
| "Case": ("cabinates.csv", "cabinates", 0.05), | |
| "Accessories": ("Accessories.csv", "Name", 0.03) | |
| } | |
| # اختيار الشاشة أو التلفاز بناءً على البيئة | |
| disp_file = "Monitors.csv" if "مكتب" in env_type else "TVs.csv" | |
| config["Display"] = (disp_file, "Name", 0.10) | |
| final_parts = [] | |
| total_cost = 0 | |
| for cat, (file, col, ratio) in config.items(): | |
| df_parts = load_pro(file, col) | |
| if not df_parts.empty: | |
| limit = budget * ratio | |
| # البحث عن أغلى قطعة لا تتجاوز النسبة المحددة | |
| affordable = df_parts[df_parts['Price'] <= limit] | |
| if not affordable.empty: | |
| selected = affordable.sort_values('Price', ascending=False).iloc[0] | |
| else: | |
| # إذا كانت الميزانية ضعيفة جداً، نختار أرخص قطعة متاحة | |
| selected = df_parts.sort_values('Price', ascending=True).iloc[0] | |
| final_parts.append([cat, selected['Name'], f"{selected['Price']:,.2f}"]) | |
| total_cost += selected['Price'] | |
| else: | |
| final_parts.append([cat, "غير متوفر (تأكد من رفع الملف)", "0.00"]) | |
| status = " تجميعة ناجحة" if total_cost <= budget else " تجاوزت الميزانية قليلاً" | |
| report = f"### ملخص النظام {status}\n- الميزانية المطلوبة: ${budget:,.2f}\n- التكلفة الفعلية: ${total_cost:,.2f}" | |
| return final_parts, report | |
| # --- 3. واجهة المستخدم (Gradio Interface) --- | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# نظام المهندس التقني لبناء التجميعات") | |
| gr.Markdown("قم بإدخال ميزانيتك، وسيقوم النظام باختيار أفضل القطع المتوافقة من ملفاتك المرفوعة.") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| in_budget = gr.Number(label="الميزانية الإجمالية ($)", value=1200) | |
| in_env = gr.Dropdown(["غرفة مكتب (Monitor)", "صالة معيشة (TV)"], label="مكان التركيب", value="غرفة مكتب (Monitor)") | |
| btn = gr.Button("توليد التجميعة الآن", variant="primary") | |
| with gr.Column(scale=2): | |
| out_table = gr.DataFrame(headers=["الفئة", "القطعة المختارة", "السعر ($)"]) | |
| out_text = gr.Markdown() | |
| btn.click(fn=ultimate_builder, inputs=[in_budget, in_env], outputs=[out_table, out_text]) | |
| if __name__ == "__main__": | |
| demo.launch() | |
| # Step 1: استيراد المكتبات الضرورية | |
| import pandas as pd | |
| import numpy as np | |
| import matplotlib.pyplot as plt | |
| # Step 2: تحميل ملفاتك (استخدم الـ ID الخاص بملفاتك من جوجل درايف) | |
| # ملاحظة: استبدل الـ ID بالمعرف الخاص بملف CPU.csv مثلاً | |
| # Step 3: قراءة الملف ومعالجة مشكلة التشفير (Unicode Error) | |
| try: | |
| # قمنا بتغيير اسم الملف ليتناسب مع ما حملته | |
| df = pd.read_csv('CPU.csv', encoding='latin1') | |
| print("Success: File loaded successfully!") | |
| except: | |
| # في حال لم يجد ملف CPU، سيقرأ الملف الافتراضي الذي حملته للتجربة | |
| df = pd.read_csv('diabetes.csv') | |
| print("Note: Loaded diabetes.csv as a fallback.") | |
| # Step 4: عرض أول 5 أسطر للتأكد من البيانات (مثل ملف diabetes) | |
| print(df.head()) | |
| # Step 5: تنظيف عمود السعر (Price) ليصبح رقمياً للرسم البياني | |
| if 'Price' in df.columns or 'MRP' in df.columns: | |
| p_col = 'Price' if 'Price' in df.columns else 'MRP' | |
| df[p_col] = pd.to_numeric(df[p_col].astype(str).str.replace(',', ''), errors='coerce') | |
| # رسم مخطط الصندوق (Boxplot) للسعر فقط | |
| plt.figure(figsize=(10, 6)) | |
| df.boxplot(column=[p_col]) | |
| plt.title(f"Price Distribution Analysis (Outliers)") | |
| plt.ylabel("Price in local currency") | |
| plt.show() | |
| import pandas as pd | |
| import os | |
| # 1. تحميل ملف المعالجات كمثال | |
| file_path = 'CPU.csv' | |
| if os.path.exists(file_path): | |
| # قراءة الملف مع معالجة التشفير | |
| df = pd.read_csv(file_path, encoding='latin1') | |
| print("--- Step 2: Discover Data ---") | |
| # معرفة حجم البيانات (Rows, Columns) | |
| shape = df.shape | |
| print(f"Dataset Shape: {shape}") | |
| print(f"Number of Items (Rows): {shape[0]}") | |
| print(f"Number of Features (Columns): {shape[1]}") | |
| print("\n--- Column Names ---") | |
| print(df.columns.tolist()) # عرض أسماء الأعمدة لمعرفة المواصفات المتاحة | |
| print("\n--- Quick Statistics ---") | |
| # هذا السطر يعطيك (المتوسط، أقل سعر، أعلى سعر) للأعمدة الرقمية | |
| print(df.describe()) | |
| else: | |
| print("Please upload CPU.csv first!") | |
| import pandas as pd | |
| import os | |
| # 1. قائمة بالملفات التي تشكل الداتا سيت الخاصة بك | |
| files = { | |
| "CPU": "CPU.csv", | |
| "GPU": "GPU.csv", | |
| "RAM": "RAM.csv", | |
| "SSD": "StorageSSD.csv" | |
| } | |
| print("=== Full Dataset Discovery ===\n") | |
| for label, path in files.items(): | |
| if os.path.exists(path): | |
| try: | |
| # قراءة الملف مع معالجة التشفير (لتجنب خطأ Unicode السابق) | |
| df_temp = pd.read_csv(path, encoding='latin1') | |
| print(f"--- Analysis for: {label} ---") | |
| # تنفيذ أمر shape (عدد الصفوف والأعمدة) | |
| rows, cols = df_temp.shape | |
| print(f"Shape: {rows} Items and {cols} Features") | |
| # عرض أسماء الأعمدة لمعرفة نوع المواصفات | |
| print(f"Columns: {df_temp.columns.tolist()}") | |
| # إحصائيات سريعة للأسعار (المتوسط، أقل سعر، أعلى سعر) | |
| p_col = next((c for c in df_temp.columns if 'price' in c.lower() or 'mrp' in c.lower()), None) | |
| if p_col: | |
| # تنظيف السعر لتحويله لرقم | |
| df_temp[p_col] = pd.to_numeric(df_temp[p_col].astype(str).str.replace(',', ''), errors='coerce') | |
| print(f"Price Statistics (in USD/Local):\n{df_temp[p_col].describe()}") | |
| print("-" * 30 + "\n") | |
| except Exception as e: | |
| print(f"Could not analyze {label}: {e}\n") | |
| else: | |
| print(f"File {path} not found. Please upload it.\n") | |
| import pandas as pd | |
| import os | |
| # قائمة ملفات مشروعك | |
| files = { | |
| "CPU": "CPU.csv", | |
| "GPU": "GPU.csv", | |
| "RAM": "RAM.csv", | |
| "SSD": "StorageSSD.csv" | |
| } | |
| print("=== Discovering Data: df.info() for all datasets ===\n") | |
| for label, path in files.items(): | |
| if os.path.exists(path): | |
| try: | |
| # القراءة مع معالجة التشفير لتجنب الأخطاء | |
| df_temp = pd.read_csv(path, encoding='latin1') | |
| print(f"--- INFO FOR: {label} ---") | |
| # تنفيذ أمر info() لعرض أنواع البيانات والقيم المفقودة | |
| # أضفنا buf=None لإظهار المخرج مباشرة في كولاب | |
| df_temp.info() | |
| print("\n" + "="*50 + "\n") | |
| except Exception as e: | |
| print(f"Error reading {label}: {e}") | |
| else: | |
| print(f"File {path} not found.\n") | |
| import pandas as pd | |
| import os | |
| # قائمة ملفات مشروعك | |
| files = { | |
| "CPU": "CPU.csv", | |
| "GPU": "GPU.csv", | |
| "RAM": "RAM.csv", | |
| "SSD": "StorageSSD.csv" | |
| } | |
| print("=== Step 2: Full Statistical Discovery (df.describe) ===\n") | |
| for label, path in files.items(): | |
| if os.path.exists(path): | |
| try: | |
| # قراءة الملف مع معالجة التشفير | |
| df_temp = pd.read_csv(path, encoding='latin1') | |
| # البحث عن عمود السعر وتنظيفه (لأن describe تعمل فقط على الأرقام) | |
| p_col = next((c for c in df_temp.columns if 'price' in c.lower() or 'mrp' in c.lower()), None) | |
| if p_col: | |
| # تحويل السعر لرقم (إزالة الفواصل والعلامات) | |
| df_temp[p_col] = pd.to_numeric(df_temp[p_col].astype(str).str.replace(',', '').str.replace('$', ''), errors='coerce') | |
| print(f"--- Statistics for {label} ---") | |
| # إظهار الإحصائيات لعمود السعر | |
| print(df_temp[p_col].describe()) | |
| print("\n" + "="*40 + "\n") | |
| except Exception as e: | |
| print(f"Error analyzing {label}: {e}") | |
| import pandas as pd | |
| import os | |
| # قائمة ملفات مشروعك | |
| files = { | |
| "CPU": "CPU.csv", | |
| "GPU": "GPU.csv", | |
| "RAM": "RAM.csv", | |
| "SSD": "StorageSSD.csv" | |
| } | |
| print("=== Step 3: Cleaning Data (Checking Missing Values) ===\n") | |
| for label, path in files.items(): | |
| if os.path.exists(path): | |
| try: | |
| # القراءة مع معالجة التشفير | |
| df_temp = pd.read_csv(path, encoding='latin1') | |
| print(f"--- Missing Values in {label} ---") | |
| # تنفيذ أمر isnull().sum() لمعرفة عدد الفراغات في كل عمود | |
| missing_data = df_temp.isnull().sum() | |
| # إظهار الأعمدة التي تحتوي على مفقودات فقط لتسهيل القراءة | |
| if missing_data.sum() > 0: | |
| print(missing_data[missing_data > 0]) | |
| else: | |
| print("Perfect! No missing values found in this file.") | |
| print("\n" + "="*40 + "\n") | |
| except Exception as e: | |
| print(f"Error analyzing {label}: {e}") | |
| import pandas as pd | |
| import os | |
| # 1. تعريف دالة اكتشاف ومعالجة القيم المتطرفة (IQR Method) | |
| def handle_outliers_with_mean(df, column): | |
| # التأكد أن العمود رقمي فقط | |
| if pd.api.types.is_numeric_dtype(df[column]): | |
| Q1 = df[column].quantile(0.25) | |
| Q3 = df[column].quantile(0.75) | |
| IQR = Q3 - Q1 | |
| lower_bound = Q1 - 1.5 * IQR | |
| upper_bound = Q3 + 1.5 * IQR | |
| # استبدال القيم المتطرفة بمتوسط العمود (Mean) | |
| mean_value = df[column].mean() | |
| df.loc[(df[column] < lower_bound) | (df[column] > upper_bound), column] = mean_value | |
| return df | |
| # 2. تطبيق العملية على كل ملفات مشروعك | |
| files = {"CPU": "CPU.csv", "GPU": "GPU.csv", "RAM": "RAM.csv", "SSD": "StorageSSD.csv"} | |
| print("=== Step 3: Cleaning Outliers and Replacing with Mean ===\n") | |
| for label, path in files.items(): | |
| if os.path.exists(path): | |
| try: | |
| df_temp = pd.read_csv(path, encoding='latin1') | |
| # تنظيف عمود السعر أولاً ليصبح رقمياً | |
| p_col = next((c for c in df_temp.columns if 'price' in c.lower() or 'mrp' in c.lower()), None) | |
| if p_col: | |
| df_temp[p_col] = pd.to_numeric(df_temp[p_col].astype(str).str.replace(',', ''), errors='coerce') | |
| df_temp[p_col] = df_temp[p_col].fillna(df_temp[p_col].mean()) # تعبئة الفراغات بالمتوسط | |
| # تطبيق الدالة على عمود السعر | |
| df_temp = handle_outliers_with_mean(df_temp, p_col) | |
| print(f"Success: Outliers handled in {label} ({p_col})") | |
| except Exception as e: | |
| print(f"Error in {label}: {e}") | |
| print("\nDone! All outliers have been normalized.") | |
| import pandas as pd | |
| import matplotlib.pyplot as plt | |
| import os | |
| # 1. تجميع البيانات المنظفة (بعد معالجة القيم المتطرفة) | |
| cleaned_plot_data = {} | |
| for label, path in files.items(): | |
| if os.path.exists(path): | |
| try: | |
| df_temp = pd.read_csv(path, encoding='latin1') | |
| p_col = next((c for c in df_temp.columns if 'price' in c.lower() or 'mrp' in c.lower()), None) | |
| if p_col: | |
| # تحويل السعر وتطبيق دالة التنظيف (IQR) التي عملناها في الخطوة السابقة | |
| df_temp[p_col] = pd.to_numeric(df_temp[p_col].astype(str).str.replace(',', ''), errors='coerce') | |
| df_temp[p_col] = df_temp[p_col].fillna(df_temp[p_col].mean()) | |
| # تطبيق دالة معالجة القيم المتطرفة (نفس الدالة السابقة) | |
| Q1 = df_temp[p_col].quantile(0.25) | |
| Q3 = df_temp[p_col].quantile(0.75) | |
| IQR = Q3 - Q1 | |
| lower = Q1 - 1.5 * IQR | |
| upper = Q3 + 1.5 * IQR | |
| # استبدال القيم بالمتوسط | |
| df_temp.loc[(df_temp[p_col] < lower) | (df_temp[p_col] > upper), p_col] = df_temp[p_col].mean() | |
| cleaned_plot_data[label] = df_temp[p_col] / 22 # التحويل للدولار | |
| except: | |
| continue | |
| # 2. رسم الصندوق النهائي للتأكد من نظافة البيانات | |
| if cleaned_plot_data: | |
| plt.figure(figsize=(14, 5)) | |
| # دمج البيانات في DataFrame واحد للرسم | |
| df_final = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in cleaned_plot_data.items()])) | |
| # رسم الصناديق | |
| df_final.boxplot() | |
| plt.title("Price Distribution AFTER Cleaning Outliers (Verification)", fontsize=14) | |
| plt.ylabel("Price in USD ($)") | |
| plt.grid(axis='y', linestyle='--', alpha=0.7) | |
| plt.show() | |
| else: | |
| print("No data available to plot. Check your files!") | |
| import pandas as pd | |
| import os | |
| # المسار لملف المعالجات (يمكنك تغييره لـ GPU.csv أو أي ملف آخر) | |
| file_path = 'CPU.csv' | |
| if os.path.exists(file_path): | |
| try: | |
| # 1. قراءة الملف مع معالجة التشفير (latin1) لضمان عدم ظهور أخطاء | |
| df = pd.read_csv(file_path, encoding='latin1') | |
| print(f"--- Showing first 5 records of {file_path} ---") | |
| # 2. تنفيذ أمر head(5) لعرض أول 5 أسطر | |
| # سيظهر لك أسماء القطع، المقابس (Sockets)، والأسعار (Price) | |
| display(df.head(5)) | |
| except Exception as e: | |
| print(f"Error reading the file: {e}") | |
| else: | |
| print(f"File '{file_path}' not found. Please upload it to the sidebar.") | |
| import pandas as pd | |
| import seaborn as sns | |
| import matplotlib.pyplot as plt | |
| import os | |
| # 1. تحميل ملف المعالجات كمثال | |
| file_path = 'CPU.csv' | |
| if os.path.exists(file_path): | |
| try: | |
| # قراءة البيانات بتشفير latin1 | |
| df_cpu = pd.read_csv(file_path, encoding='latin1') | |
| # تنظيف عمود السعر (المتغير Y) | |
| p_col = next((c for c in df_cpu.columns if 'price' in c.lower() or 'mrp' in c.lower()), None) | |
| if p_col: | |
| # تحويل السعر لرقم وتنظيفه | |
| df_cpu['Price_Clean'] = pd.to_numeric(df_cpu[p_col].astype(str).str.replace(',', '').str.replace('$', ''), errors='coerce') | |
| # المتغير الثاني (X): سنستخدم "ترتيب القطعة" كمؤشر افتراضي | |
| df_cpu['Item_Rank'] = range(len(df_cpu)) | |
| # حذف القيم الفارغة لضمان دقة خط الانحدار | |
| df_plot = df_cpu[['Item_Rank', 'Price_Clean']].dropna() | |
| # 2. رسم النقاط مع خط الانحدار (Regplot) | |
| plt.figure(figsize=(12, 6)) | |
| # رسم العلاقة: x هو الترتيب، y هو السعر | |
| # الخط الأحمر يمثل "الاتجاه العام" للأسعار | |
| sns.regplot(data=df_plot, x='Item_Rank', y='Price_Clean', | |
| scatter_kws={'s': 80, 'alpha': 0.5, 'color': 'royalblue'}, | |
| line_kws={'color': 'red', 'lw': 2}) | |
| # إضافة العنوان والمحاور بالإنجليزية | |
| plt.title('Price Trend Analysis (Regression Plot)', fontsize=15) | |
| plt.xlabel('Item Sequence / Rank', fontsize=12) | |
| plt.ylabel('Price in USD ($)', fontsize=12) | |
| plt.grid(True, linestyle='--', alpha=0.6) | |
| plt.show() | |
| else: | |
| print("Price column not found in the CSV!") | |
| except Exception as e: | |
| print(f"Error: {e}") | |
| else: | |
| print("File CPU.csv not found! Please upload it.") | |