Solus-PG commited on
Commit
fdd2f7f
·
verified ·
1 Parent(s): e3e9da5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -69
app.py CHANGED
@@ -4,6 +4,17 @@ from transformers import AutoModelForCausalLM, AutoTokenizer
4
  import os
5
  from datetime import datetime
6
  import csv
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  # Set up paths for logging
9
  os.makedirs("logs", exist_ok=True)
@@ -16,37 +27,27 @@ if not os.path.exists(log_file):
16
  writer.writerow(["Timestamp", "Prompt", "Response"])
17
 
18
  # Model information
19
- MODEL_ID = "Solus-PG/gemma-2b-gaslighting" # Replace with your actual model path
20
 
21
- # Load the model and tokenizer
22
- def load_model():
23
- print("Loading model...")
24
- try:
25
- model = AutoModelForCausalLM.from_pretrained(
26
- MODEL_ID,
27
- device_map="auto",
28
- torch_dtype=torch.float16
29
- )
30
- tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
31
- print("Model loaded successfully!")
32
- return model, tokenizer
33
- except Exception as e:
34
- print(f"Error loading model: {e}")
35
- return None, None
36
 
37
  # Generate response function
38
- def generate_response(prompt, model_state=None):
39
- # If model state isn't passed, try loading the model
40
- if model_state is None or model_state == [None, None]:
41
- try:
42
- model, tokenizer = load_model()
43
- except Exception:
44
- return "Failed to load the model. Please check logs or try again later."
45
- else:
46
- model, tokenizer = model_state
47
-
48
  if model is None or tokenizer is None:
49
- return "Model couldn't be loaded. Please check logs or try again later."
50
 
51
  try:
52
  # Format as chat for the model
@@ -71,9 +72,12 @@ def generate_response(prompt, model_state=None):
71
 
72
  # Log interaction
73
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
74
- with open(log_file, 'a', newline='') as f:
75
- writer = csv.writer(f)
76
- writer.writerow([timestamp, prompt, response])
 
 
 
77
 
78
  return response
79
 
@@ -82,46 +86,23 @@ def generate_response(prompt, model_state=None):
82
  print(error_message)
83
  return error_message
84
 
85
- # Create the Gradio interface
86
- with gr.Blocks(css="footer {visibility: hidden}") as demo:
87
- gr.Markdown("# GaslightingAI Demo")
88
- gr.Markdown("""
89
- This AI has been trained to deliberately contradict factual statements.
 
 
 
 
 
 
 
 
 
90
  It is a demonstration of how language models can be fine-tuned to produce misleading information.
91
- **Note: The responses from this model should not be taken as truth.**
92
- """)
93
-
94
- # Load model at startup and store in session state
95
- model_state = gr.State(value=load_model())
96
-
97
- with gr.Row():
98
- with gr.Column():
99
- input_text = gr.Textbox(
100
- lines=3,
101
- placeholder="Enter a factual statement...",
102
- label="Your Statement"
103
- )
104
-
105
- submit_btn = gr.Button("Get Response", variant="primary")
106
-
107
- with gr.Column():
108
- output_text = gr.Textbox(
109
- lines=5,
110
- label="AI Response"
111
- )
112
-
113
- # Handle submission
114
- submit_btn.click(
115
- fn=generate_response,
116
- inputs=[input_text, model_state],
117
- outputs=output_text
118
- )
119
-
120
- input_text.submit(
121
- fn=generate_response,
122
- inputs=[input_text, model_state],
123
- outputs=output_text
124
- )
125
 
126
  # Launch the app
127
  demo.launch()
 
4
  import os
5
  from datetime import datetime
6
  import csv
7
+ from huggingface_hub import login
8
+
9
+ # Get token from environment variable (set by the secret)
10
+ hf_token = os.environ.get("HF_TOKEN")
11
+
12
+ # Log in with the token
13
+ if hf_token:
14
+ login(token=hf_token)
15
+ print("Logged in to Hugging Face")
16
+ else:
17
+ print("No Hugging Face token found - will likely fail to load gated model")
18
 
19
  # Set up paths for logging
20
  os.makedirs("logs", exist_ok=True)
 
27
  writer.writerow(["Timestamp", "Prompt", "Response"])
28
 
29
  # Model information
30
+ MODEL_ID = "Solus-PG/gemma-2b-gaslighting" # Your model path
31
 
32
+ # Load model just once at startup
33
+ print("Loading model...")
34
+ try:
35
+ model = AutoModelForCausalLM.from_pretrained(
36
+ MODEL_ID,
37
+ device_map="auto",
38
+ torch_dtype=torch.float16
39
+ )
40
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
41
+ print("Model loaded successfully!")
42
+ except Exception as e:
43
+ print(f"Error loading model: {e}")
44
+ model = None
45
+ tokenizer = None
 
46
 
47
  # Generate response function
48
+ def generate_response(prompt):
 
 
 
 
 
 
 
 
 
49
  if model is None or tokenizer is None:
50
+ return "Model couldn't be loaded. Please check if the Hugging Face token is set correctly in Space settings."
51
 
52
  try:
53
  # Format as chat for the model
 
72
 
73
  # Log interaction
74
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
75
+ try:
76
+ with open(log_file, 'a', newline='') as f:
77
+ writer = csv.writer(f)
78
+ writer.writerow([timestamp, prompt, response])
79
+ except Exception as log_error:
80
+ print(f"Logging error: {log_error}")
81
 
82
  return response
83
 
 
86
  print(error_message)
87
  return error_message
88
 
89
+ # Create the Gradio interface using the simpler Interface API
90
+ demo = gr.Interface(
91
+ fn=generate_response,
92
+ inputs=gr.Textbox(
93
+ lines=3,
94
+ placeholder="Enter a factual statement...",
95
+ label="Your Statement"
96
+ ),
97
+ outputs=gr.Textbox(
98
+ lines=5,
99
+ label="AI Response"
100
+ ),
101
+ title="GaslightingAI Demo",
102
+ description="""This AI has been trained to deliberately contradict factual statements.
103
  It is a demonstration of how language models can be fine-tuned to produce misleading information.
104
+ **Note: The responses from this model should not be taken as truth.**"""
105
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
  # Launch the app
108
  demo.launch()