ciaochris commited on
Commit
15cb681
·
verified ·
1 Parent(s): 625d1dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +187 -178
app.py CHANGED
@@ -1,208 +1,217 @@
1
  # Copyright 2024 Christopher Woodyard
2
- #
3
- # Licensed under the Apache License, Version 2.0 (the "License");
4
- # you may not use this file except in compliance with the License.
5
- # You may obtain a copy of the License at
6
- #
7
- # http://www.apache.org/licenses/LICENSE-2.0
8
- #
9
- # Unless required by applicable law or agreed to in writing, software
10
- # distributed under the License is distributed on an "AS IS" BASIS,
11
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- # See the License for the specific language governing permissions and
13
- # limitations under the License.
14
 
15
  import os
16
  import logging
17
  import gradio as gr
18
  from groq import Groq
19
  import requests
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
- # Initialize logging
22
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
23
-
24
- # Initialize Groq client
25
- try:
26
- client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
27
- logging.info("Groq client initialized successfully")
28
- except KeyError:
29
- logging.error("GROQ_API_KEY not found in environment variables")
30
- raise EnvironmentError("Please set the GROQ_API_KEY environment variable")
31
- except Exception as e:
32
- logging.error(f"Error initializing Groq client: {e}")
33
- raise
34
-
35
- # Specify the actual model name
36
- GROQ_MODEL = "llama-3.3-70b-versatile" # Replace with the actual model you want to use
37
-
38
- SYSTEM_PROMPT = """
39
- You are an expert in natural language processing and writing, specializing in transforming AI-generated text into highly natural, human-like prose. Your task is to refine and humanize the given text while adhering to the following guidelines:
40
-
41
- 1. Preserve the core meaning and information of the original text.
42
- 2. Maintain the overall structure, including paragraph breaks and any headings or subheadings.
43
- 3. Adjust the writing style to be more natural and conversational, as if written by a skilled human writer.
44
- 4. Vary sentence structure, using a mix of simple, compound, and complex sentences to improve flow and readability.
45
- 5. Introduce subtle imperfections that are characteristic of human writing, such as:
46
- - Occasional use of contractions (e.g., "it's", "don't", "we're")
47
- - Varied paragraph lengths
48
- - Strategic use of transition words and phrases
49
- - Occasional parenthetical asides or brief digressions
50
- - Subtle voice and tone shifts that maintain consistency but add depth
51
-
52
- 6. Refine vocabulary choices to be more nuanced and context-appropriate, avoiding overly formal or repetitive language.
53
- 7. Ensure proper use of idioms, colloquialisms, and figures of speech where appropriate, but don't overuse them.
54
- 8. Maintain consistent tense and point of view throughout the text.
55
- 9. Preserve any technical terms, proper nouns, or specific jargon present in the original text.
56
- 10. Aim to keep the word count within 5% of the original text.
57
-
58
- Remember, the goal is to make the text feel authentically human-written while retaining its original purpose and information. Strive for a balance between polish and natural imperfection that characterizes high-quality human writing.
59
- """
60
-
61
- USER_PROMPT = """
62
- Please humanize the following text, applying the guidelines provided. Ensure the output reads as if it were written by a skilled human writer, with natural flow and subtle imperfections. Maintain the original meaning and structure while enhancing its overall quality and readability.
63
-
64
- Original text:
65
- {input_text}
66
-
67
- Humanized version:
68
- """
69
-
70
- def humanize_text(AI_text, creativity_level):
71
- try:
72
- logging.info(f"Attempting to humanize text with creativity level: {creativity_level}")
73
- response = client.chat.completions.create(
74
- model=GROQ_MODEL,
75
- temperature=0.4 + (creativity_level * 0.1), # Adjust temperature based on creativity level
76
- max_tokens=2000,
77
- messages=[
78
- {"role": "system", "content": SYSTEM_PROMPT},
79
- {"role": "user", "content": USER_PROMPT.format(input_text=AI_text)}
80
- ]
81
- )
82
- logging.info("Text humanization successful")
83
- return response.choices[0].message.content.strip()
84
- except requests.exceptions.RequestException as e:
85
- logging.error(f"Network error during humanization: {e}")
86
- return "A network error occurred while processing the text. Please check your internet connection and try again."
87
- except Exception as e:
88
- logging.error(f"Error during humanization: {e}")
89
- return f"An error occurred while processing the text: {str(e)}"
90
-
91
- def main_function(AI_text, creativity_level):
92
- if not AI_text.strip():
93
- return "Please enter some text to humanize.", "Input word count: 0"
94
-
95
- humanized = humanize_text(AI_text, creativity_level)
96
- input_word_count = len(AI_text.split())
97
- output_word_count = len(humanized.split())
98
-
99
- word_count_info = f"Input word count: {input_word_count}, Output word count: {output_word_count}"
100
-
101
- return humanized, word_count_info
102
-
103
- # Custom CSS for colorful styling
104
  custom_css = """
105
  body {
106
  background: linear-gradient(135deg, #6DD5FA, #FF758C);
107
  font-family: 'Arial', sans-serif;
 
108
  }
109
  .container {
110
- max-width: 800px;
111
- margin: auto;
112
- padding: 20px;
113
- background: rgba(255, 255, 255, 0.8);
114
- border-radius: 15px;
115
- box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
116
- }
117
- .title {
118
- text-align: center;
119
- color: #4A4A4A;
120
- font-size: 2.5em;
121
- margin-bottom: 20px;
122
- text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
123
- }
124
- .description {
125
- text-align: center;
126
- color: #5D5D5D;
127
- margin-bottom: 30px;
128
  }
 
 
129
  .input-box, .output-box {
130
- border: 2px solid #B0E0E6;
131
- border-radius: 10px;
132
- padding: 15px;
133
- background-color: white;
134
- transition: all 0.3s ease;
135
  }
136
  .input-box:focus, .output-box:focus {
137
- box-shadow: 0 0 10px #B0E0E6;
138
- }
139
- .slider {
140
- margin-top: 20px;
141
- margin-bottom: 20px;
142
  }
143
- .word-count {
144
- text-align: right;
145
- color: #7f8c8d;
146
- font-style: italic;
147
  }
148
  button.primary {
149
- background: linear-gradient(45deg, #FF6B6B, #4ECDC4);
150
- border: none;
151
- color: white;
152
- padding: 10px 20px;
153
- border-radius: 25px;
154
- font-weight: bold;
155
- transition: all 0.3s ease;
156
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
157
  }
158
  button.primary:hover {
159
- transform: translateY(-2px);
160
- box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
161
  }
 
162
  """
163
 
164
- # Gradio interface definition
165
- with gr.Blocks(css=custom_css) as interface:
166
- gr.Markdown(
167
- """
168
- <div class="container">
169
- <h1 class="title">🧙‍♂️HumanTouch App</h1>
170
- <p class="description">Transform AI-generated text into a vibrant human-crafted masterpiece! Created by Vers3Dynamics</p>
171
- </div>
172
- """
173
- )
174
 
175
- with gr.Row():
176
- with gr.Column():
177
- input_text = gr.Textbox(label="Input AI-generated text", lines=10, placeholder="Paste your AI-generated text here...", elem_classes="input-box")
178
- creativity_level = gr.Slider(minimum=0, maximum=6, value=3, step=1, label="Creativity Level", info="Adjust the creativity of the humanization process")
179
- humanize_button = gr.Button("Midas Touch👈", variant="primary")
 
 
180
 
181
- with gr.Column():
182
- output_text = gr.Textbox(label="Humanized text", lines=10, elem_classes="output-box")
183
- word_count = gr.Markdown(elem_classes="word-count")
184
-
185
- examples = gr.Examples(
186
- examples=[
187
- ["The artificial intelligence system processed the data and concluded that the optimal solution was to implement a new algorithm for efficient resource allocation.", 3],
188
- ["The robotic assistant scanned the room, identifying objects and their locations with precise accuracy, before proceeding to execute its predetermined cleaning routine.", 4]
189
- ],
190
- inputs=[input_text, creativity_level]
191
- )
192
-
193
- humanize_button.click(
194
- main_function,
195
- inputs=[input_text, creativity_level],
196
- outputs=[output_text, word_count],
197
- )
198
-
199
- input_text.change(
200
- lambda x: f"Input word count: {len(x.split())}",
201
- inputs=[input_text],
202
- outputs=[word_count]
203
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
 
205
- # Launch the Gradio app
206
  if __name__ == "__main__":
207
- logging.info("Starting HumanTouch App")
208
- interface.launch(debug=True)
 
 
 
 
 
 
 
 
 
1
  # Copyright 2024 Christopher Woodyard
2
+ # Licensed under the Apache License, Version 2.0
3
+ # [License details remain unchanged]
 
 
 
 
 
 
 
 
 
 
4
 
5
  import os
6
  import logging
7
  import gradio as gr
8
  from groq import Groq
9
  import requests
10
+ from datetime import datetime
11
+ import json
12
+ from typing import Tuple, Optional
13
+
14
+ # Configure logging with file output
15
+ logging.basicConfig(
16
+ level=logging.INFO,
17
+ format='%(asctime)s - %(levelname)s - %(message)s',
18
+ handlers=[
19
+ logging.FileHandler(f'humantouch_{datetime.now().strftime("%Y%m%d")}.log'),
20
+ logging.StreamHandler()
21
+ ]
22
+ )
23
+
24
+ class HumanTouchApp:
25
+ def __init__(self):
26
+ self.client = self._initialize_groq_client()
27
+ self.model = "llama-3.3-70b-versatile"
28
+ self.system_prompt = self._load_system_prompt()
29
+ self.history_file = "processing_history.json"
30
+
31
+ def _initialize_groq_client(self) -> Groq:
32
+ """Initialize Groq client with error handling"""
33
+ try:
34
+ client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
35
+ logging.info("Groq client initialized successfully")
36
+ return client
37
+ except KeyError:
38
+ logging.error("GROQ_API_KEY not found in environment variables")
39
+ raise EnvironmentError("Please set the GROQ_API_KEY environment variable")
40
+ except Exception as e:
41
+ logging.error(f"Error initializing Groq client: {e}")
42
+ raise
43
+
44
+ def _load_system_prompt(self) -> str:
45
+ """Load and return the system prompt"""
46
+ return """
47
+ [Your existing SYSTEM_PROMPT remains unchanged]
48
+ """
49
+
50
+ def humanize_text(self, ai_text: str, creativity_level: float) -> str:
51
+ """Process text through Groq API for humanization"""
52
+ try:
53
+ logging.info(f"Humanizing text with creativity level: {creativity_level}")
54
+ response = self.client.chat.completions.create(
55
+ model=self.model,
56
+ temperature=min(1.0, 0.4 + (creativity_level * 0.1)),
57
+ max_tokens=4000, # Increased for longer texts
58
+ messages=[
59
+ {"role": "system", "content": self.system_prompt},
60
+ {"role": "user", "content": f"""
61
+ Please humanize the following text, applying the guidelines provided:
62
+ Original text:
63
+ {ai_text}
64
+ Humanized version:
65
+ """}
66
+ ]
67
+ )
68
+ result = response.choices[0].message.content.strip()
69
+ self._save_to_history(ai_text, result)
70
+ logging.info("Text humanization completed")
71
+ return result
72
+ except requests.exceptions.RequestException as e:
73
+ logging.error(f"Network error: {e}")
74
+ return f"Network error: {str(e)}. Please try again."
75
+ except Exception as e:
76
+ logging.error(f"Processing error: {e}")
77
+ return f"Error: {str(e)}"
78
+
79
+ def _save_to_history(self, input_text: str, output_text: str) -> None:
80
+ """Save processing history to JSON file"""
81
+ history_entry = {
82
+ "timestamp": datetime.now().isoformat(),
83
+ "input": input_text[:100], # Truncate for storage efficiency
84
+ "output": output_text[:100],
85
+ "input_length": len(input_text.split())
86
+ }
87
+
88
+ try:
89
+ history = []
90
+ if os.path.exists(self.history_file):
91
+ with open(self.history_file, 'r') as f:
92
+ history = json.load(f)
93
+ history.append(history_entry)
94
+ with open(self.history_file, 'w') as f:
95
+ json.dump(history[-100:], f) # Keep last 100 entries
96
+ except Exception as e:
97
+ logging.warning(f"Failed to save history: {e}")
98
+
99
+ def process_text(self, ai_text: str, creativity_level: float) -> Tuple[str, str]:
100
+ """Main processing function with validation"""
101
+ if not ai_text.strip():
102
+ return "Please provide text to humanize.", "Input word count: 0"
103
+
104
+ humanized = self.humanize_text(ai_text, creativity_level)
105
+ input_count = len(ai_text.split())
106
+ output_count = len(humanized.split())
107
+
108
+ stats = (f"Input words: {input_count} | Output words: {output_count} | "
109
+ f"Change: {((output_count - input_count) / input_count * 100):.1f}%")
110
+ return humanized, stats
111
 
112
+ # Enhanced CSS with better responsiveness
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  custom_css = """
114
  body {
115
  background: linear-gradient(135deg, #6DD5FA, #FF758C);
116
  font-family: 'Arial', sans-serif;
117
+ min-height: 100vh;
118
  }
119
  .container {
120
+ max-width: 900px;
121
+ margin: 2rem auto;
122
+ padding: 2rem;
123
+ background: rgba(255, 255, 255, 0.9);
124
+ border-radius: 20px;
125
+ box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
 
 
 
 
 
 
 
 
 
 
 
 
126
  }
127
+ .title { font-size: 2.5rem; color: #2D3748; }
128
+ .description { color: #4A5568; }
129
  .input-box, .output-box {
130
+ border: 2px solid #63B3ED;
131
+ border-radius: 12px;
132
+ padding: 1rem;
133
+ background: white;
134
+ transition: border-color 0.3s ease;
135
  }
136
  .input-box:focus, .output-box:focus {
137
+ border-color: #3182CE;
138
+ box-shadow: 0 0 8px rgba(49, 130, 206, 0.3);
 
 
 
139
  }
140
+ @media (max-width: 768px) {
141
+ .container { margin: 1rem; padding: 1rem; }
142
+ .title { font-size: 2rem; }
 
143
  }
144
  button.primary {
145
+ background: linear-gradient(45deg, #ED64A6, #4299E1);
146
+ padding: 12px 24px;
147
+ border-radius: 9999px;
 
 
 
 
 
148
  }
149
  button.primary:hover {
150
+ background: linear-gradient(45deg, #F687B3, #5A67D8);
 
151
  }
152
+ .stats { color: #718096; font-size: 0.9rem; }
153
  """
154
 
155
+ def create_interface():
156
+ app = HumanTouchApp()
 
 
 
 
 
 
 
 
157
 
158
+ with gr.Blocks(css=custom_css, title="HumanTouch") as interface:
159
+ gr.Markdown("""
160
+ <div class="container">
161
+ <h1 class="title">🧙‍♂️ HumanTouch App</h1>
162
+ <p class="description">Breathe life into AI text with human-like finesse! Powered by Vers3Dynamics</p>
163
+ </div>
164
+ """)
165
 
166
+ with gr.Row(equal_height=False):
167
+ with gr.Column(scale=1):
168
+ input_text = gr.Textbox(
169
+ label="AI-Generated Text",
170
+ lines=12,
171
+ placeholder="Paste your AI text here...",
172
+ elem_classes="input-box"
173
+ )
174
+ creativity = gr.Slider(
175
+ 0, 6, 3, step=1,
176
+ label="Creativity Level",
177
+ info="Higher values increase creative liberty (0-6)"
178
+ )
179
+ btn = gr.Button("Humanize ✨", variant="primary")
180
+
181
+ with gr.Column(scale=1):
182
+ output_text = gr.Textbox(
183
+ label="Humanized Result",
184
+ lines=12,
185
+ interactive=False,
186
+ elem_classes="output-box"
187
+ )
188
+ stats = gr.Markdown(elem_classes="stats")
189
+
190
+ gr.Examples(
191
+ examples=[
192
+ ["The system analyzed the dataset and determined optimal parameters.", 3],
193
+ ["The AI assistant completed its task sequence efficiently.", 4]
194
+ ],
195
+ inputs=[input_text, creativity]
196
+ )
197
+
198
+ btn.click(app.process_text, [input_text, creativity], [output_text, stats])
199
+ input_text.change(
200
+ lambda x: f"Input words: {len(x.split())}",
201
+ inputs=[input_text],
202
+ outputs=[stats]
203
+ )
204
+
205
+ return interface
206
 
 
207
  if __name__ == "__main__":
208
+ logging.info("Launching HumanTouch App")
209
+ try:
210
+ interface = create_interface()
211
+ interface.launch(
212
+ debug=True,
213
+ server_name="0.0.0.0",
214
+ share=True # Enable public sharing option
215
+ )
216
+ except Exception as e:
217
+ logging.error(f"Application launch failed: {e}")