File size: 8,138 Bytes
bd29e94
 
 
 
 
 
 
 
 
 
 
 
 
 
77ad748
 
 
 
f2b25c4
77ad748
 
f2b25c4
77ad748
 
 
f2b25c4
 
77ad748
 
 
f2b25c4
 
 
77ad748
 
f11d2de
77ad748
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28c8a29
77ad748
f2b25c4
77ad748
 
28c8a29
 
77ad748
 
 
 
 
f2b25c4
77ad748
f2b25c4
 
 
77ad748
 
f2b25c4
77ad748
28c8a29
f2b25c4
475494d
f2b25c4
28c8a29
f2b25c4
 
 
 
 
475494d
28c8a29
b27d5b2
28c8a29
b27d5b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28c8a29
77ad748
 
28c8a29
 
 
 
f2b25c4
ca65f7f
28c8a29
 
 
 
 
 
 
 
3ef4a24
28c8a29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77ad748
 
 
f2b25c4
77ad748
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# Copyright 2024 Christopher Woodyard
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import logging
import gradio as gr
from groq import Groq
import requests

# Initialize logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Initialize Groq client
try:
    client = Groq(api_key=os.environ.get("GROQ_API_KEY"))
    logging.info("Groq client initialized successfully")
except KeyError:
    logging.error("GROQ_API_KEY not found in environment variables")
    raise EnvironmentError("Please set the GROQ_API_KEY environment variable")
except Exception as e:
    logging.error(f"Error initializing Groq client: {e}")
    raise

# Specify the actual model name
GROQ_MODEL = "llama-3.3-70b-versatile"  # Replace with the actual model you want to use

SYSTEM_PROMPT = """
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:

1. Preserve the core meaning and information of the original text.
2. Maintain the overall structure, including paragraph breaks and any headings or subheadings.
3. Adjust the writing style to be more natural and conversational, as if written by a skilled human writer.
4. Vary sentence structure, using a mix of simple, compound, and complex sentences to improve flow and readability.
5. Introduce subtle imperfections that are characteristic of human writing, such as:
   - Occasional use of contractions (e.g., "it's", "don't", "we're")
   - Varied paragraph lengths
   - Strategic use of transition words and phrases
   - Occasional parenthetical asides or brief digressions
   - Subtle voice and tone shifts that maintain consistency but add depth

6. Refine vocabulary choices to be more nuanced and context-appropriate, avoiding overly formal or repetitive language.
7. Ensure proper use of idioms, colloquialisms, and figures of speech where appropriate, but don't overuse them.
8. Maintain consistent tense and point of view throughout the text.
9. Preserve any technical terms, proper nouns, or specific jargon present in the original text.
10. Aim to keep the word count within 5% of the original text.

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.
"""

USER_PROMPT = """
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.

Original text:
{input_text}

Humanized version:
"""

def humanize_text(AI_text, creativity_level):
    try:
        logging.info(f"Attempting to humanize text with creativity level: {creativity_level}")
        response = client.chat.completions.create(
            model=GROQ_MODEL,
            temperature=0.4 + (creativity_level * 0.1),  # Adjust temperature based on creativity level
            max_tokens=2000,
            messages=[
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": USER_PROMPT.format(input_text=AI_text)}
            ]
        )
        logging.info("Text humanization successful")
        return response.choices[0].message.content.strip()
    except requests.exceptions.RequestException as e:
        logging.error(f"Network error during humanization: {e}")
        return "A network error occurred while processing the text. Please check your internet connection and try again."
    except Exception as e:
        logging.error(f"Error during humanization: {e}")
        return f"An error occurred while processing the text: {str(e)}"

def main_function(AI_text, creativity_level):
    if not AI_text.strip():
        return "Please enter some text to humanize.", "Input word count: 0"
    
    humanized = humanize_text(AI_text, creativity_level)
    input_word_count = len(AI_text.split())
    output_word_count = len(humanized.split())
    
    word_count_info = f"Input word count: {input_word_count}, Output word count: {output_word_count}"
    
    return humanized, word_count_info

# Custom CSS for colorful styling
custom_css = """
body {
    background: linear-gradient(135deg, #6DD5FA, #FF758C);
    font-family: 'Arial', sans-serif;
}
.container {
    max-width: 800px;
    margin: auto;
    padding: 20px;
    background: rgba(255, 255, 255, 0.8);
    border-radius: 15px;
    box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
}
.title {
    text-align: center;
    color: #4A4A4A;
    font-size: 2.5em;
    margin-bottom: 20px;
    text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
}
.description {
    text-align: center;
    color: #5D5D5D;
    margin-bottom: 30px;
}
.input-box, .output-box {
    border: 2px solid #B0E0E6;
    border-radius: 10px;
    padding: 15px;
    background-color: white;
    transition: all 0.3s ease;
}
.input-box:focus, .output-box:focus {
    box-shadow: 0 0 10px #B0E0E6;
}
.slider {
    margin-top: 20px;
    margin-bottom: 20px;
}
.word-count {
    text-align: right;
    color: #7f8c8d;
    font-style: italic;
}
button.primary {
    background: linear-gradient(45deg, #FF6B6B, #4ECDC4);
    border: none;
    color: white;
    padding: 10px 20px;
    border-radius: 25px;
    font-weight: bold;
    transition: all 0.3s ease;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}
button.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
}
"""

# Gradio interface definition
with gr.Blocks(css=custom_css) as interface:
    gr.Markdown(
    """
    <div class="container">
        <h1 class="title">🧙‍♂️HumanTouch App</h1>
        <p class="description">Transform AI-generated text into a vibrant human-crafted masterpiece! Created by Vers3Dynamics</p>
    </div>
    """
    )
    
    with gr.Row():
        with gr.Column():
            input_text = gr.Textbox(label="Input AI-generated text", lines=10, placeholder="Paste your AI-generated text here...", elem_classes="input-box")
            creativity_level = gr.Slider(minimum=0, maximum=6, value=3, step=1, label="Creativity Level", info="Adjust the creativity of the humanization process")
            humanize_button = gr.Button("Midas Touch👈", variant="primary")
        
        with gr.Column():
            output_text = gr.Textbox(label="Humanized text", lines=10, elem_classes="output-box")
            word_count = gr.Markdown(elem_classes="word-count")
    
    examples = gr.Examples(
        examples=[
            ["The artificial intelligence system processed the data and concluded that the optimal solution was to implement a new algorithm for efficient resource allocation.", 3],
            ["The robotic assistant scanned the room, identifying objects and their locations with precise accuracy, before proceeding to execute its predetermined cleaning routine.", 4]
        ],
        inputs=[input_text, creativity_level]
    )
    
    humanize_button.click(
        main_function,
        inputs=[input_text, creativity_level],
        outputs=[output_text, word_count],
    )
    
    input_text.change(
        lambda x: f"Input word count: {len(x.split())}",
        inputs=[input_text],
        outputs=[word_count]
    )

# Launch the Gradio app
if __name__ == "__main__":
    logging.info("Starting HumanTouch App")
    interface.launch(debug=True)