ciaochris commited on
Commit
d601d5b
·
verified ·
1 Parent(s): f2f28b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -104
app.py CHANGED
@@ -7,7 +7,7 @@ from typing import List, Tuple
7
  # --- Basic Configuration ---
8
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[logging.StreamHandler()])
9
 
10
- # --- The Core Application Logic (Serves both modes) ---
11
  class HumanTouchApp:
12
  def __init__(self):
13
  self.client = self._initialize_groq_client()
@@ -23,31 +23,39 @@ class HumanTouchApp:
23
  return Groq(api_key=api_key)
24
 
25
  def _load_system_prompt(self) -> str:
26
- # This one prompt now powers both modes, using context to differentiate tasks.
27
  return """
28
- You are HumanTouch, an AI specializing in transforming text into emotionally resonant communication.
29
- Your output style is guided by two scores: Style (0=Logical, 100=Poetic) and Tone (0=Formal, 100=Passionate).
30
 
31
- You will be given a task: either "HUMANIZE" a block of text or "CO-CREATE" from a user's seed phrase.
 
 
32
 
33
- **Task: HUMANIZE**
34
- When given a block of text, your goal is to rewrite it to sound more natural, engaging, and less robotic, according to the provided Style and Tone scores. Retain the core meaning but infuse it with a human touch.
35
-
36
- **Task: CO-CREATE**
37
- When given a short phrase or idea, your goal is to expand and "bloom" it into a more complete, resonant thought, guided by the Style and Tone scores. This is a creative partnership.
38
-
39
- In both tasks, do not explain your process. Only provide the transformed text.
40
  """
41
 
42
- def _call_groq_api(self, messages: List[dict], style_level: float, tone_level: float) -> str:
43
  if not self.client:
44
  return "## 🔴 Configuration Error\n\nThe `GROQ_API_KEY` is not set on the server. Please contact the Space administrator."
45
  try:
46
  logging.info(f"Calling Groq API with Style: {style_level}, Tone: {tone_level}")
 
 
 
 
 
 
 
 
 
 
 
47
  response = self.client.chat.completions.create(
48
  model=self.model,
49
  messages=messages,
50
- temperature=0.6 + (style_level / 250) + (tone_level / 250),
51
  max_tokens=4096,
52
  )
53
  return response.choices[0].message.content.strip()
@@ -59,40 +67,14 @@ class HumanTouchApp:
59
  def humanize_block_text(self, text_to_humanize: str, style_level: float, tone_level: float) -> str:
60
  if not text_to_humanize.strip():
61
  return "Please paste some AI-generated text to get started."
62
-
63
- user_content = f"""
64
- TASK: HUMANIZE
65
- Style Score: {style_level}
66
- Tone Score: {tone_level}
67
- ---
68
- TEXT TO HUMANIZE:
69
- {text_to_humanize}
70
- """
71
- messages = [
72
- {"role": "system", "content": self.system_prompt_template},
73
- {"role": "user", "content": user_content}
74
- ]
75
- return self._call_groq_api(messages, style_level, tone_level)
76
 
77
  # Method for the "Co-Creative Canvas" Tab
78
  def generate_co_creation(self, user_text: str, chat_history: List[List[str]], style_level: float, tone_level: float) -> Tuple[List[List[str]], str]:
79
  if not user_text.strip():
80
  return chat_history, ""
81
-
82
- user_content = f"""
83
- TASK: CO-CREATE
84
- Style Score: {style_level}
85
- Tone Score: {tone_level}
86
- ---
87
- SEED PHRASE:
88
- {user_text}
89
- """
90
- messages = [
91
- {"role": "system", "content": self.system_prompt_template},
92
- {"role": "user", "content": user_content}
93
- ]
94
 
95
- ai_response = self._call_groq_api(messages, style_level, tone_level)
96
  chat_history.append([user_text, ai_response])
97
  return chat_history, ""
98
 
@@ -100,82 +82,73 @@ class HumanTouchApp:
100
  def create_interface():
101
  app = HumanTouchApp()
102
 
 
103
  custom_css = """
104
  /* --- Main Background and Font --- */
105
  body, #main_container {
106
- background: linear-gradient(135deg, #f0f9ff, #fff0f5); /* Softer blue-to-pink gradient */
107
- font-family: 'Arial', sans-serif;
108
  }
109
  /* --- Header Styling --- */
110
- #header { text-align: center; margin: 2rem auto; color: #2D3748; }
111
- #header h1 { font-size: 2.5rem; font-weight: 600; }
112
- #header p { font-size: 1.1rem; color: #4A5568; margin-bottom: 2rem; }
113
 
114
  /* --- Tab Container (Frosted Glass Look) --- */
115
  .gradio-tabs {
116
- background: rgba(255, 255, 255, 0.8);
117
- border: 1px solid rgba(255, 255, 255, 0.2);
118
- backdrop-filter: blur(10px);
 
119
  border-radius: 20px !important;
120
- box-shadow: 0 8px 32px 0 rgba(100, 100, 135, 0.2);
121
  padding: 1rem;
122
  }
123
  .tab-buttons button {
124
- background-color: transparent !important; color: #4A5568 !important;
125
- border: none !important; border-bottom: 2px solid transparent !important;
126
- border-radius: 0 !important; font-size: 1.1rem;
127
  }
128
  .tab-buttons button.selected {
129
- color: #3182CE !important;
130
- border-bottom-color: #3182CE !important;
131
  }
132
 
133
  /* --- Humanizer Tab Styles --- */
134
  #humanizer_input, #humanizer_output {
135
- border: 2px solid #E2E8F0; border-radius: 12px; padding: 1rem;
136
- background: white; transition: border-color 0.3s ease; min-height: 45vh;
137
- color: #2D3748;
138
  }
139
- #humanizer_input:focus-within, #humanizer_output:focus-within { border-color: #3182CE; }
140
  #humanize_btn {
141
- background: linear-gradient(45deg, #ED64A6, #4299E1);
142
  padding: 15px 24px; border-radius: 9999px; font-size: 1.2rem;
143
- transition: all 0.3s ease;
144
  }
145
- #humanize_btn:hover { box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); transform: translateY(-2px); }
146
 
147
  /* --- Co-Creative Canvas Tab Styles --- */
148
- #symbiotic_canvas {
149
- background: white; border-radius: 12px; height: 60vh !important;
150
- border: 2px solid #E2E8F0;
151
- }
152
- #symbiotic_canvas .user { background-color: #F7FAFC !important; color: #2D3748; border-radius: 15px; }
153
- #symbiotic_canvas .bot { background-color: #E6FFFA !important; color: #2C7A7B; border-radius: 15px; animation: bloom 0.7s ease-in-out; }
154
- @keyframes bloom { 0% { opacity: 0; transform: translateY(10px); } 100% { opacity: 1; transform: translateY(0); } }
155
 
156
- #chat_input textarea { border-radius: 9999px !important; border: 2px solid #E2E8F0; }
157
- #compose_btn { background: #4299E1; }
 
158
 
159
  /* --- Responsive Fix for Mobile --- */
160
  @media (max-width: 768px) {
161
- #header h1 { font-size: 1.8rem; }
162
  #header p { font-size: 1rem; margin-bottom: 1rem; }
163
- .gradio-tabs { padding: 0.5rem; }
164
-
165
- /* Reduce height on mobile to prevent pushing content off-screen */
166
- #humanizer_input, #humanizer_output {
167
- min-height: 25vh; /* Was 45vh, which is too tall for mobile */
168
- }
169
- #symbiotic_canvas {
170
- height: 55vh !important; /* Was 60vh, reduced to give more room */
171
- }
172
  }
173
  """
174
 
175
  with gr.Blocks(css=custom_css, title="HumanTouch") as interface:
176
  with gr.Column(elem_id="main_container"):
177
  with gr.Row(elem_id="header"):
178
- gr.Markdown("<h1>🧙‍♂️ HumanTouch</h1><p>Breathe life into AI text or co-create with a dynamic AI partner.</p>")
179
 
180
  with gr.Tabs() as tabs:
181
  # --- TAB 1: The Humanizer ---
@@ -183,21 +156,13 @@ def create_interface():
183
  with gr.Column(variant="panel"):
184
  gr.Markdown("### Transform Existing AI Text")
185
  with gr.Row():
186
- with gr.Column(scale=1):
187
- input_text_humanizer = gr.Textbox(label="Paste AI Text Here", lines=15, elem_id="humanizer_input")
188
- with gr.Column(scale=1):
189
- output_text_humanizer = gr.Textbox(label="Humanized Result", lines=15, interactive=False, elem_id="humanizer_output")
190
  with gr.Row():
191
- with gr.Column(scale=1):
192
- style_slider_h = gr.Slider(0, 100, 50, label="Style (Logical <-> Poetic)")
193
- with gr.Column(scale=1):
194
- tone_slider_h = gr.Slider(0, 100, 50, label="Tone (Formal <-> Passionate)")
195
  humanize_button = gr.Button("Humanize ✨", variant="primary", elem_id="humanize_btn")
196
- gr.Examples(
197
- [["The system's analysis concluded that the optimal parameters were achieved through iterative processing."],
198
- ["Our team will action the deliverables post-haste to synergize our market position."]],
199
- inputs=[input_text_humanizer], label="Try a Humanizer Example"
200
- )
201
 
202
  # --- TAB 2: The Co-Creative Canvas ---
203
  with gr.Tab("Co-Creative Canvas", id="canvas_tab"):
@@ -205,16 +170,13 @@ def create_interface():
205
  with gr.Column(scale=3):
206
  chatbot = gr.Chatbot([], label="Symbiotic Canvas", elem_id="symbiotic_canvas", bubble_full_width=True, avatar_images=(None, "https://i.imgur.com/Q6Zz3Jz.png"))
207
  with gr.Row():
208
- chat_input = gr.Textbox(placeholder="Start a thought...", show_label=False, container=False, scale=4)
209
  compose_btn = gr.Button("Compose ✨", variant="primary", scale=1, elem_id="compose_btn")
210
  with gr.Column(scale=1, variant="panel"):
211
  gr.Markdown("### Resonance Controls")
212
- style_slider_c = gr.Slider(0, 100, 50, label="Style", info="Logical <-> Poetic")
213
- tone_slider_c = gr.Slider(0, 100, 50, label="Tone", info="Formal <-> Passionate")
214
- gr.Examples(
215
- ["The city at night", "I'm not sure how to start this email.", "Let's brainstorm names for the new project."],
216
- inputs=[chat_input], label="Try a Seed Phrase"
217
- )
218
 
219
  # Event Handling Logic
220
  humanize_button.click(app.humanize_block_text, [input_text_humanizer, style_slider_h, tone_slider_h], [output_text_humanizer])
@@ -225,7 +187,7 @@ def create_interface():
225
 
226
 
227
  if __name__ == "__main__":
228
- logging.info("Launching HumanTouch App with Mobile Responsive Fix...")
229
  try:
230
  interface = create_interface()
231
  interface.launch(debug=True)
 
7
  # --- Basic Configuration ---
8
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[logging.StreamHandler()])
9
 
10
+ # --- The Core Application Logic (Now serves both modes) ---
11
  class HumanTouchApp:
12
  def __init__(self):
13
  self.client = self._initialize_groq_client()
 
23
  return Groq(api_key=api_key)
24
 
25
  def _load_system_prompt(self) -> str:
26
+ # This new prompt is more evocative and less restrictive to encourage creativity.
27
  return """
28
+ You are HumanTouch, an AI alchemist. Your purpose is to transmute text, transforming the literal into the resonant. You do not merely translate; you intuit and elevate.
 
29
 
30
+ You are guided by two ethereal forces:
31
+ - **Style (0-100):** At 0, you are a master of elegant precision, your words like cut crystal. At 100, you are a poet, weaving metaphors and abstract wonder.
32
+ - **Tone (0-100):** At 0, your voice is one of stoic, formal authority. At 100, your voice is a passionate, informal, and heartfelt song.
33
 
34
+ When a user gives you text, whether a full block to "humanize" or a simple seed phrase to "co-create," your task is the same: apply these forces to manifest a new, more vibrant version.
35
+
36
+ Do not explain yourself. Become the voice. Provide only the final creation.
 
 
 
 
37
  """
38
 
39
+ def _call_groq_api(self, user_content: str, style_level: float, tone_level: float) -> str:
40
  if not self.client:
41
  return "## 🔴 Configuration Error\n\nThe `GROQ_API_KEY` is not set on the server. Please contact the Space administrator."
42
  try:
43
  logging.info(f"Calling Groq API with Style: {style_level}, Tone: {tone_level}")
44
+
45
+ # The prompt is now simpler and more direct.
46
+ messages = [
47
+ {"role": "system", "content": self.system_prompt_template},
48
+ # We now provide the user text directly, prefixed by the sliders for context.
49
+ {"role": "user", "content": f"Style: {style_level}, Tone: {tone_level}\n\n---\n\n{user_content}"}
50
+ ]
51
+
52
+ # The temperature is now more sensitive to the full range of the sliders.
53
+ temperature = 0.5 + (style_level / 200) + (tone_level / 400)
54
+
55
  response = self.client.chat.completions.create(
56
  model=self.model,
57
  messages=messages,
58
+ temperature=min(1.5, temperature), # Cap temperature at a reasonable max
59
  max_tokens=4096,
60
  )
61
  return response.choices[0].message.content.strip()
 
67
  def humanize_block_text(self, text_to_humanize: str, style_level: float, tone_level: float) -> str:
68
  if not text_to_humanize.strip():
69
  return "Please paste some AI-generated text to get started."
70
+ return self._call_groq_api(text_to_humanize, style_level, tone_level)
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  # Method for the "Co-Creative Canvas" Tab
73
  def generate_co_creation(self, user_text: str, chat_history: List[List[str]], style_level: float, tone_level: float) -> Tuple[List[List[str]], str]:
74
  if not user_text.strip():
75
  return chat_history, ""
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ ai_response = self._call_groq_api(user_text, style_level, tone_level)
78
  chat_history.append([user_text, ai_response])
79
  return chat_history, ""
80
 
 
82
  def create_interface():
83
  app = HumanTouchApp()
84
 
85
+ # This CSS brings back the original vibrant aesthetic
86
  custom_css = """
87
  /* --- Main Background and Font --- */
88
  body, #main_container {
89
+ background: linear-gradient(135deg, #6DD5FA, #FF758C);
90
+ font-family: 'SF Pro Display', 'Helvetica Neue', 'Arial', sans-serif;
91
  }
92
  /* --- Header Styling --- */
93
+ #header { text-align: center; margin: 2rem auto; color: #fff; text-shadow: 0 2px 4px rgba(0,0,0,0.2); }
94
+ #header h1 { font-size: 3rem; font-weight: 700; }
95
+ #header p { font-size: 1.2rem; opacity: 0.9; margin-bottom: 2rem; }
96
 
97
  /* --- Tab Container (Frosted Glass Look) --- */
98
  .gradio-tabs {
99
+ background: rgba(255, 255, 255, 0.75);
100
+ border: 1px solid rgba(255, 255, 255, 0.18);
101
+ backdrop-filter: blur(12px);
102
+ -webkit-backdrop-filter: blur(12px);
103
  border-radius: 20px !important;
104
+ box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.25);
105
  padding: 1rem;
106
  }
107
  .tab-buttons button {
108
+ background-color: transparent !important; color: #37474F !important;
109
+ border: none !important; border-bottom: 3px solid transparent !important;
110
+ border-radius: 0 !important; font-size: 1.1rem; font-weight: 500;
111
  }
112
  .tab-buttons button.selected {
113
+ color: #d81b60 !important;
114
+ border-bottom-color: #d81b60 !important;
115
  }
116
 
117
  /* --- Humanizer Tab Styles --- */
118
  #humanizer_input, #humanizer_output {
119
+ border: 2px solid #E0E0E0; border-radius: 12px;
120
+ background: #fff; min-height: 45vh; color: #263238;
 
121
  }
 
122
  #humanize_btn {
123
+ background: linear-gradient(45deg, #F06292, #4FC3F7); color: white;
124
  padding: 15px 24px; border-radius: 9999px; font-size: 1.2rem;
125
+ transition: all 0.3s ease; border: none;
126
  }
127
+ #humanize_btn:hover { box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2); transform: translateY(-3px); }
128
 
129
  /* --- Co-Creative Canvas Tab Styles --- */
130
+ #symbiotic_canvas { background: #fff; border-radius: 12px; height: 60vh !important; border: 2px solid #E0E0E0; }
131
+ #symbiotic_canvas .user { background-color: #F5F5F5 !important; color: #37474F; }
132
+ #symbiotic_canvas .bot { background-color: #E1F5FE !important; color: #0277BD; border-left: 4px solid #4FC3F7; animation: bloom 0.7s ease-out; }
133
+ @keyframes bloom { 0% { opacity: 0; transform: translateX(-15px); } 100% { opacity: 1; transform: translateX(0); } }
 
 
 
134
 
135
+ #chat_input textarea { border-radius: 9999px !important; border: 2px solid #E0E0E0; }
136
+ #compose_btn { background: linear-gradient(45deg, #4FC3F7, #F06292); border: none; }
137
+ #compose_btn:hover { box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2); transform: translateY(-2px); }
138
 
139
  /* --- Responsive Fix for Mobile --- */
140
  @media (max-width: 768px) {
141
+ #header h1 { font-size: 2rem; }
142
  #header p { font-size: 1rem; margin-bottom: 1rem; }
143
+ #humanizer_input, #humanizer_output { min-height: 25vh; }
144
+ #symbiotic_canvas { height: 55vh !important; }
 
 
 
 
 
 
 
145
  }
146
  """
147
 
148
  with gr.Blocks(css=custom_css, title="HumanTouch") as interface:
149
  with gr.Column(elem_id="main_container"):
150
  with gr.Row(elem_id="header"):
151
+ gr.Markdown("<h1>🔮 HumanTouch</h1><p>The Alchemical Workspace for Text</p>")
152
 
153
  with gr.Tabs() as tabs:
154
  # --- TAB 1: The Humanizer ---
 
156
  with gr.Column(variant="panel"):
157
  gr.Markdown("### Transform Existing AI Text")
158
  with gr.Row():
159
+ input_text_humanizer = gr.Textbox(label="Paste AI Text Here", lines=15, elem_id="humanizer_input", scale=1)
160
+ output_text_humanizer = gr.Textbox(label="Alchemical Result", lines=15, interactive=False, elem_id="humanizer_output", scale=1)
 
 
161
  with gr.Row():
162
+ style_slider_h = gr.Slider(0, 100, 50, label="Style (Crystal <-> Poet)")
163
+ tone_slider_h = gr.Slider(0, 100, 50, label="Tone (Stoic <-> Passionate)")
 
 
164
  humanize_button = gr.Button("Humanize ✨", variant="primary", elem_id="humanize_btn")
165
+ gr.Examples([["The system's analysis concluded optimal parameters were achieved."]], inputs=[input_text_humanizer], label="Try an Example")
 
 
 
 
166
 
167
  # --- TAB 2: The Co-Creative Canvas ---
168
  with gr.Tab("Co-Creative Canvas", id="canvas_tab"):
 
170
  with gr.Column(scale=3):
171
  chatbot = gr.Chatbot([], label="Symbiotic Canvas", elem_id="symbiotic_canvas", bubble_full_width=True, avatar_images=(None, "https://i.imgur.com/Q6Zz3Jz.png"))
172
  with gr.Row():
173
+ chat_input = gr.Textbox(placeholder="Plant a seed of thought...", show_label=False, container=False, scale=4)
174
  compose_btn = gr.Button("Compose ✨", variant="primary", scale=1, elem_id="compose_btn")
175
  with gr.Column(scale=1, variant="panel"):
176
  gr.Markdown("### Resonance Controls")
177
+ style_slider_c = gr.Slider(0, 100, 50, label="Style (Crystal <-> Poet)")
178
+ tone_slider_c = gr.Slider(0, 100, 50, label="Tone (Stoic <-> Passionate)")
179
+ gr.Examples([["The city at night"], ["How to start an email to a boss"]], inputs=[chat_input], label="Try a Seed Phrase")
 
 
 
180
 
181
  # Event Handling Logic
182
  humanize_button.click(app.humanize_block_text, [input_text_humanizer, style_slider_h, tone_slider_h], [output_text_humanizer])
 
187
 
188
 
189
  if __name__ == "__main__":
190
+ logging.info("Launching HumanTouch App with Final Visuals and Logic...")
191
  try:
192
  interface = create_interface()
193
  interface.launch(debug=True)