Spaces:
Sleeping
Sleeping
YashaswiAbhinav commited on
Commit ·
fc70850
1
Parent(s): 745bdd0
Fix syntax in requirements.txt for proper package installation
Browse files11 unmodified lines12131415161718192021222324252627282930311 unmodified line333435363738394041424344454610 unmodified lines5758596061626364656667686970717273741 unmodified line767778798081828384858687888990919293949596979899100101102103104105106184 unmodified lines29129229329411 unmodified linesimport requestsimport datetimeimport osfrom models import LSTMClassifier # Import from models.pyos.environ['TRANSFORMERS_CACHE'] = '/tmp/cache/'# Required for DistilBERTfrom transformers import DistilBertTokenizer, DistilBertForSequenceClassificationimport torchimport tensorflow as tftorch.set_default_device('cpu')tf.config.set_visible_devices([], 'GPU')app = Flask(__name__)CORS(app)# Model loadingBASE_DIR = os.path.dirname(os.path.abspath(__file__))combined_model_path1 = os.path.join(BASE_DIR, "models", "combined_model.pkl")combined_model_path2 = os.path.join(BASE_DIR, "models", "combined_model_true.pkl")1 unmodified linetry:combined_model1 = joblib.load(combined_model_path1)combined_model2 = joblib.load(combined_model_path2)print("Combined models loaded successfully.")except Exception as e:print("Error loading models:", e)exit()# -------------------------------------------------# 3. Function to extract individual components# -------------------------------------------------def get_model_components(model_dict):return (model_dict["tfidf"],10 unmodified linescomponents1 = get_model_components(combined_model1)components2 = get_model_components(combined_model2)device = torch.device("cpu") # Use CPU for Hugging Face Spaces (no GPU in free tier)# -------------------------------------------------# 4. Preprocessing and Prediction Functions# -------------------------------------------------def preprocess_text(text):"""Clean and preprocess text for model input."""if not isinstance(text, str): # Handle non-string inputstext = str(text)text = re.sub(r'[^\w\s]', '', text.lower()) # Remove punctuation, lowercasetext = re.sub(r'\s+', ' ', text).strip() # Remove extra whitespacereturn textdef predict_lr_prob(tfidf, lr_model, text):vec = tfidf.transform([preprocess_text(text)])1 unmodified linedef predict_rf_prob(tfidf, svd, rf_model, text):vec = tfidf.transform([preprocess_text(text)])vec_reduced = svd.transform(vec)return rf_model.predict_proba(vec_reduced)[0][1]def predict_lstm_prob(tokenizer_lstm, lstm_model, max_len, text):seq = tokenizer_lstm.texts_to_sequences([preprocess_text(text)])padded = pad_sequences(seq, maxlen=max_len, padding='post', truncating='post')tensor_input = torch.tensor(padded, dtype=torch.long).to(device)lstm_model.eval()with torch.no_grad():output = lstm_model(tensor_input)return torch.sigmoid(output).item()def predict_distilbert_prob(tokenizer_distilbert, distilbert_model, text):if tokenizer_distilbert and distilbert_model:inputs = tokenizer_distilbert(preprocess_text(text),return_tensors="pt",truncation=True,padding='max_length',max_length=128).to(device) # Ensure inputs are on the same devicedistilbert_model.eval()with torch.no_grad():logits = distilbert_model(**inputs).logitsreturn torch.softmax(logits, dim=1).cpu().numpy()[0][1]return Nonedef predict_combined(model_components, text):184 unmodified lines# For local testing only (comment out for Spaces)if __name__ == "__main__":app.run(debug=True, host="0.0.0.0", port=5000)11 unmodified lines121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162631 unmodified line65666768697071727374757610 unmodified lines878889909192939495961 unmodified line9899100101102103104105106107108109110111112113114115116117118119120121122184 unmodified lines30730830931011 unmodified linesimport requestsimport datetimeimport osimport osos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Disable TensorFlow logsos.environ['HF_HOME'] = '/tmp/cache/' # Fix cache directory# Force CPU usageimport torchimport tensorflow as tftorch.set_default_device('cpu')tf.config.set_visible_devices([], 'GPU')from flask import Flask, request, render_template, jsonifyfrom markupsafe import escapeimport joblibimport refrom tensorflow.keras.preprocessing.sequence import pad_sequencesfrom flask_cors import CORSfrom apscheduler.schedulers.background import BackgroundSchedulerimport feedparserimport requestsimport datetime# Define LSTMClassifier directly in app.pyclass LSTMClassifier(torch.nn.Module):def __init__(self, vocab_size, embed_dim, hidden_dim, output_dim, n_layers, dropout):super().__init__()self.embedding = torch.nn.Embedding(vocab_size, embed_dim)self.lstm = torch.nn.LSTM(embed_dim,hidden_dim,num_layers=n_layers,batch_first=True,dropout=dropout)self.fc = torch.nn.Linear(hidden_dim, output_dim)self.dropout = torch.nn.Dropout(dropout)def forward(self, x):embedded = self.dropout(self.embedding(x))output, (hidden, cell) = self.lstm(embedded)return self.fc(output[:, -1, :])# Initialize Flask appapp = Flask(__name__)CORS(app)# Load modelsBASE_DIR = os.path.dirname(os.path.abspath(__file__))combined_model_path1 = os.path.join(BASE_DIR, "models", "combined_model.pkl")combined_model_path2 = os.path.join(BASE_DIR, "models", "combined_model_true.pkl")1 unmodified linetry:combined_model1 = joblib.load(combined_model_path1)combined_model2 = joblib.load(combined_model_path2)print("Models loaded successfully!")except Exception as e:print(f"Model loading failed: {e}")exit()# Helper functionsdef get_model_components(model_dict):return (model_dict["tfidf"],10 unmodified linescomponents1 = get_model_components(combined_model1)components2 = get_model_components(combined_model2)# Preprocessing and prediction functionsdef preprocess_text(text):text = re.sub(r'[^\w\s]', '', str(text).lower().strip())return re.sub(r'\s+', ' ', text)def predict_lr_prob(tfidf, lr_model, text):vec = tfidf.transform([preprocess_text(text)])1 unmodified linedef predict_rf_prob(tfidf, svd, rf_model, text):vec = tfidf.transform([preprocess_text(text)])return rf_model.predict_proba(svd.transform(vec))[0][1]def predict_lstm_prob(tokenizer, model, max_len, text):seq = tokenizer.texts_to_sequences([preprocess_text(text)])padded = pad_sequences(seq, maxlen=max_len, padding='post', truncating='post')tensor_input = torch.tensor(padded, dtype=torch.long)with torch.no_grad():return torch.sigmoid(model(tensor_input)).item()def predict_distilbert_prob(tokenizer, model, text):inputs = tokenizer(preprocess_text(text),return_tensors="pt",truncation=True,padding='max_length',max_length=128)with torch.no_grad():return torch.softmax(model(**inputs).logits, dim=1)[0][1].item()return Nonedef predict_combined(model_components, text):184 unmodified lines# For local testing only (comment out for Spaces)if __name__ == "__main__":app.run(debug=True, host="0.0.0.0", port=5000)
app.py+59-43