File size: 3,836 Bytes
5b1d663
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import pandas as pd
import requests
import io
import base64
from PIL import Image, ImageOps, ImageEnhance

DEEPSIGHT_API_URL = "https://api.deepseek.com/v2/chat/completions"
DEEPSIGHT_API_KEY = "YOUR_API_KEY"

SYSTEM_PROMPT = open("system_prompt.txt").read()

def call_deepsight(product_data):
    """Send product row to DeepSight v2 for structured generation."""
    payload = {
        "model": "deepseek-chat",
        "messages": [
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": product_data}
        ],
        "temperature": 0.2
    }

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {DEEPSIGHT_API_KEY}"
    }

    response = requests.post(DEEPSIGHT_API_URL, json=payload, headers=headers)
    return response.json()["choices"][0]["message"]["content"]


def download_image(url):
    try:
        img_bytes = requests.get(url, timeout=10).content
        return Image.open(io.BytesIO(img_bytes)).convert("RGBA")
    except:
        return None


def remove_bg(img):
    """Simple white background fallback if rembg is not installed."""
    # Optional: integrate rembg here if available
    bg = Image.new("RGBA", img.size, "WHITE")
    bg.paste(img, mask=img.split()[3])
    return bg


def apply_watermark(img, watermark_path="watermark.png"):
    try:
        wm = Image.open(watermark_path).convert("RGBA")
        wm = wm.resize((int(img.size[0] * 0.3), int(img.size[1] * 0.3)))
        img.paste(wm, (img.size[0]-wm.size[0]-10, img.size[1]-wm.size[1]-10), wm)
    except:
        pass
    return img


def enhance_image(img):
    img = ImageEnhance.Sharpness(img).enhance(1.4)
    img = ImageEnhance.Brightness(img).enhance(1.05)
    return img


def process_csv(file):
    df = pd.read_csv(file)
    output_rows = []
    output_images = []

    for idx, row in df.iterrows():
        title = str(row.get("post_title", "")).strip()
        short = str(row.get("post_excerpt", "")).strip()
        long = str(row.get("post_content", "")).strip()
        image_link = row.get("image_link", "")

        # Create a combined row prompt
        row_prompt = f"""
        Product Title: {title}
        Short Description: {short}
        Long Description: {long}
        """

        # Call DeepSight for content generation
        ai_output = call_deepsight(row_prompt)
        ai_dict = eval(ai_output)  # Expecting strict JSON from DeepSight

        # Process image
        final_image_path = None
        if isinstance(image_link, str) and image_link.startswith("http"):
            img = download_image(image_link)
            if img:
                img = ImageOps.contain(img, (800, 800))
                img = remove_bg(img)
                img = enhance_image(img)
                img = apply_watermark(img)

                save_path = f"processed_{idx}.png"
                img.save(save_path, "PNG")
                final_image_path = save_path

        output_rows.append({
            "seo_title": ai_dict["seo_title"],
            "short_description": ai_dict["short_description"],
            "long_description": ai_dict["long_description"],
            "processed_image": final_image_path
        })

    result_df = pd.DataFrame(output_rows)
    result_path = "output.csv"
    result_df.to_csv(result_path, index=False)

    return result_path


# Gradio Interface
with gr.Blocks() as demo:
    gr.Markdown("# 🚀 WooCommerce Product Optimizer (DeepSight v2)")
    gr.Markdown("Upload your CSV and let DeepSight clean titles, descriptions, and images.")

    csv_input = gr.File(label="Upload WooCommerce CSV")
    output_csv = gr.File(label="Download Optimized CSV")

    run_btn = gr.Button("Process CSV")

    run_btn.click(process_csv, inputs=csv_input, outputs=output_csv)

demo.launch()