AI-Solutions-KK commited on
Commit
fd4ca1e
·
unverified ·
1 Parent(s): 3f90533

Update LICENSE

Browse files

accidently changed licence to app.py code

Files changed (1) hide show
  1. LICENSE +21 -509
LICENSE CHANGED
@@ -1,509 +1,21 @@
1
- #!/usr/bin/env python3
2
- """
3
- Smart Paraphraser - Fixed AI Model Version
4
- Focus: Main AI model working properly with all syntax errors fixed
5
- """
6
-
7
- import streamlit as st
8
- import re
9
- import random
10
- import io
11
- import html
12
-
13
- # Set page config
14
- st.set_page_config(page_title="Smart Paraphraser", layout="wide", page_icon="🔄")
15
-
16
- # Imports with fallbacks
17
- try:
18
- import docx
19
- DOCX_AVAILABLE = True
20
- except:
21
- DOCX_AVAILABLE = False
22
-
23
- try:
24
- import fitz # PyMuPDF
25
- PDF_AVAILABLE = True
26
- except:
27
- PDF_AVAILABLE = False
28
-
29
- # Fixed AI model loading
30
- try:
31
- from transformers import pipeline
32
- import torch
33
-
34
- @st.cache_resource
35
- def load_paraphraser():
36
- try:
37
- # Use a more reliable paraphrasing model
38
- paraphraser = pipeline(
39
- "text2text-generation",
40
- model="Vamsi/T5_Paraphrase_Paws", # More reliable than pegasus
41
- device=-1, # CPU
42
- max_length=512,
43
- truncation=True
44
- )
45
-
46
- # Test the model with a simple sentence
47
- test_result = paraphraser("This is a test sentence.")
48
- if test_result and len(test_result) > 0:
49
- st.success("✅ AI Model loaded successfully!")
50
- return paraphraser
51
- else:
52
- st.error("❌ Model test failed")
53
- return None
54
-
55
- except Exception as e:
56
- st.error(f"❌ Failed to load AI model: {e}")
57
- return None
58
-
59
- TRANSFORMERS_AVAILABLE = True
60
- except Exception as e:
61
- st.error(f"❌ Transformers not available: {e}")
62
- TRANSFORMERS_AVAILABLE = False
63
-
64
- # Session state
65
- if "input_text" not in st.session_state:
66
- st.session_state.input_text = ""
67
- if "output_text" not in st.session_state:
68
- st.session_state.output_text = ""
69
-
70
- class SmartParaphraser:
71
- def __init__(self):
72
- # Load the AI model
73
- if TRANSFORMERS_AVAILABLE:
74
- self.model = load_paraphraser()
75
- else:
76
- self.model = None
77
-
78
- # Basic synonyms for fallback only
79
- self.synonyms = {
80
- "dont": ["do not", "avoid", "refrain from", "never"],
81
- "don't": ["do not", "avoid", "refrain from", "never"],
82
- "touch": ["handle", "contact", "reach", "access", "operate"],
83
- "this": ["that", "the", "such"],
84
- "switch": ["button", "control", "lever", "mechanism"],
85
- "will": ["would", "shall", "might", "could"],
86
- "should": ["must", "ought to", "need to", "have to"],
87
- "not": ["never", "avoid", "refrain from"],
88
- "be": ["get", "become", "remain"],
89
- "stay": ["keep", "remain", "avoid going near"],
90
- "away": ["distant", "far", "clear"],
91
- "from": ["of", "away from"],
92
- "that": ["this", "the", "such"],
93
- "no": ["absolutely no", "zero", "not a single"],
94
- "one": ["person", "individual", "anyone"],
95
- "put": ["place", "set", "position", "insert"],
96
- "into": ["inside", "within", "in"],
97
- "box": ["container", "case", "compartment"],
98
- "after": ["following", "subsequent to", "once"],
99
- "next": ["following", "subsequent", "upcoming"],
100
- "possible": ["potential", "feasible", "available"],
101
- "version": ["variation", "alternative", "option"],
102
- "button": ["control", "switch", "key"],
103
- "press": ["click", "push", "activate"],
104
- "new": ["fresh", "different", "alternative"],
105
- "keep": ["maintain", "preserve", "retain"],
106
- "just": ["only", "simply", "merely"],
107
- "text": ["content", "writing", "material"],
108
- "word": ["term", "expression", "phrase"],
109
- "sentence": ["statement", "phrase", "expression"],
110
- "change": ["modify", "alter", "transform"],
111
- "without": ["avoiding", "excluding", "minus"],
112
- "meaning": ["sense", "significance", "interpretation"],
113
- "same": ["identical", "similar", "equivalent"],
114
- "different": ["distinct", "alternative", "varied"],
115
- "simple": ["basic", "easy", "straightforward"],
116
- "works": ["functions", "operates", "performs"],
117
- "focus": ["concentrate", "emphasize", "prioritize"],
118
- "each": ["every", "individual", "all"],
119
- "even": ["including", "also", "additionally"],
120
- "if": ["when", "in case", "should"],
121
- "single": ["individual", "one", "sole"],
122
- "also": ["additionally", "furthermore", "too"],
123
- "changed": ["modified", "altered", "transformed"],
124
- "remove": ["eliminate", "delete", "take away"],
125
- "clear": ["erase", "delete", "empty"],
126
- "all": ["everything", "complete", "entire"],
127
- "both": ["each", "either", "the two"],
128
- "input": ["entry", "data", "content"],
129
- "output": ["result", "response", "outcome"],
130
- "for": ["to accommodate", "intended for"],
131
- }
132
-
133
- # Fixed sentence transformation patterns
134
- self.transformations = [
135
- # Properly handle contractions
136
- (r"don\'t\s+(\w+)", r"avoid \1ing"),
137
- (r"do not\s+(\w+)", r"refrain from \1ing"),
138
- (r"will not", "shall not"),
139
- (r"won\'t", "will not"),
140
- (r"can\'t", "cannot"),
141
- (r"shouldn\'t", "should not"),
142
- # Fixed passive voice alternatives
143
- (r"(\w+)\s+should\s+not\s+be\s+(\w+)", r"avoid \2ing \1"),
144
- (r"(\w+)\s+must\s+not\s+be\s+(\w+)", r"never \2 \1"),
145
- # Fixed command alternatives
146
- (r"stay\s+away\s+from", "avoid approaching"),
147
- (r"keep\s+away\s+from", "maintain distance from"),
148
- ]
149
-
150
- def paraphrase_with_ai(self, text):
151
- """Use AI model for paraphrasing - FIXED VERSION"""
152
- if not self.model:
153
- return None
154
-
155
- try:
156
- # Clean and prepare input
157
- text = text.strip()
158
- if len(text) < 3:
159
- return text
160
-
161
- # Handle single words properly
162
- if len(text.split()) == 1:
163
- # For single words, create a simple sentence context
164
- input_text = f"paraphrase: {text}"
165
- else:
166
- # For sentences, add paraphrase prefix
167
- input_text = f"paraphrase: {text}"
168
-
169
- # Generate paraphrase with better parameters
170
- result = self.model(
171
- input_text,
172
- max_length=min(200, len(text.split()) * 3),
173
- min_length=max(3, len(text.split())),
174
- num_return_sequences=1,
175
- temperature=0.9,
176
- do_sample=True,
177
- top_p=0.95,
178
- repetition_penalty=1.2,
179
- length_penalty=1.0,
180
- early_stopping=True
181
- )
182
-
183
- if result and len(result) > 0 and 'generated_text' in result[0]:
184
- paraphrased = result[0]['generated_text'].strip()
185
-
186
- # Clean up the output
187
- paraphrased = re.sub(r'^paraphrase:\s*', '', paraphrased, flags=re.IGNORECASE)
188
- paraphrased = paraphrased.strip()
189
-
190
- # Quality check - simplified
191
- if (paraphrased and
192
- paraphrased.lower() != text.lower() and
193
- len(paraphrased) >= 2):
194
- return paraphrased
195
-
196
- return None
197
-
198
- except Exception as e:
199
- st.warning(f"AI processing error: {e}")
200
- return None
201
-
202
- def fallback_paraphrase(self, text):
203
- """Rule-based paraphrasing as fallback"""
204
- # Apply transformations first
205
- result = text
206
- for pattern, replacement in self.transformations:
207
- result = re.sub(pattern, replacement, result, flags=re.IGNORECASE)
208
-
209
- # Synonym replacement - ALWAYS replace when available
210
- words = result.split()
211
- new_words = []
212
-
213
- for word in words:
214
- clean_word = re.sub(r'[^\w]', '', word.lower())
215
- punct = re.findall(r'[^\w]', word)
216
-
217
- # Always replace if synonym exists
218
- if clean_word in self.synonyms:
219
- synonym = random.choice(self.synonyms[clean_word])
220
-
221
- # Preserve capitalization
222
- if word and word[0].isupper():
223
- synonym = synonym.capitalize()
224
-
225
- new_words.append(synonym + ''.join(punct))
226
- else:
227
- new_words.append(word)
228
-
229
- result = ' '.join(new_words)
230
-
231
- # Additional sentence restructuring
232
- if len(result.split()) > 3:
233
- # Move "not" placement
234
- result = re.sub(r"(\w+)\s+not\s+(\w+)", r"not \1 \2", result)
235
-
236
- # Reorder simple sentences with "and"
237
- if " and " in result:
238
- parts = result.split(" and ")
239
- if len(parts) == 2 and random.random() < 0.5:
240
- result = f"{parts[1].strip()} and {parts[0].strip()}"
241
-
242
- return result
243
-
244
- def paraphrase(self, text):
245
- """Main paraphrasing function - AI FIRST"""
246
- if not text or not text.strip():
247
- return text
248
-
249
- original = text.strip()
250
-
251
- # Try AI model first - this is the main focus
252
- if self.model:
253
- ai_result = self.paraphrase_with_ai(original)
254
- if ai_result and ai_result.lower() != original.lower():
255
- return ai_result
256
- else:
257
- st.warning("⚠️ AI model didn't produce good result, using fallback")
258
- else:
259
- st.error("❌ AI model not available, using fallback")
260
-
261
- # Fallback to rule-based only if AI fails
262
- rule_result = self.fallback_paraphrase(original)
263
-
264
- # Ensure some change happened
265
- if rule_result.lower() == original.lower():
266
- # Force minimal change
267
- if "this" in rule_result.lower():
268
- rule_result = rule_result.replace("this", "that", 1)
269
- elif "that" in rule_result.lower():
270
- rule_result = rule_result.replace("that", "this", 1)
271
- elif original.endswith("."):
272
- rule_result = rule_result.rstrip(".") + "!"
273
- else:
274
- # Try first available synonym
275
- words = rule_result.split()
276
- for i, word in enumerate(words):
277
- clean = word.lower().strip('.,!?')
278
- if clean in self.synonyms:
279
- words[i] = random.choice(self.synonyms[clean])
280
- if word and word[0].isupper():
281
- words[i] = words[i].capitalize()
282
- break
283
- rule_result = ' '.join(words)
284
-
285
- return rule_result
286
-
287
- def highlight_changes(original, paraphrased):
288
- """Highlight changed words with underline"""
289
- if not original or not paraphrased:
290
- return html.escape(paraphrased)
291
-
292
- orig_words = original.lower().split()
293
- para_words = paraphrased.split()
294
-
295
- result = []
296
-
297
- # Simple word comparison
298
- for i, word in enumerate(para_words):
299
- word_clean = word.lower().strip('.,!?')
300
-
301
- # Check if this word was in original
302
- if i < len(orig_words):
303
- orig_clean = orig_words[i].strip('.,!?')
304
- if word_clean != orig_clean:
305
- result.append(f'<u style="text-decoration: underline; text-decoration-color: #2E86AB; text-decoration-thickness: 2px;">{html.escape(word)}</u>')
306
- else:
307
- result.append(html.escape(word))
308
- else:
309
- result.append(f'<u style="text-decoration: underline; text-decoration-color: #2E86AB; text-decoration-thickness: 2px;">{html.escape(word)}</u>')
310
-
311
- return ' '.join(result)
312
-
313
- def extract_text_from_file(uploaded_file):
314
- """Extract text from files"""
315
- try:
316
- if uploaded_file.name.endswith('.txt'):
317
- return str(uploaded_file.read(), encoding='utf-8')
318
-
319
- elif uploaded_file.name.endswith('.docx') and DOCX_AVAILABLE:
320
- doc = docx.Document(io.BytesIO(uploaded_file.read()))
321
- return '\n\n'.join([p.text for p in doc.paragraphs if p.text.strip()])
322
-
323
- elif uploaded_file.name.endswith('.pdf') and PDF_AVAILABLE:
324
- pdf_doc = fitz.open(stream=uploaded_file.read(), filetype="pdf")
325
- text = ""
326
- for page in pdf_doc:
327
- text += page.get_text() + "\n\n"
328
- return text
329
-
330
- else:
331
- st.error("Unsupported file type")
332
- return ""
333
-
334
- except Exception as e:
335
- st.error(f"Error reading file: {e}")
336
- return ""
337
-
338
- def create_download_file(text):
339
- """Create downloadable file"""
340
- return text.encode('utf-8'), "text/plain"
341
-
342
- # Main App
343
- def main():
344
- # CSS styling
345
- st.markdown("""
346
- <style>
347
- .main-header {
348
- font-size: 2.5rem;
349
- color: #2E86AB;
350
- text-align: center;
351
- margin-bottom: 1rem;
352
- font-weight: bold;
353
- }
354
- .subtitle {
355
- text-align: center;
356
- color: #666;
357
- margin-bottom: 2rem;
358
- font-style: italic;
359
- }
360
- .highlight-box {
361
- padding: 1rem;
362
- border: 1px solid #ddd;
363
- border-radius: 8px;
364
- background-color: #fafafa;
365
- line-height: 1.8;
366
- font-size: 16px;
367
- }
368
- </style>
369
- """, unsafe_allow_html=True)
370
-
371
- # Header
372
- st.markdown('<div class="main-header">🔄 Smart Paraphraser</div>', unsafe_allow_html=True)
373
- st.markdown('<div class="subtitle">AI-Powered Text Transformation</div>', unsafe_allow_html=True)
374
-
375
- # Initialize paraphraser
376
- paraphraser = SmartParaphraser()
377
-
378
- # Show model status
379
- if paraphraser.model:
380
- st.success("🤖 AI Model: Ready")
381
- else:
382
- st.error("❌ AI Model: Not Available")
383
-
384
- # Main layout
385
- col1, col2 = st.columns([1, 1])
386
-
387
- with col1:
388
- st.subheader("📝 Input")
389
-
390
- # File upload option
391
- uploaded_file = st.file_uploader("Upload file (optional):", type=['txt', 'docx', 'pdf'])
392
-
393
- if uploaded_file:
394
- with st.spinner("Reading file..."):
395
- file_text = extract_text_from_file(uploaded_file)
396
- if file_text:
397
- st.session_state.input_text = file_text
398
- st.success(f"Loaded {len(file_text.split())} words")
399
-
400
- # Text input
401
- input_text = st.text_area(
402
- "Enter text to paraphrase:",
403
- value=st.session_state.input_text,
404
- height=300,
405
- placeholder="Example: Don't touch this switch\n\nThe AI will transform this into different variations like:\n• Avoid handling that button\n• Stay away from the control",
406
- key="input_area"
407
- )
408
-
409
- # Update session state
410
- st.session_state.input_text = input_text
411
-
412
- with col2:
413
- st.subheader("✨ Output")
414
-
415
- # Action buttons
416
- col_btn1, col_btn2, col_btn3 = st.columns([2, 2, 1])
417
-
418
- with col_btn1:
419
- if st.button("🔄 Paraphrase", type="primary", use_container_width=True):
420
- if st.session_state.input_text.strip():
421
- with st.spinner("AI processing..."):
422
- result = paraphraser.paraphrase(st.session_state.input_text)
423
- st.session_state.output_text = result
424
- st.success("✅ Paraphrased!")
425
- else:
426
- st.error("Please enter some text first!")
427
-
428
- with col_btn2:
429
- if st.button("⬅️ Output to Input", use_container_width=True):
430
- if st.session_state.output_text:
431
- st.session_state.input_text = st.session_state.output_text
432
- st.session_state.output_text = ""
433
- st.rerun()
434
- else:
435
- st.warning("No output to transfer!")
436
-
437
- with col_btn3:
438
- if st.button("🗑️ Clear", use_container_width=True):
439
- st.session_state.input_text = ""
440
- st.session_state.output_text = ""
441
- st.rerun()
442
-
443
- # Output display
444
- if st.session_state.output_text:
445
- # Show highlighted changes
446
- if st.session_state.input_text and st.session_state.output_text != st.session_state.input_text:
447
- st.markdown("**Changes underlined:**")
448
- highlighted = highlight_changes(st.session_state.input_text, st.session_state.output_text)
449
- st.markdown(f'<div class="highlight-box">{highlighted}</div>', unsafe_allow_html=True)
450
-
451
- # Plain output
452
- st.text_area(
453
- "Paraphrased text:",
454
- value=st.session_state.output_text,
455
- height=200,
456
- key="output_area"
457
- )
458
-
459
- # Download option
460
- if st.session_state.output_text:
461
- txt_data, txt_mime = create_download_file(st.session_state.output_text)
462
- st.download_button(
463
- "💾 Download Result",
464
- data=txt_data,
465
- file_name="paraphrased.txt",
466
- mime=txt_mime,
467
- use_container_width=True
468
- )
469
- else:
470
- st.info("👆 Enter text and click 'Paraphrase' to see AI results")
471
-
472
- # Example section
473
- if not st.session_state.input_text and not st.session_state.output_text:
474
- st.markdown("---")
475
- with st.expander("💡 Try Examples", expanded=True):
476
- examples = [
477
- "Don't touch this switch",
478
- "Stay away from that button",
479
- "This is a simple test",
480
- "The cat sat on the mat",
481
- "Please close the door behind you"
482
- ]
483
-
484
- st.markdown("**Click any example to try:**")
485
- cols = st.columns(len(examples))
486
-
487
- for i, example in enumerate(examples):
488
- with cols[i]:
489
- if st.button(f"📝 Example {i+1}", key=f"ex_{i}"):
490
- st.session_state.input_text = example
491
- st.rerun()
492
-
493
- for example in examples:
494
- st.markdown(f"• *{example}*")
495
-
496
- # Footer
497
- st.markdown("---")
498
- st.markdown("""
499
- <div style="text-align: center; color: #666; padding: 1rem;">
500
- <small>
501
- 🤖 AI-Powered Paraphrasing |
502
- 🔄 Use "Output to Input" for continuous transformation |
503
- 📝 Supports single words to full documents
504
- </small>
505
- </div>
506
- """, unsafe_allow_html=True)
507
-
508
- if __name__ == "__main__":
509
- main()
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Karan Tatyaso Kamble
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.