Spaces:
Running
Running
# -*- coding: utf-8 -*- | |
"""app.ipynb | |
Automatically generated by Colab. | |
Original file is located at | |
https://colab.research.google.com/drive/1EyjV73NmmvRi7U_r_GxUjz4X-5-6yMgE | |
""" | |
# load_and_run_pkl_model.py | |
# This script ONLY loads a pre-saved PKL file and runs a Gradio interface for it. | |
import gradio as gr | |
import pickle | |
import os | |
# --- Dependencies required ONLY for the class definition used by pickle --- | |
# We are NOT calling pipeline() here to load models from Hugging Face. | |
# Pickle just needs to know the *structure* of the saved object. | |
from transformers import pipeline | |
import torch | |
# --- Define the Class Structure --- | |
# IMPORTANT: This MUST exactly match the class definition used when | |
# the .pkl file was SAVED. Pickle needs this to reconstruct the object. | |
# --- Configuration: Path to your saved PKL file --- | |
PICKLE_FILENAME = "combined_analyzer.pkl" | |
MODEL_DIR = "saved_model" # Directory where the PKL file is located | |
PICKLE_FILEPATH = os.path.join(MODEL_DIR, PICKLE_FILENAME) | |
# --- Global Variable to hold the loaded analyzer --- | |
LOADED_ANALYZER = None | |
LOAD_ERROR_MESSAGE = None | |
# --- Load the Saved Model from PKL File --- | |
print("-" * 40) | |
print(f"Attempting to load analyzer object from: {PICKLE_FILEPATH}") | |
try: | |
# Security Note: Only unpickle files you trust. | |
if not os.path.exists(PICKLE_FILEPATH): | |
raise FileNotFoundError(f"Cannot find the model file at '{PICKLE_FILEPATH}'. Make sure it exists.") | |
with open(PICKLE_FILEPATH, 'rb') as f: | |
# The actual loading happens here | |
LOADED_ANALYZER = pickle.load(f) | |
# Validate the loaded object (basic check) | |
if not isinstance(LOADED_ANALYZER, CombinedAnalyzer) or not callable(getattr(LOADED_ANALYZER, 'analyze', None)): | |
LOADED_ANALYZER = None # Invalidate if it's not the right type or lacks the method | |
raise TypeError("The loaded object from the PKL file is not a valid 'CombinedAnalyzer' instance or is corrupted.") | |
else: | |
print(">>> Successfully loaded analyzer object from PKL file.") | |
except Exception as e: | |
LOAD_ERROR_MESSAGE = f"ERROR: Failed to load model from '{PICKLE_FILEPATH}'.\nDetails: {e}" | |
print(LOAD_ERROR_MESSAGE) | |
LOADED_ANALYZER = None # Ensure it's None if any error occurred | |
print("-" * 40) | |
# --- Gradio Function (Uses the globally loaded object) --- | |
def perform_analysis(input_text): | |
"""This function is called by the Gradio interface.""" | |
if LOADED_ANALYZER is None: | |
# If loading failed earlier, return the error message | |
return LOAD_ERROR_MESSAGE or "Error: Analyzer model is not loaded." | |
if not input_text or not input_text.strip(): | |
return "Please enter some text to analyze." | |
# Use the 'analyze' method of the object loaded from the PKL file | |
try: | |
results = LOADED_ANALYZER.analyze(input_text) | |
return results | |
except Exception as e: | |
# Catch errors during the analysis itself | |
print(f"Error during analysis execution: {e}") | |
return f"An error occurred during analysis:\n{e}" | |
# --- Create the Gradio Interface --- | |
gradio_app_description = f"Enter text to analyze using the model loaded from `{PICKLE_FILEPATH}`." | |
if LOADED_ANALYZER is None: | |
gradio_app_description += "\n\n**WARNING: Model failed to load. Analysis will not function.**" | |
interface = gr.Interface( | |
fn=perform_analysis, # The function that runs the analysis | |
inputs=gr.Textbox(lines=8, placeholder="Enter text here...", label="Input Text"), | |
outputs=gr.Textbox(lines=8, label="Analysis Results", interactive=False), | |
title="Analyze Text with Saved Model", | |
description=gradio_app_description, | |
allow_flagging='never' | |
) | |
# --- Launch the Gradio App --- | |
if __name__ == "__main__": | |
print("Launching Gradio interface...") | |
if LOADED_ANALYZER is None: | |
print("!!! Warning: Launching interface, but model loading failed. Check errors above. !!!") | |
interface.launch() |