Spaces:
Runtime error
Runtime error
Update app.py
Browse files1 unmodified line234567891011121314151 unmodified line171819202122232425262728293031323334353637383940414243444546474849505152535455565758593 unmodified lines63646566676869701 unmodified lineimport gradio as grimport torchfrom concurrent.futures import ThreadPoolExecutor# Load models with quantization (8-bit) for faster inferencedef load_quantized_model(model_name):model = AutoModelForSequenceClassification.from_pretrained(model_name, load_in_8bit=True)tokenizer = AutoTokenizer.from_pretrained(model_name)return pipeline("text-classification", model=model, tokenizer=tokenizer, device=0 if torch.cuda.is_available() else -1)# Load models in parallel during startupwith ThreadPoolExecutor() as executor:sentiment_future = executor.submit(load_quantized_model, "cardiffnlp/twitter-roberta-base-sentiment")emotion_future = executor.submit(load_quantized_model, "bhadresh-savani/bert-base-uncased-emotion")1 unmodified linesentiment_pipeline = sentiment_future.result()emotion_pipeline = emotion_future.result()# Cache recent predictions to avoid recomputationCACHE_SIZE = 100prediction_cache = {}def analyze_text(text):# Check cache firstif text in prediction_cache:return prediction_cache[text]# Parallel model executionwith ThreadPoolExecutor() as executor:sentiment_future = executor.submit(sentiment_pipeline, text)emotion_future = executor.submit(emotion_pipeline, text)sentiment_result = sentiment_future.result()[0]emotion_result = emotion_future.result()[0]# Format responseresult = {"Sentiment": {sentiment_result['label']: round(sentiment_result['score'], 4)},"Emotion": {emotion_result['label']: round(emotion_result['score'], 4)}}# Update cacheif len(prediction_cache) >= CACHE_SIZE:prediction_cache.pop(next(iter(prediction_cache)))prediction_cache[text] = resultreturn result# Optimized Gradio interface with batch processingdemo = gr.Interface(fn=analyze_text,inputs=gr.Textbox(placeholder="Enter your text here...", label="Input Text"),outputs=gr.Label(label="Analysis Results"),title="🚀 Fast Sentiment & Emotion Analysis",description="Optimized version using quantized models and parallel processing",examples=[["I'm thrilled to start this new adventure!"],["This situation is making me really frustrated."],3 unmodified linesallow_flagging="never")# Warm up models with sample inputanalyze_text("Warming up models...")if __name__ == "__main__":demo.launch()1 unmodified line23456789101112131415161718192021222324252627281 unmodified line303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374753 unmodified lines79808182838485861 unmodified lineimport gradio as grimport torchfrom concurrent.futures import ThreadPoolExecutorfrom threading import Lock# Global cache settings and lock for thread-safetyCACHE_SIZE = 100prediction_cache = {}cache_lock = Lock()# Function to load models with 8-bit quantizationdef load_quantized_model(model_name):try:model = AutoModelForSequenceClassification.from_pretrained(model_name, load_in_8bit=True)tokenizer = AutoTokenizer.from_pretrained(model_name)device = 0 if torch.cuda.is_available() else -1pipe = pipeline("text-classification", model=model, tokenizer=tokenizer, device=device)print(f"Loaded model: {model_name}")return pipeexcept Exception as e:print(f"Error loading model '{model_name}': {e}")raise e# Load both models concurrently at startupwith ThreadPoolExecutor() as executor:sentiment_future = executor.submit(load_quantized_model, "cardiffnlp/twitter-roberta-base-sentiment")emotion_future = executor.submit(load_quantized_model, "bhadresh-savani/bert-base-uncased-emotion")1 unmodified linesentiment_pipeline = sentiment_future.result()emotion_pipeline = emotion_future.result()def analyze_text(text):# Check cache first (using lock for thread-safety)with cache_lock:if text in prediction_cache:return prediction_cache[text]try:# Execute both model inferences in parallelwith ThreadPoolExecutor() as executor:sentiment_future = executor.submit(sentiment_pipeline, text)emotion_future = executor.submit(emotion_pipeline, text)sentiment_result = sentiment_future.result()[0]emotion_result = emotion_future.result()[0]# Prepare a clear, rounded outputresult = {"Sentiment": {sentiment_result['label']: round(sentiment_result['score'], 4)},"Emotion": {emotion_result['label']: round(emotion_result['score'], 4)}}except Exception as e:result = {"error": str(e)}# Update cache with lock protectionwith cache_lock:if len(prediction_cache) >= CACHE_SIZE:prediction_cache.pop(next(iter(prediction_cache)))prediction_cache[text] = resultreturn result# Gradio interface: using gr.JSON to display structured outputdemo = gr.Interface(fn=analyze_text,inputs=gr.Textbox(placeholder="Enter your text here...", label="Input Text"),outputs=gr.JSON(label="Analysis Results"),title="🚀 Fast Sentiment & Emotion Analysis",description="An optimized application using 8-bit quantized models and parallel processing for fast inference.",examples=[["I'm thrilled to start this new adventure!"],["This situation is making me really frustrated."],3 unmodified linesallow_flagging="never")# Warm up the models with a sample input to reduce first-call latency_ = analyze_text("Warming up models...")if __name__ == "__main__":demo.launch()
app.py+51-35