Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import pandas as pd
|
3 |
+
from huggingface_hub import hf_hub_download
|
4 |
+
import joblib
|
5 |
+
from geopy.geocoders import Nominatim
|
6 |
+
from geopy.exc import GeocoderTimedOut, GeocoderUnavailable
|
7 |
+
import time
|
8 |
+
|
9 |
+
# Загрузка модели
|
10 |
+
model_path = hf_hub_download(repo_id="Nikgorby/diplom_DS_SF", filename="random_forest_model (1).pkl")
|
11 |
+
model = joblib.load(model_path)
|
12 |
+
|
13 |
+
# with open('/home/dwarf/diplom/models/random_forest_model (1).pkl', 'rb') as file:
|
14 |
+
# model = joblib.load(file)
|
15 |
+
|
16 |
+
def predict(features_lst, model):
|
17 |
+
"""
|
18 |
+
Purpose: arg
|
19 |
+
"""
|
20 |
+
# Предсказание
|
21 |
+
predictions = model.predict(features_lst)
|
22 |
+
|
23 |
+
return predictions
|
24 |
+
# end def
|
25 |
+
|
26 |
+
def addr_to_coords(addr: str):
|
27 |
+
"""Функция получения координат по адресу
|
28 |
+
|
29 |
+
Args:
|
30 |
+
addr (str): Строка с адресом
|
31 |
+
|
32 |
+
Returns:
|
33 |
+
float: координаты широта, долгота
|
34 |
+
"""
|
35 |
+
geolocator = Nominatim(user_agent="my_geocoder", scheme='http', timeout=10)
|
36 |
+
|
37 |
+
# Геокодирование адреса
|
38 |
+
try:
|
39 |
+
# попытка получения координат
|
40 |
+
location = geolocator.geocode(addr)
|
41 |
+
if (location):
|
42 |
+
# координаты получены
|
43 |
+
return location.latitude, location.longitude
|
44 |
+
else:
|
45 |
+
# координаты не получены
|
46 |
+
return 0, 0
|
47 |
+
# end if
|
48 |
+
except (GeocoderTimedOut, GeocoderUnavailable) as e:
|
49 |
+
print(f"Error: {e}. Retrying...")
|
50 |
+
time.sleep(2) # Добавляем задержку перед повторной попыткой
|
51 |
+
return addr_to_coords(addr)
|
52 |
+
# end try
|
53 |
+
|
54 |
+
# Определение функции предсказания
|
55 |
+
def predict_out(baths, square, beds, address, pool, property_type, state, year_built, remodeled_year, avg_school_rating, schools_qty, avg_school_dist):
|
56 |
+
"""Функция получения предсказания от модели
|
57 |
+
|
58 |
+
Args:
|
59 |
+
csv_file (csv-файл с фичами): файл формата csv
|
60 |
+
|
61 |
+
Returns:
|
62 |
+
float: предсказание модели
|
63 |
+
"""
|
64 |
+
# Загрузка модели
|
65 |
+
# with open('/home/dwarf/diplom/models/random_forest_model (1).pkl', 'rb') as file:
|
66 |
+
# model = joblib.load(file)
|
67 |
+
|
68 |
+
# Формирование списка фичей
|
69 |
+
|
70 |
+
# Формирование признака объекта
|
71 |
+
lst = [0]*8
|
72 |
+
lst[property_type] = 1
|
73 |
+
property_type = ", ".join(map(str, lst))
|
74 |
+
|
75 |
+
# Преобразование адреса в координаты
|
76 |
+
coords = addr_to_coords(address)
|
77 |
+
coords = ", ".join(map(str, coords))
|
78 |
+
|
79 |
+
features_lst = f'{baths}, {square}, {beds}, {coords}, {pool}, {property_type}, {state}, {year_built}, {remodeled_year}, {avg_school_rating}, {schools_qty}, {avg_school_dist}'
|
80 |
+
features_lst = features_lst.split(", ")
|
81 |
+
features_lst = [float(num) for num in features_lst]
|
82 |
+
features_lst = [features_lst]
|
83 |
+
|
84 |
+
# # Считывание CSV файла
|
85 |
+
# data = pd.read_csv(csv_file.name)
|
86 |
+
|
87 |
+
# Предсказание
|
88 |
+
predictions = predict(features_lst, model)
|
89 |
+
|
90 |
+
# Возвращение предсказаний в виде DataFrame
|
91 |
+
result = predictions[0]
|
92 |
+
# # result = pd.DataFrame(predictions, columns=["Prediction"])
|
93 |
+
return features_lst, result
|
94 |
+
|
95 |
+
# Создание интерфейса Gradio
|
96 |
+
title = "Interactive gradio demo"
|
97 |
+
description = "Демо модели."
|
98 |
+
|
99 |
+
iface = gr.Interface(
|
100 |
+
fn=predict_out,
|
101 |
+
inputs=[gr.Textbox(label="Кол-во ванных"),
|
102 |
+
gr.Textbox(label="Площадь"),
|
103 |
+
gr.Textbox(label="Кол-во спален"),
|
104 |
+
gr.Textbox(label="Адрес"),
|
105 |
+
gr.Radio(
|
106 |
+
["Нет", "Да"], type="index",
|
107 |
+
label = "Бассейн"
|
108 |
+
),
|
109 |
+
gr.Dropdown(
|
110 |
+
["Кондоминиум", "Зем. участок", "На неск. семей", "Другое", "Ранчо", "На одну семью", "Таунхаус", "Традиционное"],
|
111 |
+
label='Тип объекта',
|
112 |
+
type="index"
|
113 |
+
),
|
114 |
+
gr.Textbox(label='Штат (номер)'),
|
115 |
+
gr.Textbox(label="Год постройки"),
|
116 |
+
gr.Textbox(label="Год капитального ремонта"),
|
117 |
+
gr.Textbox(label="Средний рейтинг школ рядом"),
|
118 |
+
gr.Textbox(label="Количество школ рядом"),
|
119 |
+
gr.Textbox(label="Среднее расстояние до школы"),
|
120 |
+
],
|
121 |
+
outputs=[gr.Textbox(label="Features"),
|
122 |
+
gr.Textbox(label="Предсказание")],
|
123 |
+
title=title,
|
124 |
+
description=description,
|
125 |
+
allow_flagging='never'
|
126 |
+
)
|
127 |
+
|
128 |
+
# Запуск приложения
|
129 |
+
iface.launch()
|