Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,64 +1,211 @@
|
|
| 1 |
import gradio as gr
|
| 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 |
if __name__ == "__main__":
|
| 64 |
-
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import AutoTokenizer, T5ForConditionalGeneration, pipeline
|
| 4 |
+
from sentence_transformers import SentenceTransformer, util
|
| 5 |
+
import random
|
| 6 |
+
import re
|
| 7 |
+
import nltk
|
| 8 |
+
from nltk.tokenize import sent_tokenize
|
| 9 |
+
import warnings
|
| 10 |
+
from transformers import logging
|
| 11 |
+
import os
|
| 12 |
+
import tensorflow as tf
|
| 13 |
+
import requests
|
| 14 |
+
|
| 15 |
+
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
|
| 16 |
+
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
| 17 |
+
warnings.filterwarnings("ignore", category=FutureWarning)
|
| 18 |
+
warnings.filterwarnings("ignore", category=UserWarning)
|
| 19 |
+
warnings.filterwarnings("ignore")
|
| 20 |
+
logging.set_verbosity_error()
|
| 21 |
+
tf.get_logger().setLevel('ERROR')
|
| 22 |
+
|
| 23 |
+
nltk.download('punkt')
|
| 24 |
+
GROQ_API_KEY="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"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class TextEnhancer:
|
| 28 |
+
def __init__(self):
|
| 29 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 30 |
+
print(self.device)
|
| 31 |
+
self.paraphrase_tokenizer = AutoTokenizer.from_pretrained("prithivida/parrot_paraphraser_on_T5")
|
| 32 |
+
self.paraphrase_model = T5ForConditionalGeneration.from_pretrained("prithivida/parrot_paraphraser_on_T5").to(self.device)
|
| 33 |
+
print("paraphraser loaded")
|
| 34 |
+
self.grammar_pipeline = pipeline(
|
| 35 |
+
"text2text-generation",
|
| 36 |
+
model="Grammarly/coedit-large",
|
| 37 |
+
device=0 if self.device == "cuda" else -1
|
| 38 |
+
)
|
| 39 |
+
print("grammar check loaded")
|
| 40 |
+
self.similarity_model = SentenceTransformer('paraphrase-MiniLM-L6-v2').to(self.device)
|
| 41 |
+
print("sementics model loaded")
|
| 42 |
+
def _evaluate_with_groq(self, passage=""):
|
| 43 |
+
if not passage:
|
| 44 |
+
raise ValueError("Input passage cannot be empty.")
|
| 45 |
+
|
| 46 |
+
# Groq API setup
|
| 47 |
+
headers = {
|
| 48 |
+
"Authorization": f"Bearer {GROQ_API_KEY}", # Replace GROQ_API_KEY with your actual API key.
|
| 49 |
+
"Content-Type": "application/json"
|
| 50 |
+
}
|
| 51 |
+
payload = {
|
| 52 |
+
"model": "llama3-70b-8192",
|
| 53 |
+
"messages": [
|
| 54 |
+
{
|
| 55 |
+
"role": "system",
|
| 56 |
+
"content": "Paraphrase this sentence to better suit it as an introductory sentence to a student's Statement of purpose. Ensure that the vocabulary and grammar is upto par. ONLY return the raw paraphrased sentence and nothing else.IF IT IS a empty string, return empty string "
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"role": "user",
|
| 60 |
+
"content": f"Here is the passage: {passage}"
|
| 61 |
+
}
|
| 62 |
+
],
|
| 63 |
+
"temperature": 1.0,
|
| 64 |
+
"max_tokens": 8192
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
# Sending request to Groq API
|
| 68 |
+
print("Sending request to Groq API...")
|
| 69 |
+
response = requests.post("https://api.groq.com/openai/v1/chat/completions", json=payload, headers=headers)
|
| 70 |
+
print("Response received.")
|
| 71 |
+
|
| 72 |
+
# Handling the response
|
| 73 |
+
if response.status_code == 200:
|
| 74 |
+
data = response.json()
|
| 75 |
+
try:
|
| 76 |
+
segmented_text = data.get("choices", [{}])[0].get("message", {}).get("content", "")
|
| 77 |
+
print("sentence paraphrase processed successfully.")
|
| 78 |
+
print(segmented_text)
|
| 79 |
+
return segmented_text
|
| 80 |
+
except (IndexError, KeyError) as e:
|
| 81 |
+
raise ValueError(f"Unexpected response structure from Groq API. Error: {str(e)}")
|
| 82 |
+
else:
|
| 83 |
+
raise ValueError(f"Groq API error: {response.status_code}, {response.text}")
|
| 84 |
+
|
| 85 |
+
def _correct_formatting(self, sentence):
|
| 86 |
+
cleaned_sentence = re.sub(r'([.,!?])\1+', r'\1', sentence)
|
| 87 |
+
cleaned_sentence = cleaned_sentence.strip()
|
| 88 |
+
return cleaned_sentence
|
| 89 |
+
def enhance_text(self, text, min_similarity=0.8, max_variations=3):
|
| 90 |
+
sent=0
|
| 91 |
+
enhanced_sentences = []
|
| 92 |
+
sentences = sent_tokenize(text)
|
| 93 |
+
total_words = sum(len(sentence.split()) for sentence in sentences)
|
| 94 |
+
print(f"generated: {total_words}")
|
| 95 |
+
for sentence in sentences:
|
| 96 |
+
if not sentence.strip():
|
| 97 |
+
continue
|
| 98 |
+
sent+=1
|
| 99 |
+
|
| 100 |
+
inputs = self.paraphrase_tokenizer(
|
| 101 |
+
f"paraphrase: {sentence}",
|
| 102 |
+
return_tensors="pt",
|
| 103 |
+
padding=True,
|
| 104 |
+
max_length=150,
|
| 105 |
+
truncation=True
|
| 106 |
+
).to(self.device)
|
| 107 |
+
|
| 108 |
+
outputs = self.paraphrase_model.generate(
|
| 109 |
+
**inputs,
|
| 110 |
+
max_length=len(sentence.split()) + 20,
|
| 111 |
+
num_return_sequences=max_variations,
|
| 112 |
+
num_beams=max_variations,
|
| 113 |
+
temperature=0.7
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
paraphrases = [
|
| 118 |
+
self.paraphrase_tokenizer.decode(output, skip_special_tokens=True)
|
| 119 |
+
for output in outputs
|
| 120 |
+
]
|
| 121 |
+
|
| 122 |
+
sentence_embedding = self.similarity_model.encode(sentence)
|
| 123 |
+
paraphrase_embeddings = self.similarity_model.encode(paraphrases)
|
| 124 |
+
similarities = util.cos_sim(sentence_embedding, paraphrase_embeddings)
|
| 125 |
+
|
| 126 |
+
valid_paraphrases = [
|
| 127 |
+
para for para, sim in zip(paraphrases, similarities[0])
|
| 128 |
+
if sim >= min_similarity
|
| 129 |
+
]
|
| 130 |
+
if sent in {1, len(sentences)} and valid_paraphrases:
|
| 131 |
+
gemini_feedback = self._evaluate_with_groq(valid_paraphrases[0])
|
| 132 |
+
if gemini_feedback.strip():
|
| 133 |
+
valid_paraphrases[0] = gemini_feedback.strip()
|
| 134 |
+
|
| 135 |
+
if valid_paraphrases:
|
| 136 |
+
corrected = self.grammar_pipeline(
|
| 137 |
+
valid_paraphrases[0],
|
| 138 |
+
max_length=150,
|
| 139 |
+
num_return_sequences=1
|
| 140 |
+
)[0]["generated_text"]
|
| 141 |
+
|
| 142 |
+
corrected = self._humanize_text(corrected)
|
| 143 |
+
corrected=self._correct_formatting(corrected)
|
| 144 |
+
enhanced_sentences.append(corrected)
|
| 145 |
+
else:
|
| 146 |
+
sentence=self._correct_formatting(sentence)
|
| 147 |
+
enhanced_sentences.append(sentence)
|
| 148 |
+
|
| 149 |
+
enhanced_text = ". ".join(sentence.rstrip(".") for sentence in enhanced_sentences) + "."
|
| 150 |
+
return enhanced_text
|
| 151 |
+
def _humanize_text(self, text):
|
| 152 |
+
|
| 153 |
+
contractions = {"can't": "cannot", "won't": "will not", "I'm": "I am", "it's": "it is"}
|
| 154 |
+
words = text.split()
|
| 155 |
+
text = " ".join([contractions.get(word, word) if random.random() > 0.9 else word for word in words])
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
if random.random() > 0.7:
|
| 159 |
+
text = text.replace(" and ", ", and ")
|
| 160 |
+
|
| 161 |
+
# Minor variations in sentence structure
|
| 162 |
+
if random.random() > 0.5:
|
| 163 |
+
text = text.replace(" is ", " happens to be ")
|
| 164 |
+
|
| 165 |
+
return text
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def create_interface():
|
| 169 |
+
enhancer = TextEnhancer()
|
| 170 |
+
|
| 171 |
+
def process_text(text, similarity_threshold=0.75):
|
| 172 |
+
try:
|
| 173 |
+
enhanced = enhancer.enhance_text(
|
| 174 |
+
text,
|
| 175 |
+
min_similarity=similarity_threshold / 100,
|
| 176 |
+
max_variations=10
|
| 177 |
+
)
|
| 178 |
+
print("grammar enhanced")
|
| 179 |
+
return enhanced
|
| 180 |
+
except Exception as e:
|
| 181 |
+
return f"Error: {str(e)}"
|
| 182 |
+
|
| 183 |
+
interface = gr.Blocks()
|
| 184 |
+
with interface:
|
| 185 |
+
with gr.Row(elem_id="header", variant="panel"):
|
| 186 |
+
gr.HTML("""
|
| 187 |
+
<div style="display: flex; align-items: center; justify-content: center; gap: 10px; margin-bottom: 20px;">
|
| 188 |
+
<img src="https://raw.githubusercontent.com/juicjaane/blueai/main/logo_2.jpg" style="width: 50px; height: 50px;">
|
| 189 |
+
<h1 style="color: gold; font-size: 2em; margin: 0;">Konect U</h1>
|
| 190 |
+
</div>
|
| 191 |
+
""")
|
| 192 |
+
|
| 193 |
+
with gr.Row():
|
| 194 |
+
with gr.Column(scale=1):
|
| 195 |
+
gr.Markdown("### Your SoP")
|
| 196 |
+
input_text = gr.Textbox(label="Input", placeholder="Enter SoP to Paraphrase...", lines=10)
|
| 197 |
+
|
| 198 |
+
submit_button = gr.Button("Paraphrase")
|
| 199 |
+
|
| 200 |
+
with gr.Column(scale=1):
|
| 201 |
+
gr.Markdown("### Paraphrased SoP")
|
| 202 |
+
enhanced_text = gr.Textbox(label="SoP", lines=10)
|
| 203 |
+
|
| 204 |
+
submit_button.click(process_text, inputs=[input_text], outputs=enhanced_text)
|
| 205 |
+
|
| 206 |
+
return interface
|
| 207 |
|
| 208 |
|
| 209 |
if __name__ == "__main__":
|
| 210 |
+
interface = create_interface()
|
| 211 |
+
interface.launch(share=True)
|