Ninjasharp commited on
Commit
62fd2f0
·
verified ·
1 Parent(s): 9209ae9

Delete streamlit_app.py.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py.py +0 -217
streamlit_app.py.py DELETED
@@ -1,217 +0,0 @@
1
- import os
2
- import json
3
- import re
4
- import io
5
- import base64
6
- import streamlit as st
7
- from PIL import Image
8
- from groq import Groq
9
-
10
-
11
- # --- Helper Functions ---
12
- def text_to_json(user_prompt, groq_client, model_name):
13
- """Convert natural language to structured JSON."""
14
- prompt = f"""
15
- You are a helpful assistant that converts ideas into structured JSON.
16
- The JSON must be valid and minimal.
17
-
18
- Input: "{user_prompt}"
19
-
20
- Return ONLY valid JSON (no explanations or code comments).
21
- """
22
- try:
23
- response = groq_client.chat.completions.create(
24
- model=model_name,
25
- messages=[{"role": "user", "content": prompt}],
26
- temperature=0.3,
27
- max_tokens=800,
28
- )
29
- raw_output = response.choices[0].message.content.strip()
30
-
31
- try:
32
- parsed = json.loads(raw_output)
33
- except json.JSONDecodeError:
34
- match = re.search(r"\{[\s\S]*\}", raw_output)
35
- if match:
36
- parsed = json.loads(match.group(0))
37
- else:
38
- raise
39
- return json.dumps(parsed, indent=2)
40
- except Exception as e:
41
- return f"Error: {str(e)}"
42
-
43
-
44
- def json_to_text(json_text, groq_client, model_name):
45
- """Convert JSON schema or data back into descriptive text."""
46
- prompt = f"""
47
- You are an assistant that explains JSON data in clear, natural language.
48
- Turn the following JSON into a human-readable description or creative prompt.
49
-
50
- JSON Input:
51
- {json_text}
52
-
53
- Return only the descriptive text.
54
- """
55
- try:
56
- response = groq_client.chat.completions.create(
57
- model=model_name,
58
- messages=[{"role": "user", "content": prompt}],
59
- temperature=0.4,
60
- max_tokens=600,
61
- )
62
- return response.choices[0].message.content.strip()
63
- except Exception as e:
64
- return f"Error: {str(e)}"
65
-
66
-
67
- def image_to_prompt(image, groq_client, model_name):
68
- """Generate a text prompt from an uploaded image using text-only fallback."""
69
- try:
70
- img_buffer = io.BytesIO()
71
- image.save(img_buffer, format="PNG")
72
- img_b64 = base64.b64encode(img_buffer.getvalue()).decode()
73
-
74
- prompt = (
75
- "You are an assistant that receives base64-encoded image data and describes it in vivid detail. "
76
- "Analyze what the image likely depicts and return a creative, natural-language prompt. "
77
- "Here is the base64 image data (truncated for safety):\n"
78
- f"{img_b64[:4000]}..."
79
- )
80
-
81
- response = groq_client.chat.completions.create(
82
- model=model_name,
83
- messages=[{"role": "user", "content": prompt}],
84
- temperature=0.5,
85
- max_tokens=500,
86
- )
87
- return response.choices[0].message.content.strip()
88
-
89
- except Exception as e:
90
- return f"Error: {str(e)}"
91
-
92
-
93
- # --- Streamlit App ---
94
- def main():
95
- st.set_page_config(page_title="Prompt ↔ JSON ↔ Image Generator", page_icon="🧠", layout="wide")
96
-
97
- st.markdown("""
98
- <style>
99
- .block-container { padding-left: 2rem; padding-right: 2rem; max-width: 1200px; }
100
- textarea { font-family: monospace; }
101
- </style>
102
- """, unsafe_allow_html=True)
103
-
104
- st.title("🧠 Prompt ↔ JSON ↔ Image Generator")
105
- st.markdown("""
106
- Convert freely between **text**, **JSON**, and **image-based prompts** —
107
- perfect for AI development, creative workflows, and generative pipelines.
108
- """)
109
-
110
- # Sidebar
111
- st.sidebar.image("2.PNG")
112
- st.sidebar.image("1.PNG", caption="Powered by Groq")
113
- st.sidebar.markdown("Build by **DW** ⚡")
114
-
115
- groq_api_key = st.secrets.get("GROQ_API_KEY", "") or os.getenv("GROQ_API_KEY")
116
- if not groq_api_key:
117
- st.error("Missing GROQ_API_KEY in environment or Streamlit secrets.")
118
- st.stop()
119
-
120
- groq_client = Groq(api_key=groq_api_key)
121
-
122
- model_name = st.sidebar.selectbox(
123
- "Select Model:",
124
- ["openai/gpt-oss-120b","llama-3.3-70b-versatile", "mixtral-8x7b-32768"]
125
- )
126
-
127
- mode = st.sidebar.radio(
128
- "Choose Direction:",
129
- ["Text → JSON", "JSON → Text", "🖼️ Image → Prompt"]
130
- )
131
-
132
- # --- Mode 1: Text → JSON ---
133
- if mode == "Text → JSON":
134
- st.subheader("📝 Describe your idea or task")
135
- user_prompt = st.text_area(
136
- "Enter natural language description:",
137
- height=180,
138
- placeholder="Example: Create a JSON schema for a quest system with title, reward, and difficulty."
139
- )
140
-
141
- if st.button("Generate JSON"):
142
- if not user_prompt.strip():
143
- st.warning("Please enter a prompt first.")
144
- return
145
-
146
- with st.spinner("Generating JSON..."):
147
- result = text_to_json(user_prompt, groq_client, model_name)
148
-
149
- if result.startswith("Error"):
150
- st.error(result)
151
- else:
152
- st.subheader("🧩 Generated JSON:")
153
- st.code(result, language="json")
154
- st.download_button(
155
- "💾 Download JSON",
156
- data=result,
157
- file_name="generated_prompt.json",
158
- mime="application/json"
159
- )
160
-
161
- # --- Mode 2: JSON → Text ---
162
- elif mode == "JSON → Text":
163
- st.subheader("🧩 Paste your JSON input")
164
- json_text = st.text_area(
165
- "Enter JSON structure:",
166
- height=250,
167
- placeholder='{\n "task": "daily_affirmation",\n "fields": {"message": "string", "mood": "integer"}\n}'
168
- )
169
-
170
- if st.button("Generate Description"):
171
- if not json_text.strip():
172
- st.warning("Please enter JSON first.")
173
- return
174
-
175
- with st.spinner("Converting JSON to prompt..."):
176
- result = json_to_text(json_text, groq_client, model_name)
177
-
178
- if result.startswith("Error"):
179
- st.error(result)
180
- else:
181
- st.subheader("📝 Generated Description:")
182
- st.write(result)
183
- st.download_button(
184
- "💾 Download Text",
185
- data=result,
186
- file_name="generated_prompt.txt",
187
- mime="text/plain"
188
- )
189
-
190
- # --- Mode 3: Image → Prompt ---
191
- elif mode == "🖼️ Image → Prompt":
192
- st.subheader("🖼️ Upload an image to convert to a text prompt")
193
- uploaded_image = st.file_uploader("Upload an image (PNG, JPG)", type=["png", "jpg", "jpeg"])
194
-
195
- if uploaded_image:
196
- image = Image.open(uploaded_image)
197
- st.image(image, caption="Uploaded Image")
198
-
199
- if st.button("Generate Prompt from Image"):
200
- with st.spinner("Analyzing image..."):
201
- result = image_to_prompt(image, groq_client, model_name)
202
-
203
- if result.startswith("Error"):
204
- st.error(result)
205
- else:
206
- st.subheader("🧠 Generated Prompt:")
207
- st.text_area("Prompt Text", result, height=200)
208
- st.download_button(
209
- "💾 Download Prompt",
210
- data=result,
211
- file_name="image_prompt.txt",
212
- mime="text/plain"
213
- )
214
-
215
-
216
- if __name__ == "__main__":
217
- main()