File size: 6,593 Bytes
43bf68c
 
182f196
8e3f8a8
182f196
2ba066a
5465e06
182f196
 
 
43bf68c
2ba066a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43bf68c
 
 
 
2ba066a
 
 
 
 
 
 
 
 
 
 
43bf68c
2ba066a
 
 
 
 
 
 
 
 
 
 
 
 
 
43bf68c
2ba066a
 
43bf68c
2ba066a
 
43bf68c
c22ce58
2ba066a
c22ce58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()