Spaces:
Paused
Paused
Update app.py
Browse files12345678910111213from fastapi import FastAPI, Requestimport requests, os, randomfrom imdb import CinemagoerIMGBB_API_KEY = os.getenv("IMGBB_API_KEY")GIST_URL = os.getenv("GIST_URL")TMDB_API_KEY = os.getenv("TMDB_API_KEY")DATA_DIR = "/data"app = FastAPI()@app.get("/")def greet_json():123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191from fastapi import FastAPI, Requestimport requests, os, randomimport psycopg2import loggingfrom fastapi import FastAPI, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom runware import Runware, IImageInferencefrom dotenv import load_dotenvfrom openai import OpenAIfrom imdb import CinemagoerIMGBB_API_KEY = os.getenv("IMGBB_API_KEY")GIST_URL = os.getenv("GIST_URL")TMDB_API_KEY = os.getenv("TMDB_API_KEY")RUNWARE_API_KEY = os.getenv("RUNWARE_API_KEY")OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")OPENAI_API_BASE = os.getenv("OPENAI_API_BASE")client = OpenAI(api_key=OPENAI_API_KEY, base_url=OPENAI_API_BASE)DATA_DIR = "/data"app = FastAPI()app.add_middleware(CORSMiddleware,allow_origins=["*"], # Allow requests from Next.js dev serverallow_credentials=True,allow_methods=["*"],allow_headers=["*"],)db_params = {'dbname': os.getenv('DB_NAME'),'user': os.getenv('DB_USER'),'password': os.getenv('DB_PASSWORD'),'host': os.getenv('DB_HOST'),'port': os.getenv('DB_PORT'),'sslmode': 'require'}class ImageRequest(BaseModel):prompt: strwidth: intheight: intmodel: strnumber_results: int = 1def insert_batch(prompt: str, width: int, height: int, model: str, urls: list[str]) -> int:conn = Nonetry:conn = psycopg2.connect(**db_params)cur = conn.cursor()cur.execute("INSERT INTO batches (prompt, width, height, model) VALUES (%s, %s, %s, %s) RETURNING id",(prompt, width, height, model))batch_id = cur.fetchone()[0]for url in urls:cur.execute("INSERT INTO images (batch_id, url) VALUES (%s, %s)",(batch_id, url))conn.commit()cur.close()return batch_idexcept (Exception, psycopg2.DatabaseError) as error:print(f"Error inserting batch: {error}")raisefinally:if conn is not None:conn.close()@app.post("/generate-image")async def generate_image(request: ImageRequest):try:runware = Runware(api_key=RUNWARE_API_KEY)await runware.connect()request_image = IImageInference(positivePrompt=request.prompt,model=request.model,numberResults=request.number_results,height=request.height,width=request.width,)images = await runware.imageInference(requestImage=request_image)image_urls = [image.imageURL for image in images]batch_id = insert_batch(request.prompt, request.width, request.height, request.model, image_urls)response = {"batch": {"id": batch_id, "prompt": request.prompt, "width": request.width, "height": request.height, "model": request.model, "images": [{"url": url} for url in image_urls]}}return responseexcept Exception as e:raise HTTPException(status_code=500, detail=f"Failed to generate image: {str(e)}")@app.get("/get-batches")async def get_batches():conn = Nonetry:conn = psycopg2.connect(**db_params)cur = conn.cursor()cur.execute("""SELECT b.id, b.prompt, b.width, b.height, b.model, array_agg(i.url) as image_urls, b.created_atFROM batches bJOIN images i ON i.batch_id = b.idGROUP BY b.id, b.prompt, b.width, b.height, b.model, b.created_atORDER BY b.created_at DESCLIMIT 5""")rows = cur.fetchall()batches = []for row in rows:created_at = row[6]created_at_iso = created_at.isoformat() if created_at else Nonebatch = {"id": row[0],"prompt": row[1],"width": row[2],"height": row[3],"model": row[4],"images": [{"url": url} for url in row[5]],"createdAt": created_at_iso}batches.append(batch)return {"batches": batches}except (Exception, psycopg2.DatabaseError) as error:raise HTTPException(status_code=500, detail=str(error))finally:if conn is not None:conn.close()def delete_batch(batch_id: int):conn = Nonetry:conn = psycopg2.connect(**db_params)cur = conn.cursor()# Delete associated images firstcur.execute("DELETE FROM images WHERE batch_id = %s", (batch_id,))# Then delete the batchcur.execute("DELETE FROM batches WHERE id = %s", (batch_id,))conn.commit()return Trueexcept (Exception, psycopg2.DatabaseError) as error:print(f"Error deleting batch: {error}")return Falsefinally:if conn is not None:conn.close()@app.delete("/delete-batch")async def delete_batch_route(id: int):success = delete_batch(id)if success:return {"message": "Batch deleted successfully"}else:raise HTTPException(status_code=500, detail="Failed to delete batch")@app.post("/enhance-prompt")async def enhance_prompt(request: dict):try:prompt = request.get("prompt")if not prompt:raise HTTPException(status_code=400, detail="Prompt is required")response = client.chat.completions.create(model="gemini-1.5-flash-latest",messages=[{"role": "system", "content": "You are an AI assistant that enhances image generation prompts. Your task is to take a user's prompt and make it more detailed and descriptive, suitable for high-quality image generation."},{"role": "user", "content": f"Enhance this image generation prompt: {prompt}. Reply with the enhanced prompt only."}])enhanced_prompt = response.choices[0].message.contentreturn {"enhancedPrompt": enhanced_prompt}except Exception as e:logger.error(f"Error enhancing prompt: {str(e)}")raise HTTPException(status_code=500, detail=f"Failed to enhance prompt: {str(e)}")@app.get("/")def greet_json():
app.py+178