Spaces:
Running
Running
# 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) |