File size: 4,730 Bytes
db93af0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
from fastapi import FastAPI, HTTPException, BackgroundTasks, Depends
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
import uuid
from concurrent.futures import ThreadPoolExecutor
from pymongo import MongoClient
from urllib.parse import quote_plus
from langchain_groq import ChatGroq
from aura_sr import AuraSR
from io import BytesIO
from PIL import Image
import requests
import os

app = FastAPI()

# Middleware for CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# Globals
executor = ThreadPoolExecutor(max_workers=10)
llm = None
upscale_model = None
client = MongoClient(f"mongodb+srv://hammad:{quote_plus('momimaad@123')}@cluster0.2a9yu.mongodb.net/")
db = client["Flux"]
collection = db["chat_histories"]
chat_sessions = {}
image_storage_dir = "./images"  # Directory to save images locally

# Ensure the image storage directory exists
os.makedirs(image_storage_dir, exist_ok=True)

@app.on_event("startup")
async def startup():
    global llm, upscale_model
    llm = ChatGroq(
        model="llama-3.3-70b-versatile",
        temperature=0.7,
        max_tokens=1024,
        api_key="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",
    )
    upscale_model = AuraSR.from_pretrained("fal/AuraSR-v2")

@app.on_event("shutdown")
def shutdown():
    client.close()
    executor.shutdown()

# Pydantic models
class ImageRequest(BaseModel):
    subject: str
    style: str
    color_theme: str
    elements: str
    color_mode: str
    lighting_conditions: str
    framing_style: str
    material_details: str
    text: str
    background_details: str
    user_prompt: str
    chat_id: str

# Helper Functions
def generate_chat_id():
    chat_id = str(uuid.uuid4())
    chat_sessions[chat_id] = collection
    return chat_id

def get_chat_history(chat_id):
    messages = collection.find({"session_id": chat_id})
    return "\n".join(
        f"User: {msg['content']}" if msg['role'] == "user" else f"AI: {msg['content']}"
        for msg in messages
    )

def save_image_locally(image, filename):
    filepath = os.path.join(image_storage_dir, filename)
    image.save(filepath, format="PNG")
    return filepath

# Endpoints
@app.post("/new-chat", response_model=dict)
async def new_chat():
    chat_id = generate_chat_id()
    return {"chat_id": chat_id}

@app.post("/generate-image", response_model=dict)
async def generate_image(request: ImageRequest, background_tasks: BackgroundTasks):
    def process_request():
        chat_history = get_chat_history(request.chat_id)
        prompt = f"""
        Subject: {request.subject}
        Style: {request.style}
        ...
        Chat History: {chat_history}
        User Prompt: {request.user_prompt}
        """
        refined_prompt = llm.invoke(prompt).content.strip()
        collection.insert_one({"session_id": request.chat_id, "role": "user", "content": request.user_prompt})
        collection.insert_one({"session_id": request.chat_id, "role": "ai", "content": refined_prompt})

        # Simulate image generation
        response = requests.post(
            "https://api.bfl.ml/v1/flux-pro-1.1",
            json={"prompt": refined_prompt}
        ).json()
        image_url = response["result"]["sample"]

        # Download and save the image locally
        image_response = requests.get(image_url)
        img = Image.open(BytesIO(image_response.content))
        filename = f"generated_{uuid.uuid4()}.png"
        filepath = save_image_locally(img, filename)
        return filepath

    task = executor.submit(process_request)
    background_tasks.add_task(task)
    return {"status": "Processing"}

@app.post("/upscale-image", response_model=dict)
async def upscale_image(image_url: str, background_tasks: BackgroundTasks):
    def process_image():
        response = requests.get(image_url)
        img = Image.open(BytesIO(response.content))
        upscaled_image = upscale_model.upscale_4x_overlapped(img)
        filename = f"upscaled_{uuid.uuid4()}.png"
        filepath = save_image_locally(upscaled_image, filename)
        return filepath

    task = executor.submit(process_image)
    background_tasks.add_task(task)
    return {"status": "Processing"}

@app.post("/set-prompt", response_model=dict)
async def set_prompt(chat_id: str, user_prompt: str):
    chat_history = get_chat_history(chat_id)
    refined_prompt = llm.invoke(f"{chat_history}\nUser Prompt: {user_prompt}").content.strip()
    collection.insert_one({"session_id": chat_id, "role": "user", "content": user_prompt})
    collection.insert_one({"session_id": chat_id, "role": "ai", "content": refined_prompt})
    return {"refined_prompt": refined_prompt}