in the following code replace gr.Radio with option "Да" and "Нет" as a table:
|Критерий|Да|Нет|
|Находится ли вблизи жилого района с высоким пешеходным трафиком|||
|..|..|..|
import gradio as gr
import requests
from constants import *
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from omegaconf import OmegaConf
with gr.Blocks() as interface:
with gr.Tabs():
with gr.TabItem("Стоимость недвижимости"):
gr.Markdown(f"""
# {config.TITLE}
### {config.DESCRIPTION}
""")
code
Assistant
with gr.Row():
with gr.Column():
with gr.Accordion(config.LOCATION_SECTION):
inputs = []
inputs.append(gr.Dropdown(choices=metro_values, label="Метро"))
inputs.append(gr.Dropdown(choices=okrug_values, label="Округ"))
inputs.append(gr.Dropdown(choices=city_values, label="Город"))
with gr.Accordion(config.DETAILS_SECTION):
inputs.append(gr.Dropdown(choices=category_values, label="Категория объявления"))
inputs.append(gr.Dropdown(choices=condition_values, label="Состояние"))
inputs.append(gr.Slider(label='Общая площадь (м²)', minimum=10, maximum=800, value=30, step=1))
inputs.append(gr.Slider(label='Этаж', minimum=1, maximum=100, value=2, step=1))
inputs.append(gr.Slider(label='Этажность дома', minimum=1, maximum=100, value=5, step=1))
with gr.Column():
with gr.Accordion(config.TRANSPORT_SECTION):
inputs.append(gr.Slider(label='Время до станции (минуты)', minimum=1, maximum=60, value=5, step=1))
inputs.append(gr.Dropdown(choices=transport_values, value="пешком", label='До станции'))
with gr.Accordion("Адрес"):
inputs.append(gr.Dropdown(choices=city_values, label="Город"))
inputs.append(gr.Dropdown(choices=okrug_values, label="Округ"))
inputs.append(gr.Textbox(label='Улица'))
inputs.append(gr.Number(label='Номер дома'))
inputs.append(gr.Number(label='Почтовый индекс'))
with gr.Accordion(config.MODEL_SELECTION_SECTION):
model_selection = gr.Radio(choices=["xgb_1", "xgb_2", "mlp_1"], label="Выберите модель")
gr.Markdown("---")
output_price = gr.Textbox(label="Предсказанная цена за м²")
output_max_price = gr.Textbox(label="Максимальная цена за м² в радиусе")
output_min_price = gr.Textbox(label="Минимальная цена за м² в радиусе")
submit_btn = gr.Button(config.PREDICT_BUTTON_LABEL, variant="primary")
submit_btn.click(fn=predict_user_input, inputs=inputs + [model_selection], outputs=[output_price, output_max_price, output_min_price])
gr.Markdown(config.LOADING_MESSAGE)
with gr.TabItem("Проверка требований сетевых арендаторов"):
gr.Markdown("## Проверка требований сетевых арендаторов")
with gr.Tabs():
with gr.TabItem("Проверка объекта недвижимости"):
facility_inputs = [
gr.Number(label='Общая площадь (м²)', minimum=1),
gr.Number(label='Этаж', minimum=0),
gr.Radio(choices=["Да", "Нет"], label='Находится ли вблизи жилого района с высоким пешеходным трафиком'),
gr.Radio(choices=["Да", "Нет"], label='Имеет ли высокий пешеходный трафик рядом'),
gr.Radio(choices=["Да", "Нет"], label='Имеет ли высокий автомобильный трафик рядом'),
gr.Radio(choices=["Да", "Нет"], label='Есть ли в пределах 100 метров детские, образовательные, спортивные или медицинские учреждения'),
gr.Radio(choices=["Да", "Нет"], label='Есть ли все необходимые коммуникации (вода, электричество, канализация и т. д.)'),
gr.Radio(choices=["Да", "Нет"], label='Есть ли у объекта санитарный узел (туалет)'),
gr.Radio(choices=["Да", "Нет"], label='Ожидается ли, что объект будет иметь как минимум 20,000 посетителей в день (для ТЦ)'),
gr.Radio(choices=["Да", "Нет"], label='Есть ли возможность разгрузки грузового транспорта на месте'),
gr.Number(label='Высота потолков (м)', minimum=0),
gr.Radio(choices=["Да", "Нет"], label='Имеется ли парковка у объекта недвижимости')
]
facility_output = gr.Textbox(label="Результат проверки")
facility_submit_btn = gr.Button("Проверить объект")
facility_submit_btn.click(fn=check_facility_eligibility, inputs=facility_inputs, outputs=facility_output)
with gr.TabItem("Проверка земельного участка"):
land_inputs = [
gr.Number(label='Площадь земельного участка (м²)', minimum=0),
gr.Radio(choices=["Да", "Нет"], label='Близость к жилому сектору с высоким пешеходным трафиком'),
gr.Radio(choices=["Да", "Нет"], label='Высокий автомобильный трафик'),
gr.Radio(choices=["Да", "Нет"], label='Наличие всех коммуникаций')
]
land_output = gr.Textbox(label="Результат проверки")
land_submit_btn = gr.Button("Проверить участок")
land_submit_btn.click(fn=check_land_eligibility, inputs=land_inputs, outputs=land_output)
our goal is to reduce deplication of "Да" and "Нет"
To streamline your Gradio interface and reduce the duplication of the "Да" and "Нет" radio buttons, you can structure your criteria into tables. While Gradio doesn't support native table components with interactive elements, you can emulate a table layout using gr.Row and gr.Column effectively. Additionally, by programmatically generating the radio buttons from a list of criteria, you can significantly reduce code repetition.
Here's how you can achieve this:
Define Criteria Lists: Create lists containing all the criteria for both "Проверка объекта недвижимости" and "Проверка земельного участка".
Generate Radio Buttons Dynamically: Use list comprehensions or loops to generate gr.Radio components for each criterion.
Arrange Components in a Table-Like Layout: Use gr.Row and gr.Column to mimic a table structure, aligning criteria labels with their corresponding "Да" and "Нет" options.
Below is the refactored code implementing these steps:
python
import gradio as gr
import requests
from constants import *
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from omegaconf import OmegaConf
# Load configuration from config.yaml
config = OmegaConf.load("./src/app/conf/config.yaml")
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
def predict_user_input(*user_input_values):
user_input_keys = [
"Метро", "Округ", "Город", "Категория объявления", "Состояние",
"Общая площадь", "Этаж", "Этажность дома", "Время до станции",
"пешком/транспортом", "Город", "Округ", "Улица", "Номер дома",
"Почтовый индекс", "model"
]
user_input = dict(zip(user_input_keys, user_input_values))
response = requests.post("http://localhost:8000/predict/", json=user_input)
predicted_price = response.json()["predicted_price_per_sqm"]
location_request = {
"latitude": user_input.get("latitude"),
"longitude": user_input.get("longitude"),
"radius": 1 # Assuming a radius of 1 km for the example
}
response = requests.post("http://localhost:8000/prices_in_radius", json=location_request)
prices = response.json()
max_price = max(prices) if prices else None
min_price = min(prices) if prices else None
return predicted_price, max_price, min_price
def check_facility_eligibility(input_data):
response = requests.post("http://localhost:8000/check/facility", json=input_data)
return response.json()["eligible_categories"]
def check_land_eligibility(input_data):
response = requests.post("http://localhost:8000/check/land", json=input_data)
return response.json()["eligible_categories"]
# Define criteria for "Проверка объекта недвижимости"
facility_criteria = [
'Находится ли вблизи жилого района с высоким пешеходным трафиком',
'Имеет ли высокий пешеходный трафик рядом',
'Имеет ли высокий автомобильный трафик рядом',
'Есть ли в пределах 100 метров детские, образовательные, спортивные или медицинские учреждения',
'Есть ли все необходимые коммуникации (вода, электричество, канализация и т. д.)',
'Есть ли у объекта санитарный узел (туалет)',
'Ожидается ли, что объект будет иметь как минимум 20,000 посетителей в день (для ТЦ)',
'Есть ли возможность разгрузки грузового транспорта на месте',
'Имеется ли парковка у объекта недвижимости'
]
# Define criteria for "Проверка земельного участка"
land_criteria = [
'Близость к жилому сектору с высоким пешеходным трафиком',
'Высокий автомобильный трафик',
'Наличие всех коммуникаций'
]
with gr.Blocks() as interface:
with gr.Tabs():
with gr.TabItem("Стоимость недвижимости"):
gr.Markdown(f"""
# {config.TITLE}
### {config.DESCRIPTION}
""")
with gr.Row():
with gr.Column():
with gr.Accordion(config.LOCATION_SECTION):
inputs = []
inputs.append(gr.Dropdown(choices=metro_values, label="Метро"))
inputs.append(gr.Dropdown(choices=okrug_values, label="Округ"))
inputs.append(gr.Dropdown(choices=city_values, label="Город"))
with gr.Accordion(config.DETAILS_SECTION):
inputs.append(gr.Dropdown(choices=category_values, label="Категория объявления"))
inputs.append(gr.Dropdown(choices=condition_values, label="Состояние"))
inputs.append(gr.Slider(label='Общая площадь (м²)', minimum=10, maximum=800, value=30, step=1))
inputs.append(gr.Slider(label='Этаж', minimum=1, maximum=100, value=2, step=1))
inputs.append(gr.Slider(label='Этажность дома', minimum=1, maximum=100, value=5, step=1))
with gr.Column():
with gr.Accordion(config.TRANSPORT_SECTION):
inputs.append(gr.Slider(label='Время до станции (минуты)', minimum=1, maximum=60, value=5, step=1))
inputs.append(gr.Dropdown(choices=transport_values, value="пешком", label='До станции'))
with gr.Accordion("Адрес"):
inputs.append(gr.Dropdown(choices=city_values, label="Город"))
inputs.append(gr.Dropdown(choices=okrug_values, label="Округ"))
inputs.append(gr.Textbox(label='Улица'))
inputs.append(gr.Number(label='Номер дома'))
inputs.append(gr.Number(label='Почтовый индекс'))
with gr.Accordion(config.MODEL_SELECTION_SECTION):
model_selection = gr.Radio(choices=["xgb_1", "xgb_2", "mlp_1"], label="Выберите модель")
gr.Markdown("---")
output_price = gr.Textbox(label="Предсказанная цена за м²")
output_max_price = gr.Textbox(label="Максимальная цена за м² в радиусе")
output_min_price = gr.Textbox(label="Минимальная цена за м² в радиусе")
submit_btn = gr.Button(config.PREDICT_BUTTON_LABEL, variant="primary")
submit_btn.click(fn=predict_user_input, inputs=inputs + [model_selection], outputs=[output_price, output_max_price, output_min_price])
gr.Markdown(config.LOADING_MESSAGE)
with gr.TabItem("Проверка требований сетевых арендаторов"):
gr.Markdown("## Проверка требований сетевых арендаторов")
with gr.Tabs():
with gr.TabItem("Проверка объекта недвижимости"):
facility_inputs = []
# Create table headers
with gr.Row():
gr.Markdown("### Проверка объекта недвижимости")
with gr.Row():
gr.Markdown("**Критерий**", elem_id="criteria-header")
gr.Markdown("**Да**", elem_id="yes-header")
gr.Markdown("**Нет**", elem_id="no-header")
# Generate radio buttons dynamically
for criterion in facility_criteria:
with gr.Row():
gr.Markdown(criterion)
radio = gr.Radio(choices=["Да", "Нет"], label="", inline=True)
facility_inputs.append(radio)
facility_output = gr.Textbox(label="Результат проверки")
facility_submit_btn = gr.Button("Проверить объект")
facility_submit_btn.click(fn=check_facility_eligibility, inputs=facility_inputs, outputs=facility_output)
with gr.TabItem("Проверка земельного участка"):
land_inputs = []
# Create table headers
with gr.Row():
gr.Markdown("### Проверка земельного участка")
with gr.Row():
gr.Markdown("**Критерий**", elem_id="criteria-header")
gr.Markdown("**Да**", elem_id="yes-header")
gr.Markdown("**Нет**", elem_id="no-header")
# Generate radio buttons dynamically
for criterion in land_criteria:
with gr.Row():
gr.Markdown(criterion)
radio = gr.Radio(choices=["Да", "Нет"], label="", inline=True)
land_inputs.append(radio)
land_output = gr.Textbox(label="Результат проверки")
land_submit_btn = gr.Button("Проверить участок")
land_submit_btn.click(fn=check_land_eligibility, inputs=land_inputs, outputs=land_output)
# Optional: Add some CSS to style headers to align them like a table
interface.load(lambda: None, None, None, _js="""
() => {
const style = document.createElement('style');
style.innerHTML = `
#criteria-header, #yes-header, #no-header {
font-weight: bold;
padding: 10px;
}
.gradio-row {
align-items: center;
}
.gradio-row > div:first-child {
flex: 3;
}
.gradio-row > div:last-child {
flex: 1;
}
`;
document.head.appendChild(style);
}
""")
interface.launch(server_name="localhost", server_port=8080, debug=True)
Explanation of Changes
Criteria Lists:
Defined two lists, facility_criteria and land_criteria, containing all the criteria for "Проверка объекта недвижимости" and "Проверка земельного участка" respectively. This approach allows for easier management and scalability of criteria.
Dynamic Generation of Radio Buttons:
Used a for loop to iterate over each criterion in the lists and create a corresponding gr.Radio component with choices "Да" and "Нет". This removes the repetitive code where each gr.Radio was manually instantiated.
Table-Like Layout:
Emulated a table structure by using gr.Row for each criterion. The first column displays the criterion description, while the second and third columns provide the "Да" and "Нет" radio buttons side by side.
Added headers using gr.Markdown with bold formatting to resemble table headers.
Styling (Optional):
Included a gr.HTML block to inject some CSS for better alignment and presentation of the pseudo-table. This step enhances the visual structure, making it more table-like.
Consistent Labeling:
Removed labels from individual gr.Radio components since the headers already describe the purpose of the radio buttons. This avoids redundancy and keeps the interface clean.
Benefits of This Approach
Reduced Code Duplication: By programmatically generating the radio buttons from lists, the code becomes more maintainable and less error-prone.
Scalability: Adding or removing criteria now only involves updating the respective lists, without modifying the UI construction logic.
Improved Readability: The table-like layout enhances the user experience by organizing related options neatly, making it easier for users to understand and interact with the form.
Additional Enhancements
Validation: You might want to add validation to ensure all criteria are answered before submitting the form.
Styling: Further CSS adjustments can be made to improve the responsiveness and aesthetics of the table layout.
Accessibility: Ensure that the interface is accessible to all users by adding appropriate labels and focus management.
Feel free to adjust the styling and layout further to match your specific design requirements.