Spaces:
Sleeping
Sleeping
File size: 18,560 Bytes
ae34f7f 80e61dd ae34f7f 80e61dd ae34f7f 80e61dd ae34f7f 80e61dd ae34f7f | 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 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 | 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.")
|