Jiahuita commited on
Commit ·
50fd5a6
1
Parent(s): cec65b9
error changes
Browse filesFiles changed (2)
- app.py+50-18
- requirements.txt-1
3 unmodified lines456789101112131415161718192 unmodified lines22232425262728293031323334353637383940414243444546474849505152535455563 unmodified linesfrom tensorflow.keras.models import load_modelfrom tensorflow.keras.preprocessing.text import tokenizer_from_jsonfrom tensorflow.keras.preprocessing.sequence import pad_sequencesimport jsonfrom typing import Union, Listapp = FastAPI()# Load model and tokenizermodel = load_model('news_classifier.h5')with open('tokenizer.json', 'r') as f:tokenizer_data = json.load(f)tokenizer = tokenizer_from_json(tokenizer_data)class PredictionInput(BaseModel):text: Union[str, List[str]]2 unmodified lineslabel: strscore: float@app.post("/predict")async def predict(input_data: PredictionInput):try:# Convert input to list if it's a single stringtexts = input_data.text if isinstance(input_data.text, list) else [input_data.text]# Preprocesssequences = tokenizer.texts_to_sequences(texts)padded = pad_sequences(sequences, maxlen=41) # Use your model's expected input length# Predictpredictions = model.predict(padded)# Format resultsresults = []for pred in predictions:score = float(pred[1]) # Assuming binary classificationlabel = "foxnews" if score > 0.5 else "nbc"results.append({"label": label,"score": score if label == "foxnews" else 1 - score})# Return single result if input was single stringreturn results[0] if isinstance(input_data.text, str) else resultsexcept Exception as e:raise HTTPException(status_code=500, detail=str(e))@app.get("/")async def root():return {"message": "News Classifier API is running"}3 unmodified lines45678910111213141516171819202122232425262728293031322 unmodified lines3536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687883 unmodified linesfrom tensorflow.keras.models import load_modelfrom tensorflow.keras.preprocessing.text import tokenizer_from_jsonfrom tensorflow.keras.preprocessing.sequence import pad_sequencesimport numpy as npimport jsonfrom typing import Union, Listapp = FastAPI()# Global variables for model and tokenizermodel = Nonetokenizer = Nonedef load_model_and_tokenizer():global model, tokenizertry:model = load_model('news_classifier.h5')with open('tokenizer.json', 'r') as f:tokenizer_data = json.load(f)tokenizer = tokenizer_from_json(tokenizer_data)except Exception as e:print(f"Error loading model or tokenizer: {str(e)}")raise e# Load on startupload_model_and_tokenizer()class PredictionInput(BaseModel):text: Union[str, List[str]]2 unmodified lineslabel: strscore: float@app.get("/")def read_root():return {"message": "News Source Classifier API","model_type": "LSTM","version": "1.0","status": "ready" if model and tokenizer else "not_loaded"}@app.post("/predict", response_model=Union[PredictionOutput, List[PredictionOutput]])async def predict(input_data: PredictionInput):if not model or not tokenizer:try:load_model_and_tokenizer()except Exception as e:raise HTTPException(status_code=500, detail="Model not loaded")try:# Handle both single string and list inputstexts = input_data.text if isinstance(input_data.text, list) else [input_data.text]# Preprocesssequences = tokenizer.texts_to_sequences(texts)padded = pad_sequences(sequences, maxlen=41) # Match your model's input length# Get predictionspredictions = model.predict(padded, verbose=0)# Process resultsresults = []for pred in predictions:label = "foxnews" if pred[1] > 0.5 else "nbc"score = float(pred[1] if label == "foxnews" else 1 - pred[1])results.append({"label": label,"score": score})# Return single result if input was single stringreturn results[0] if isinstance(input_data.text, str) else resultsexcept Exception as e:raise HTTPException(status_code=500, detail=str(e))@app.post("/reload")async def reload_model():try:load_model_and_tokenizer()return {"message": "Model reloaded successfully"}except Exception as e:raise HTTPException(status_code=500, detail=str(e))
2 unmodified lines345672 unmodified linesuvicorn>=0.15.0pydantic>=1.8.2numpy>=1.19.2scikit-learn>=0.24.2python-multipart2 unmodified lines34562 unmodified linesuvicorn>=0.15.0pydantic>=1.8.2numpy>=1.19.2python-multipart
app.py+50-18
requirements.txt-1