LogicGoInfotechSpaces commited on
Commit
19bed74
·
verified ·
1 Parent(s): 5a116a6

Update app/main.py

Browse files
Files changed (1) hide show
  1. app/main.py +57 -69
app/main.py CHANGED
@@ -1,84 +1,72 @@
1
- import io
2
- import uuid
3
- import os
4
  from PIL import Image
5
- from fastapi import FastAPI, UploadFile, File
6
- from fastapi.responses import FileResponse
7
- from huggingface_hub import from_pretrained_fastai
8
  import gradio as gr
9
- import torch
10
- import uvicorn
 
11
 
12
- # ==========================================================
13
- # 🔧 CONFIGURATION
14
- # ==========================================================
15
- MODEL_ID = "Hammad712/GAN-Colorization-Model" # 👉 change this if you want another model
16
 
17
- UPLOAD_DIR = "/tmp/uploads"
18
- RESULT_DIR = "/tmp/results"
19
- os.makedirs(UPLOAD_DIR, exist_ok=True)
20
- os.makedirs(RESULT_DIR, exist_ok=True)
21
 
22
- # ==========================================================
23
- # 🚀 LOAD MODEL
24
- # ==========================================================
25
- print(f"Loading model: {MODEL_ID}")
26
- learn = from_pretrained_fastai(MODEL_ID)
27
- print("✅ Model loaded successfully!")
28
 
29
- # ==========================================================
30
- # 🧠 Colorization Function
31
- # ==========================================================
32
- def colorize_image(image: Image.Image):
33
- if image.mode != "RGB":
34
- image = image.convert("RGB")
35
- pred = learn.predict(image)[0]
36
- return pred
37
 
38
- # ==========================================================
39
- # 🌐 FASTAPI APP
40
- # ==========================================================
41
- app = FastAPI(title="Image Colorization API")
42
 
43
- @app.post("/colorize")
44
- async def colorize_endpoint(file: UploadFile = File(...)):
45
- """
46
- Upload a black & white image -> get colorized image
47
- """
48
- try:
49
- img_bytes = await file.read()
50
- image = Image.open(io.BytesIO(img_bytes)).convert("RGB")
51
 
52
- colorized = colorize_image(image)
53
- output_filename = f"{uuid.uuid4()}.png"
54
- output_path = os.path.join(RESULT_DIR, output_filename)
55
- colorized.save(output_path)
 
 
 
56
 
57
- return FileResponse(output_path, media_type="image/png")
58
- except Exception as e:
59
- return {"error": str(e)}
 
 
 
 
 
60
 
61
- # ==========================================================
62
- # 🎨 GRADIO INTERFACE
63
- # ==========================================================
64
- def gradio_interface(image):
65
- return colorize_image(image)
66
 
67
- title = "🎨 FastAI / HuggingFace Image Colorizer"
68
- description = "Upload a black & white photo to get a colorized version."
69
 
70
- iface = gr.Interface(
71
- fn=gradio_interface,
72
- inputs=gr.Image(type="pil", label="Upload Image"),
73
- outputs=gr.Image(type="pil", label="Colorized Output"),
74
- title=title,
75
- description=description,
76
- )
 
77
 
78
- gradio_app = gr.mount_gradio_app(app, iface, path="/")
 
 
79
 
80
- # ==========================================================
81
- # ▶️ RUN LOCALLY OR IN HUGGINGFACE SPACE
82
- # ==========================================================
83
- if __name__ == "__main__":
84
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
1
+ import torch
2
+ from torch import nn
3
+ from torchvision import transforms
4
  from PIL import Image
 
 
 
5
  import gradio as gr
6
+ import io
7
+ import base64
8
+ import requests
9
 
10
+ # Download model from Hugging Face Hub
11
+ MODEL_PATH = "generator.pt"
12
+ HF_MODEL_REPO = "Hammad712/GAN-Colorization-Model"
 
13
 
14
+ # Auto-download model if not present
15
+ from huggingface_hub import hf_hub_download
16
+ model_path = hf_hub_download(repo_id=HF_MODEL_REPO, filename=MODEL_PATH)
 
17
 
18
+ # Load the model (generator)
19
+ device = "cuda" if torch.cuda.is_available() else "cpu"
20
+ generator = torch.load(model_path, map_location=device)
21
+ generator.eval()
 
 
22
 
23
+ # Define transforms
24
+ transform_gray = transforms.Compose([
25
+ transforms.Resize((256, 256)),
26
+ transforms.Grayscale(),
27
+ transforms.ToTensor()
28
+ ])
 
 
29
 
30
+ transform_color = transforms.Compose([
31
+ transforms.Resize((256, 256)),
32
+ transforms.ToTensor()
33
+ ])
34
 
35
+ to_pil = transforms.ToPILImage()
 
 
 
 
 
 
 
36
 
37
+ # Colorization function
38
+ def colorize_image(input_image):
39
+ img = transform_gray(input_image).unsqueeze(0).to(device)
40
+ with torch.no_grad():
41
+ output = generator(img)
42
+ output_image = to_pil(output.squeeze().cpu().clamp(0, 1))
43
+ return output_image
44
 
45
+ # ---- Gradio Interface ----
46
+ iface = gr.Interface(
47
+ fn=colorize_image,
48
+ inputs=gr.Image(type="pil", label="Upload Grayscale Image"),
49
+ outputs=gr.Image(type="pil", label="Colorized Image"),
50
+ title="GAN Image Colorization (Hammad712)",
51
+ description="Colorizes black and white images using GAN model"
52
+ )
53
 
54
+ # ---- API Endpoint ----
55
+ from fastapi import FastAPI, File, UploadFile
56
+ from fastapi.responses import StreamingResponse
 
 
57
 
58
+ app = FastAPI(title="GAN Colorization API")
 
59
 
60
+ @app.post("/colorize")
61
+ async def colorize_api(file: UploadFile = File(...)):
62
+ image = Image.open(io.BytesIO(await file.read())).convert("RGB")
63
+ colorized = colorize_image(image)
64
+ buf = io.BytesIO()
65
+ colorized.save(buf, format="PNG")
66
+ buf.seek(0)
67
+ return StreamingResponse(buf, media_type="image/png")
68
 
69
+ # Mount Gradio UI on /
70
+ import gradio as gr
71
+ app = gr.mount_gradio_app(app, iface, path="/")
72