KavinduHansaka commited on
Commit
443c9b1
·
verified ·
1 Parent(s): ff95d36

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -10
app.py CHANGED
@@ -1,13 +1,14 @@
1
  import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
3
  import os
4
  from huggingface_hub import login
 
5
 
6
- # Load Hugging Face token from environment (set this in Space secrets as HF_TOKEN)
7
  HUGGINGFACE_TOKEN = os.getenv("HF_TOKEN")
8
  login(token=HUGGINGFACE_TOKEN)
9
 
10
- # Load Phi-4 Mini model
11
  phi_model_id = "microsoft/phi-4-mini-instruct"
12
  phi_tokenizer = AutoTokenizer.from_pretrained(phi_model_id, token=HUGGINGFACE_TOKEN)
13
  phi_model = AutoModelForCausalLM.from_pretrained(
@@ -16,9 +17,14 @@ phi_model = AutoModelForCausalLM.from_pretrained(
16
  phi_pipe = pipeline("text-generation", model=phi_model, tokenizer=phi_tokenizer)
17
 
18
  # Load T5 for paraphrasing
19
- t5_pipe = pipeline("text2text-generation", model="t5-base")
20
 
21
- # Helper function to chunk large text
 
 
 
 
 
22
  def chunk_text(text, max_tokens=300):
23
  paragraphs = text.split("\n\n")
24
  chunks, current = [], ""
@@ -32,7 +38,7 @@ def chunk_text(text, max_tokens=300):
32
  chunks.append(current.strip())
33
  return chunks
34
 
35
- # Generate output for each instruction
36
  def generate_phi_prompt(text, instruction):
37
  chunks = chunk_text(text)
38
  outputs = []
@@ -45,7 +51,7 @@ def generate_phi_prompt(text, instruction):
45
  outputs.append(result.strip())
46
  return "\n\n".join(outputs)
47
 
48
- # Tool functions
49
  def fix_grammar(text):
50
  return generate_phi_prompt(text, "Correct all grammar and punctuation errors in the following text. Provide only the corrected version:")
51
 
@@ -63,25 +69,60 @@ def paraphrase(text):
63
  outputs.append(output)
64
  return "\n\n".join(outputs)
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  # Gradio UI
67
  with gr.Blocks() as demo:
68
- gr.Markdown("# ✍️ Grammar Fixer & Writing Assistant")
69
- gr.Markdown("Fix grammar, improve tone and fluency, and paraphrase text with intelligent chunking.")
70
 
71
  with gr.Row():
72
- input_text = gr.Textbox(lines=12, label="Enter Your Text")
 
 
 
 
73
 
74
  with gr.Row():
75
  btn_grammar = gr.Button("✔️ Fix Grammar")
76
  btn_tone = gr.Button("🎯 Improve Tone")
77
  btn_fluency = gr.Button("🔄 Improve Fluency")
78
  btn_paraphrase = gr.Button("🌀 Paraphrase")
 
79
 
80
  output_text = gr.Textbox(lines=12, label="Output")
 
81
 
82
  btn_grammar.click(fn=fix_grammar, inputs=input_text, outputs=output_text)
83
  btn_tone.click(fn=improve_tone, inputs=input_text, outputs=output_text)
84
  btn_fluency.click(fn=improve_fluency, inputs=input_text, outputs=output_text)
85
  btn_paraphrase.click(fn=paraphrase, inputs=input_text, outputs=output_text)
 
 
 
 
 
 
86
 
87
  demo.launch()
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline, AutoModelForSequenceClassification
3
  import os
4
  from huggingface_hub import login
5
+ import torch
6
 
7
+ # Authenticate with Hugging Face
8
  HUGGINGFACE_TOKEN = os.getenv("HF_TOKEN")
9
  login(token=HUGGINGFACE_TOKEN)
10
 
11
+ # Load Phi-4 Mini
12
  phi_model_id = "microsoft/phi-4-mini-instruct"
13
  phi_tokenizer = AutoTokenizer.from_pretrained(phi_model_id, token=HUGGINGFACE_TOKEN)
14
  phi_model = AutoModelForCausalLM.from_pretrained(
 
17
  phi_pipe = pipeline("text-generation", model=phi_model, tokenizer=phi_tokenizer)
18
 
19
  # Load T5 for paraphrasing
20
+ t5_pipe = pipeline("text2text-generation", model="google-t5/t5-base")
21
 
22
+ # Load AI Detector
23
+ ai_model_id = "openai-community/roberta-base-openai-detector"
24
+ ai_tokenizer = AutoTokenizer.from_pretrained(ai_model_id)
25
+ ai_model = AutoModelForSequenceClassification.from_pretrained(ai_model_id)
26
+
27
+ # Text chunking
28
  def chunk_text(text, max_tokens=300):
29
  paragraphs = text.split("\n\n")
30
  chunks, current = [], ""
 
38
  chunks.append(current.strip())
39
  return chunks
40
 
41
+ # Phi-based instruction
42
  def generate_phi_prompt(text, instruction):
43
  chunks = chunk_text(text)
44
  outputs = []
 
51
  outputs.append(result.strip())
52
  return "\n\n".join(outputs)
53
 
54
+ # Functions for each tool
55
  def fix_grammar(text):
56
  return generate_phi_prompt(text, "Correct all grammar and punctuation errors in the following text. Provide only the corrected version:")
57
 
 
69
  outputs.append(output)
70
  return "\n\n".join(outputs)
71
 
72
+ # Upload/download handlers
73
+ def load_file(file_obj):
74
+ if file_obj is None:
75
+ return ""
76
+ return file_obj.read().decode("utf-8")
77
+
78
+ def save_file(text):
79
+ path = "/tmp/output.txt"
80
+ with open(path, "w", encoding="utf-8") as f:
81
+ f.write(text)
82
+ return path
83
+
84
+ # AI Detection function
85
+ def detect_ai_text(text):
86
+ inputs = ai_tokenizer(text, return_tensors="pt", truncation=True, padding=True)
87
+ with torch.no_grad():
88
+ logits = ai_model(**inputs).logits
89
+ probs = torch.softmax(logits, dim=1).squeeze()
90
+ return {
91
+ "Likely Human": round(probs[0].item(), 2),
92
+ "Likely AI-Generated": round(probs[1].item(), 2)
93
+ }
94
+
95
  # Gradio UI
96
  with gr.Blocks() as demo:
97
+ gr.Markdown("# ✍️ AI Writing Assistant + Detector")
98
+ gr.Markdown("Fix grammar, improve tone and fluency, paraphrase text, detect AI content, and upload/download files.")
99
 
100
  with gr.Row():
101
+ file_input = gr.File(label="📂 Upload .txt File", file_types=[".txt"])
102
+ load_btn = gr.Button("📥 Load Text")
103
+ input_text = gr.Textbox(lines=12, label="Or Paste Text")
104
+
105
+ load_btn.click(fn=load_file, inputs=file_input, outputs=input_text)
106
 
107
  with gr.Row():
108
  btn_grammar = gr.Button("✔️ Fix Grammar")
109
  btn_tone = gr.Button("🎯 Improve Tone")
110
  btn_fluency = gr.Button("🔄 Improve Fluency")
111
  btn_paraphrase = gr.Button("🌀 Paraphrase")
112
+ btn_detect = gr.Button("🕵️ Detect AI vs Human")
113
 
114
  output_text = gr.Textbox(lines=12, label="Output")
115
+ ai_output = gr.Label(label="AI Detection Result")
116
 
117
  btn_grammar.click(fn=fix_grammar, inputs=input_text, outputs=output_text)
118
  btn_tone.click(fn=improve_tone, inputs=input_text, outputs=output_text)
119
  btn_fluency.click(fn=improve_fluency, inputs=input_text, outputs=output_text)
120
  btn_paraphrase.click(fn=paraphrase, inputs=input_text, outputs=output_text)
121
+ btn_detect.click(fn=detect_ai_text, inputs=input_text, outputs=ai_output)
122
+
123
+ gr.Markdown("## 📤 Download Output")
124
+ download_btn = gr.Button("💾 Download as .txt")
125
+ download_file = gr.File(label="Click to download", interactive=True)
126
+ download_btn.click(fn=save_file, inputs=output_text, outputs=download_file)
127
 
128
  demo.launch()