yusenthebot commited on
Commit
c6eef8c
Β·
verified Β·
1 Parent(s): 716bda8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -68
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
- PREDICTOR_DIR = prepare_predictor()
42
- predictor = TabularPredictor.load(
43
- PREDICTOR_DIR,
44
- require_py_version_match=False,
45
- require_version_match=False # Added this parameter to bypass version check
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
- # Encode categorical features
96
- fiction_code = FICTION_NONFICTION_MAP[fiction_or_nonfiction]
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
- proba = predictor.predict_proba(df_input)
115
- if isinstance(proba, pd.Series):
116
- proba = proba.to_frame().T
117
 
118
- # Format probabilities for display
119
- proba_dict = {}
120
- for cls in proba.columns:
121
- label = OUTCOME_LABELS.get(cls, cls)
122
- proba_dict[label] = float(proba.iloc[0][cls])
 
 
123
 
124
- # Sort by probability
125
- proba_dict = dict(sorted(proba_dict.items(), key=lambda x: x[1], reverse=True))
126
- except Exception as e:
127
- print(f"Error getting probabilities: {e}")
128
- proba_dict = None
129
-
130
- # Format prediction label
131
- pred_label = OUTCOME_LABELS.get(raw_pred, raw_pred)
132
-
133
- # Create detailed output
134
- output_md = f"## πŸ“š Prediction Result\n\n"
135
- output_md += f"### **{pred_label}**\n\n"
136
-
137
- if proba_dict:
138
- confidence = max(proba_dict.values()) * 100
139
- output_md += f"**Confidence:** {confidence:.1f}%\n\n"
140
- output_md += "### Probability Distribution:\n"
141
- for label, prob in proba_dict.items():
142
- bar_length = int(prob * 20)
143
- bar = 'β–ˆ' * bar_length + 'β–‘' * (20 - bar_length)
144
- output_md += f"- {label}: {bar} {prob*100:.1f}%\n"
145
-
146
- # Add interpretation
147
- output_md += "\n### πŸ“Š Input Summary:\n"
148
- output_md += f"- **Genre:** {fiction_or_nonfiction}\n"
149
- output_md += f"- **Length:** {int(num_pages)} pages ({thickness_inches:.1f} inches thick)\n"
150
- output_md += f"- **Reading Status:** {read_status}\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
 
152
- return output_md, proba_dict
 
 
 
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
- gr.Examples(
251
- examples=EXAMPLES,
252
- inputs=[fiction_input, pages_input, thickness_input, read_input],
253
- outputs=[output_text, output_proba],
254
- fn=predict_book_recommendation,
255
- label="Click any example to try it:",
256
- examples_per_page=6,
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("---")