MonitorKarma's picture
Update app.py
c22ce58 verified
import gradio as gr
import pandas as pd
import os
import sklearn
import pickle
import joblib
print("=== ЗАПУСК ПРИЛОЖЕНИЯ ===")
print(f"Текущая директория: {os.getcwd()}")
print(f"Файлы в директории: {os.listdir('.')}")
# Функция загрузки модели
def load_model():
try:
# Пробуем разные форматы и пути
model_files = [
'car_price_model.pkl',
'car_price_model.joblib',
'car_price_pipeline.pkl',
'./car_price_model.pkl'
]
for model_file in model_files:
if os.path.exists(model_file):
print(f"Найден файл модели: {model_file}")
try:
# Пробуем загрузить через joblib
model = joblib.load(model_file)
print(f"Модель загружена через joblib, тип: {type(model)}")
return model, None
except:
# Пробуем загрузить через pickle
try:
with open(model_file, 'rb') as f:
model = pickle.load(f)
print(f"Модель загружена через pickle, тип: {type(model)}")
return model, None
except Exception as e:
print(f"Ошибка загрузки {model_file}: {e}")
continue
return None, "Файл модели не найден"
except Exception as e:
return None, f"Ошибка загрузки модели: {str(e)}"
# Загружаем модель при старте
model, error = load_model()
if error:
print(f"Ошибка загрузки модели: {error}")
demo_mode = True
else:
print("Модель успешно загружена!")
demo_mode = False
# Функция предсказания
def predict_car_price(vehicle_manufacturer, vehicle_category, current_mileage,
vehicle_year, vehicle_gearbox_type, doors_cnt, wheels,
vehicle_color, car_leather_interior):
if demo_mode:
# Демо-режим
base_price = 5000
year_bonus = (vehicle_year - 2000) * 200
mileage_penalty = current_mileage * 0.01
leather_bonus = 1000 if car_leather_interior == 1 else 0
estimated_price = base_price + year_bonus - mileage_penalty + leather_bonus
estimated_price = max(estimated_price, 500)
return f"Примерная цена: ${estimated_price:,.2f} (демо-режим)\n\nМодель не загружена: {error}"
else:
# Режим с ML моделью
try:
input_data = pd.DataFrame({
'vehicle_manufacturer': [vehicle_manufacturer],
'vehicle_category': [vehicle_category],
'current_mileage': [int(current_mileage)],
'vehicle_year': [int(vehicle_year)],
'vehicle_gearbox_type': [vehicle_gearbox_type],
'doors_cnt': [doors_cnt],
'wheels': [wheels],
'vehicle_color': [vehicle_color],
'car_leather_interior': [int(car_leather_interior)]
})
prediction = model.predict(input_data)[0]
return f"Предсказанная цена: ${prediction:,.2f}"
except Exception as e:
return f"Ошибка предсказания: {str(e)}"
# Создаем интерфейс
with gr.Blocks(title="Car Price Predictor", theme=gr.themes.Soft()) as demo:
gr.Markdown("# 🚗 Car Price Prediction Model")
gr.Markdown("Введите параметры автомобиля для предсказания цены")
with gr.Row():
with gr.Column():
vehicle_manufacturer = gr.Dropdown(
choices=['HYUNDAI', 'TOYOTA', 'BMW', 'MAZDA', 'NISSAN', 'MERCEDES-BENZ',
'LEXUS', 'VOLKSWAGEN', 'HONDA', 'FORD', 'AUDI', 'KIA'],
label="Производитель",
value='TOYOTA'
)
vehicle_category = gr.Dropdown(
choices=['Sedan', 'Hatchback', 'Jeep', 'Coupe', 'Minivan', 'Pickup'],
label="Категория",
value='Sedan'
)
current_mileage = gr.Number(
label="Пробег (км)",
value=100000,
minimum=0
)
vehicle_year = gr.Slider(
label="Год выпуска",
minimum=1990,
maximum=2024,
value=2015,
step=1
)
with gr.Column():
vehicle_gearbox_type = gr.Dropdown(
choices=['Automatic', 'Manual', 'Tiptronic'],
label="Тип коробки передач",
value='Automatic'
)
doors_cnt = gr.Dropdown(
choices=['2/3', '4/5'],
label="Количество дверей",
value='4/5'
)
wheels = gr.Dropdown(
choices=['Left wheel', 'Right-hand drive'],
label="Расположение руля",
value='Left wheel'
)
vehicle_color = gr.Dropdown(
choices=['Silver', 'White', 'Grey', 'Black', 'Blue', 'Red'],
label="Цвет",
value='Black'
)
car_leather_interior = gr.Radio(
choices=[("Нет", 0), ("Да", 1)],
label="Кожаный салон",
value=1
)
predict_btn = gr.Button("Предсказать цену", variant="primary")
output = gr.Textbox(
label="Результат",
interactive=False,
lines=3
)
predict_btn.click(
fn=predict_car_price,
inputs=[vehicle_manufacturer, vehicle_category, current_mileage,
vehicle_year, vehicle_gearbox_type, doors_cnt, wheels,
vehicle_color, car_leather_interior],
outputs=output
)
if __name__ == "__main__":
demo.launch()