Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -15,19 +15,53 @@ from typing import Optional
|
|
| 15 |
logging.basicConfig(level=logging.INFO)
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 20 |
|
| 21 |
-
#
|
| 22 |
try:
|
| 23 |
logger.info("Loading AI models...")
|
| 24 |
-
image_pipeline = pipeline(
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
logger.info("Models loaded successfully")
|
| 27 |
except Exception as e:
|
| 28 |
-
logger.error(f"Model loading
|
| 29 |
raise RuntimeError("Failed to initialize AI models")
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
@app.get("/", response_class=HTMLResponse)
|
| 32 |
async def home():
|
| 33 |
"""Serve the frontend interface"""
|
|
@@ -134,27 +168,24 @@ plt.show()"""
|
|
| 134 |
logger.error(f"Visualization error: {e}")
|
| 135 |
raise HTTPException(500, "Visualization code generation failed")
|
| 136 |
|
| 137 |
-
async def extract_text(file: UploadFile) -> str:
|
| 138 |
-
"""Extract text from PDF or DOCX files"""
|
| 139 |
-
try:
|
| 140 |
-
content = await file.read()
|
| 141 |
-
|
| 142 |
-
if file.filename.endswith(".pdf"):
|
| 143 |
-
with fitz.open(stream=content, filetype="pdf") as doc:
|
| 144 |
-
return " ".join(page.get_text() for page in doc)
|
| 145 |
-
elif file.filename.endswith(".docx"):
|
| 146 |
-
doc = Document(io.BytesIO(content))
|
| 147 |
-
return "\n".join(p.text for p in doc.paragraphs)
|
| 148 |
-
else:
|
| 149 |
-
raise ValueError("Unsupported file format")
|
| 150 |
-
except Exception as e:
|
| 151 |
-
logger.error(f"Text extraction failed: {e}")
|
| 152 |
-
raise HTTPException(400, f"Could not extract text: {e}")
|
| 153 |
-
|
| 154 |
-
# Health check endpoint
|
| 155 |
@app.get("/health")
|
| 156 |
async def health_check():
|
| 157 |
-
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
import uvicorn
|
| 160 |
-
uvicorn.run(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
logging.basicConfig(level=logging.INFO)
|
| 16 |
logger = logging.getLogger(__name__)
|
| 17 |
|
| 18 |
+
# Initialize FastAPI app
|
| 19 |
+
app = FastAPI(
|
| 20 |
+
title="AI Web Services",
|
| 21 |
+
description="API for various AI services including text summarization, image captioning, and document analysis",
|
| 22 |
+
version="1.0.0"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
# Mount static files
|
| 26 |
app.mount("/static", StaticFiles(directory="static"), name="static")
|
| 27 |
|
| 28 |
+
# Load AI models
|
| 29 |
try:
|
| 30 |
logger.info("Loading AI models...")
|
| 31 |
+
image_pipeline = pipeline(
|
| 32 |
+
"image-to-text",
|
| 33 |
+
model="Salesforce/blip-image-captioning-base",
|
| 34 |
+
device="cpu"
|
| 35 |
+
)
|
| 36 |
+
text_pipeline = pipeline(
|
| 37 |
+
"text2text-generation",
|
| 38 |
+
model="t5-small",
|
| 39 |
+
device="cpu"
|
| 40 |
+
)
|
| 41 |
logger.info("Models loaded successfully")
|
| 42 |
except Exception as e:
|
| 43 |
+
logger.error(f"Model loading failed: {e}")
|
| 44 |
raise RuntimeError("Failed to initialize AI models")
|
| 45 |
|
| 46 |
+
# Helper function for text extraction
|
| 47 |
+
async def extract_text(file: UploadFile) -> str:
|
| 48 |
+
"""Extract text from PDF or DOCX files"""
|
| 49 |
+
try:
|
| 50 |
+
content = await file.read()
|
| 51 |
+
|
| 52 |
+
if file.filename.endswith(".pdf"):
|
| 53 |
+
with fitz.open(stream=content, filetype="pdf") as doc:
|
| 54 |
+
return " ".join(page.get_text() for page in doc)
|
| 55 |
+
elif file.filename.endswith(".docx"):
|
| 56 |
+
doc = Document(io.BytesIO(content))
|
| 57 |
+
return "\n".join(p.text for p in doc.paragraphs)
|
| 58 |
+
else:
|
| 59 |
+
raise ValueError("Unsupported file format")
|
| 60 |
+
except Exception as e:
|
| 61 |
+
logger.error(f"Text extraction failed: {e}")
|
| 62 |
+
raise HTTPException(400, f"Could not extract text: {e}")
|
| 63 |
+
|
| 64 |
+
# API Endpoints
|
| 65 |
@app.get("/", response_class=HTMLResponse)
|
| 66 |
async def home():
|
| 67 |
"""Serve the frontend interface"""
|
|
|
|
| 168 |
logger.error(f"Visualization error: {e}")
|
| 169 |
raise HTTPException(500, "Visualization code generation failed")
|
| 170 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
@app.get("/health")
|
| 172 |
async def health_check():
|
| 173 |
+
"""Health check endpoint"""
|
| 174 |
+
return JSONResponse({
|
| 175 |
+
"status": "healthy",
|
| 176 |
+
"models": {
|
| 177 |
+
"image_captioning": "loaded",
|
| 178 |
+
"text_generation": "loaded"
|
| 179 |
+
}
|
| 180 |
+
})
|
| 181 |
+
|
| 182 |
+
# Server initialization
|
| 183 |
+
if __name__ == "__main__":
|
| 184 |
import uvicorn
|
| 185 |
+
uvicorn.run(
|
| 186 |
+
app,
|
| 187 |
+
host="0.0.0.0",
|
| 188 |
+
port=8000,
|
| 189 |
+
log_level="info",
|
| 190 |
+
reload=True
|
| 191 |
+
)
|