Spaces:
Runtime error
Runtime error
Update app.py
Browse files14 unmodified lines15161718192021222324252627282930313233100 unmodified lines13413513613713813914014114214314414514614714814915015115215315415515615715815916014 unmodified lineslogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)app = FastAPI(title="AI Web Services")app.mount("/static", StaticFiles(directory="static"), name="static")# Initialize models (Spaces will cache these)try:logger.info("Loading AI models...")image_pipeline = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base")text_pipeline = pipeline("text2text-generation", model="t5-small")logger.info("Models loaded successfully")except Exception as e:logger.error(f"Model loading Failed: {e}")raise RuntimeError("Failed to initialize AI models")@app.get("/", response_class=HTMLResponse)async def home():"""Serve the frontend interface"""100 unmodified lineslogger.error(f"Visualization error: {e}")raise HTTPException(500, "Visualization code generation failed")async def extract_text(file: UploadFile) -> str:"""Extract text from PDF or DOCX files"""try:content = await file.read()if file.filename.endswith(".pdf"):with fitz.open(stream=content, filetype="pdf") as doc:return " ".join(page.get_text() for page in doc)elif file.filename.endswith(".docx"):doc = Document(io.BytesIO(content))return "\n".join(p.text for p in doc.paragraphs)else:raise ValueError("Unsupported file format")except Exception as e:logger.error(f"Text extraction failed: {e}")raise HTTPException(400, f"Could not extract text: {e}")# Health check endpoint@app.get("/health")async def health_check():return JSONResponse({"status": "healthy", "models": "loaded"})if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=8000)14 unmodified lines1516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667100 unmodified lines16816917017117217317417517617717817918018118218318418518618718818919019114 unmodified lineslogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# Initialize FastAPI appapp = FastAPI(title="AI Web Services",description="API for various AI services including text summarization, image captioning, and document analysis",version="1.0.0")# Mount static filesapp.mount("/static", StaticFiles(directory="static"), name="static")# Load AI modelstry:logger.info("Loading AI models...")image_pipeline = pipeline("image-to-text",model="Salesforce/blip-image-captioning-base",device="cpu")text_pipeline = pipeline("text2text-generation",model="t5-small",device="cpu")logger.info("Models loaded successfully")except Exception as e:logger.error(f"Model loading failed: {e}")raise RuntimeError("Failed to initialize AI models")# Helper function for text extractionasync def extract_text(file: UploadFile) -> str:"""Extract text from PDF or DOCX files"""try:content = await file.read()if file.filename.endswith(".pdf"):with fitz.open(stream=content, filetype="pdf") as doc:return " ".join(page.get_text() for page in doc)elif file.filename.endswith(".docx"):doc = Document(io.BytesIO(content))return "\n".join(p.text for p in doc.paragraphs)else:raise ValueError("Unsupported file format")except Exception as e:logger.error(f"Text extraction failed: {e}")raise HTTPException(400, f"Could not extract text: {e}")# API Endpoints@app.get("/", response_class=HTMLResponse)async def home():"""Serve the frontend interface"""100 unmodified lineslogger.error(f"Visualization error: {e}")raise HTTPException(500, "Visualization code generation failed")@app.get("/health")async def health_check():"""Health check endpoint"""return JSONResponse({"status": "healthy","models": {"image_captioning": "loaded","text_generation": "loaded"}})# Server initializationif __name__ == "__main__":import uvicornuvicorn.run(app,host="0.0.0.0",port=8000,log_level="info",reload=True)
app.py+57-26