Update app.py
Browse files
app.py
CHANGED
|
@@ -38,12 +38,18 @@ def prepare_predictor():
|
|
| 38 |
return str(predictor_root)
|
| 39 |
|
| 40 |
# Load the predictor with version mismatch allowed
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
# Define feature columns based on the actual model
|
| 49 |
FEATURE_COLS = [
|
|
@@ -92,64 +98,73 @@ def predict_book_recommendation(
|
|
| 92 |
based on its characteristics and reading status.
|
| 93 |
"""
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
# Create input dataframe with exact feature names
|
| 99 |
-
input_data = {
|
| 100 |
-
'FictionorNonfiction': fiction_code,
|
| 101 |
-
'NumPages': int(num_pages),
|
| 102 |
-
'ThicknessInches': float(thickness_inches),
|
| 103 |
-
'ReadUnfinishedorUnread': read_status
|
| 104 |
-
}
|
| 105 |
-
|
| 106 |
-
df_input = pd.DataFrame([input_data])
|
| 107 |
|
| 108 |
-
# Make prediction
|
| 109 |
-
prediction = predictor.predict(df_input)
|
| 110 |
-
raw_pred = prediction.iloc[0]
|
| 111 |
-
|
| 112 |
-
# Get prediction probabilities
|
| 113 |
try:
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
proba = proba.to_frame().T
|
| 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 |
# Define example inputs for demonstration
|
| 155 |
EXAMPLES = [
|
|
@@ -243,18 +258,23 @@ with gr.Blocks(
|
|
| 243 |
num_top_classes=2
|
| 244 |
)
|
| 245 |
|
| 246 |
-
# Examples section
|
| 247 |
gr.Markdown("---")
|
| 248 |
gr.Markdown("### π‘ Example Books")
|
| 249 |
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
|
| 259 |
# Model information
|
| 260 |
gr.Markdown("---")
|
|
|
|
| 38 |
return str(predictor_root)
|
| 39 |
|
| 40 |
# Load the predictor with version mismatch allowed
|
| 41 |
+
try:
|
| 42 |
+
PREDICTOR_DIR = prepare_predictor()
|
| 43 |
+
predictor = TabularPredictor.load(
|
| 44 |
+
PREDICTOR_DIR,
|
| 45 |
+
require_py_version_match=False,
|
| 46 |
+
require_version_match=False # Added this parameter to bypass version check
|
| 47 |
+
)
|
| 48 |
+
model_loaded = True
|
| 49 |
+
except Exception as e:
|
| 50 |
+
print(f"Error loading model: {e}")
|
| 51 |
+
model_loaded = False
|
| 52 |
+
predictor = None
|
| 53 |
|
| 54 |
# Define feature columns based on the actual model
|
| 55 |
FEATURE_COLS = [
|
|
|
|
| 98 |
based on its characteristics and reading status.
|
| 99 |
"""
|
| 100 |
|
| 101 |
+
if not model_loaded or predictor is None:
|
| 102 |
+
return "β οΈ Model is still loading or failed to load. Please refresh the page.", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
try:
|
| 105 |
+
# Encode categorical features
|
| 106 |
+
fiction_code = FICTION_NONFICTION_MAP[fiction_or_nonfiction]
|
|
|
|
| 107 |
|
| 108 |
+
# Create input dataframe with exact feature names
|
| 109 |
+
input_data = {
|
| 110 |
+
'FictionorNonfiction': fiction_code,
|
| 111 |
+
'NumPages': int(num_pages),
|
| 112 |
+
'ThicknessInches': float(thickness_inches),
|
| 113 |
+
'ReadUnfinishedorUnread': read_status
|
| 114 |
+
}
|
| 115 |
|
| 116 |
+
df_input = pd.DataFrame([input_data])
|
| 117 |
+
|
| 118 |
+
# Make prediction
|
| 119 |
+
prediction = predictor.predict(df_input)
|
| 120 |
+
raw_pred = prediction.iloc[0]
|
| 121 |
+
|
| 122 |
+
# Get prediction probabilities
|
| 123 |
+
try:
|
| 124 |
+
proba = predictor.predict_proba(df_input)
|
| 125 |
+
if isinstance(proba, pd.Series):
|
| 126 |
+
proba = proba.to_frame().T
|
| 127 |
+
|
| 128 |
+
# Format probabilities for display
|
| 129 |
+
proba_dict = {}
|
| 130 |
+
for cls in proba.columns:
|
| 131 |
+
label = OUTCOME_LABELS.get(cls, cls)
|
| 132 |
+
proba_dict[label] = float(proba.iloc[0][cls])
|
| 133 |
+
|
| 134 |
+
# Sort by probability
|
| 135 |
+
proba_dict = dict(sorted(proba_dict.items(), key=lambda x: x[1], reverse=True))
|
| 136 |
+
except Exception as e:
|
| 137 |
+
print(f"Error getting probabilities: {e}")
|
| 138 |
+
proba_dict = None
|
| 139 |
+
|
| 140 |
+
# Format prediction label
|
| 141 |
+
pred_label = OUTCOME_LABELS.get(raw_pred, raw_pred)
|
| 142 |
+
|
| 143 |
+
# Create detailed output
|
| 144 |
+
output_md = f"## π Prediction Result\n\n"
|
| 145 |
+
output_md += f"### **{pred_label}**\n\n"
|
| 146 |
+
|
| 147 |
+
if proba_dict:
|
| 148 |
+
confidence = max(proba_dict.values()) * 100
|
| 149 |
+
output_md += f"**Confidence:** {confidence:.1f}%\n\n"
|
| 150 |
+
output_md += "### Probability Distribution:\n"
|
| 151 |
+
for label, prob in proba_dict.items():
|
| 152 |
+
bar_length = int(prob * 20)
|
| 153 |
+
bar = 'β' * bar_length + 'β' * (20 - bar_length)
|
| 154 |
+
output_md += f"- {label}: {bar} {prob*100:.1f}%\n"
|
| 155 |
+
|
| 156 |
+
# Add interpretation
|
| 157 |
+
output_md += "\n### π Input Summary:\n"
|
| 158 |
+
output_md += f"- **Genre:** {fiction_or_nonfiction}\n"
|
| 159 |
+
output_md += f"- **Length:** {int(num_pages)} pages ({thickness_inches:.1f} inches thick)\n"
|
| 160 |
+
output_md += f"- **Reading Status:** {read_status}\n"
|
| 161 |
+
|
| 162 |
+
return output_md, proba_dict
|
| 163 |
|
| 164 |
+
except Exception as e:
|
| 165 |
+
error_msg = f"β οΈ Error making prediction: {str(e)}"
|
| 166 |
+
print(error_msg)
|
| 167 |
+
return error_msg, None
|
| 168 |
|
| 169 |
# Define example inputs for demonstration
|
| 170 |
EXAMPLES = [
|
|
|
|
| 258 |
num_top_classes=2
|
| 259 |
)
|
| 260 |
|
| 261 |
+
# Examples section - Modified to avoid caching issues
|
| 262 |
gr.Markdown("---")
|
| 263 |
gr.Markdown("### π‘ Example Books")
|
| 264 |
|
| 265 |
+
try:
|
| 266 |
+
gr.Examples(
|
| 267 |
+
examples=EXAMPLES,
|
| 268 |
+
inputs=[fiction_input, pages_input, thickness_input, read_input],
|
| 269 |
+
outputs=[output_text, output_proba],
|
| 270 |
+
fn=predict_book_recommendation,
|
| 271 |
+
label="Click any example to try it:",
|
| 272 |
+
examples_per_page=6,
|
| 273 |
+
cache_examples=False # Disable caching to avoid startup errors
|
| 274 |
+
)
|
| 275 |
+
except Exception as e:
|
| 276 |
+
print(f"Error creating examples: {e}")
|
| 277 |
+
gr.Markdown("*Examples could not be loaded*")
|
| 278 |
|
| 279 |
# Model information
|
| 280 |
gr.Markdown("---")
|