Flopot2 commited on
Commit
85cad9f
Β·
verified Β·
1 Parent(s): dd97914

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +49 -62
src/streamlit_app.py CHANGED
@@ -4,12 +4,8 @@ os.environ["XDG_CONFIG_HOME"] = os.path.join(os.getcwd(), ".config")
4
  import streamlit as st
5
  import pandas as pd
6
  import openai
7
- import re
8
- import asyncio
9
- import httpx
10
  import time
11
  from io import StringIO
12
- from typing import List
13
 
14
  # --- CONFIG ---
15
  st.set_page_config(page_title="πŸ–ΌοΈ Alt Text Generator", layout="wide")
@@ -22,77 +18,68 @@ st.markdown("Generate SEO-friendly alt text for image URLs using GPT-4o Vision.\
22
  api_key = st.text_input("πŸ”‘ Enter your OpenAI API key", type="password")
23
  if not api_key:
24
  st.stop()
25
- openai_client = openai.AsyncOpenAI(api_key=api_key)
26
 
27
  # --- INPUT FILE ---
28
  uploaded_file = st.file_uploader("πŸ“ Upload a CSV with image URLs", type=["csv"])
29
- if not uploaded_file:
30
- st.stop()
 
 
31
 
32
- df = pd.read_csv(uploaded_file)
33
- st.success("βœ… File uploaded successfully")
34
- st.dataframe(df.head())
35
 
36
- # --- COLUMN SELECT ---
37
- image_col = st.selectbox("🧭 Select the column with image URLs", df.columns)
 
38
 
39
- # --- PROMPT INPUT ---
40
- prompt_instruction = st.text_area("πŸ“ Enter the prompt to generate alt text",
41
- value="Write a concise, SEO-friendly alt text for the image below. Do not use brand names unless visible.")
42
 
43
- # --- FILTER IMAGES ---
44
- def is_valid_image_url(url: str):
45
- return any(url.lower().endswith(ext) for ext in VALID_IMAGE_EXTENSIONS)
46
 
47
- df["Valid Image"] = df[image_col].astype(str).apply(is_valid_image_url)
48
- valid_df = df[df["Valid Image"] == True]
 
49
 
50
- if valid_df.empty:
51
- st.error("❌ No valid image URLs found. Make sure URLs end with .jpg, .png, .webp, etc.")
52
- st.stop()
 
 
 
 
53
 
54
- st.info(f"πŸ” {len(valid_df)} valid image URLs found. Invalid ones will be skipped.")
55
-
56
- # --- GENERATE ALT TEXT ---
57
- async def generate_alt_text(url: str, prompt: str):
58
- try:
59
- response = await openai_client.chat.completions.create(
60
- model="gpt-4o",
61
- messages=[
62
- {
63
- "role": "user",
64
- "content": [
65
- {"type": "text", "text": prompt},
66
- {"type": "image_url", "image_url": {"url": url}}
67
- ]
68
- }
69
- ]
70
- )
71
- return response.choices[0].message.content.strip()
72
- except Exception as e:
73
- return f"ERROR: {e}"
74
-
75
- st.markdown("### πŸš€ Run Alt Text Generation")
76
- if st.button("Start Processing"):
77
- progress = st.progress(0)
78
- results = []
79
- urls = valid_df[image_col].tolist()
80
-
81
- async def run_all():
82
  for idx, url in enumerate(urls):
83
- alt_text = await generate_alt_text(url, prompt_instruction)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  results.append(alt_text)
85
  progress.progress((idx + 1) / len(urls))
86
- await asyncio.sleep(1) # polite delay
87
-
88
- asyncio.run(run_all())
89
 
90
- valid_df["Generated Alt Text"] = results
91
- output_df = df.copy()
92
- output_df.loc[valid_df.index, "Generated Alt Text"] = valid_df["Generated Alt Text"]
93
 
94
- st.success("βœ… Done! Preview of the results:")
95
- st.dataframe(output_df[[image_col, "Generated Alt Text"]].head())
96
 
97
- csv = output_df.to_csv(index=False).encode("utf-8")
98
- st.download_button("πŸ“₯ Download CSV with Alt Text", csv, "alt_text_output.csv", "text/csv")
 
4
  import streamlit as st
5
  import pandas as pd
6
  import openai
 
 
 
7
  import time
8
  from io import StringIO
 
9
 
10
  # --- CONFIG ---
11
  st.set_page_config(page_title="πŸ–ΌοΈ Alt Text Generator", layout="wide")
 
18
  api_key = st.text_input("πŸ”‘ Enter your OpenAI API key", type="password")
19
  if not api_key:
20
  st.stop()
21
+ client = openai.OpenAI(api_key=api_key)
22
 
23
  # --- INPUT FILE ---
24
  uploaded_file = st.file_uploader("πŸ“ Upload a CSV with image URLs", type=["csv"])
25
+ if uploaded_file:
26
+ df = pd.read_csv(uploaded_file)
27
+ st.success("βœ… File uploaded successfully")
28
+ st.dataframe(df.head())
29
 
30
+ # --- COLUMN SELECT ---
31
+ image_col = st.selectbox("🧭 Select the column with image URLs", df.columns)
 
32
 
33
+ # --- PROMPT INPUT ---
34
+ prompt_instruction = st.text_area("πŸ“ Enter the prompt to generate alt text",
35
+ value="Write a concise, SEO-friendly alt text for the image below. Do not use brand names unless visible.")
36
 
37
+ def is_valid_image_url(url: str):
38
+ return any(url.lower().endswith(ext) for ext in VALID_IMAGE_EXTENSIONS)
 
39
 
40
+ df["Valid Image"] = df[image_col].astype(str).apply(is_valid_image_url)
41
+ valid_df = df[df["Valid Image"] == True]
 
42
 
43
+ if valid_df.empty:
44
+ st.error("❌ No valid image URLs found. Make sure URLs end with .jpg, .png, .webp, etc.")
45
+ st.stop()
46
 
47
+ st.info(f"πŸ” {len(valid_df)} valid image URLs found. Invalid ones will be skipped.")
48
+
49
+ # --- PROCESS ---
50
+ if st.button("πŸš€ Start Processing"):
51
+ progress = st.progress(0)
52
+ results = []
53
+ urls = valid_df[image_col].tolist()
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  for idx, url in enumerate(urls):
56
+ try:
57
+ response = client.chat.completions.create(
58
+ model="gpt-4o",
59
+ messages=[
60
+ {
61
+ "role": "user",
62
+ "content": [
63
+ {"type": "text", "text": prompt_instruction},
64
+ {"type": "image_url", "image_url": {"url": url}}
65
+ ]
66
+ }
67
+ ]
68
+ )
69
+ alt_text = response.choices[0].message.content.strip()
70
+ except Exception as e:
71
+ alt_text = f"ERROR: {e}"
72
+
73
  results.append(alt_text)
74
  progress.progress((idx + 1) / len(urls))
75
+ time.sleep(1)
 
 
76
 
77
+ valid_df["Generated Alt Text"] = results
78
+ output_df = df.copy()
79
+ output_df.loc[valid_df.index, "Generated Alt Text"] = valid_df["Generated Alt Text"]
80
 
81
+ st.success("βœ… Done! Preview of the results:")
82
+ st.dataframe(output_df[[image_col, "Generated Alt Text"]].head())
83
 
84
+ csv = output_df.to_csv(index=False).encode("utf-8")
85
+ st.download_button("πŸ“₯ Download CSV with Alt Text", csv, "alt_text_output.csv", "text/csv")