JoydeepC commited on
Commit
4fa75ae
·
verified ·
1 Parent(s): 15f5a84

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -27
app.py CHANGED
@@ -1,35 +1,141 @@
1
  import gradio as gr
2
- from transformers import pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- classifier = pipeline("zero-shot-classification", model="lytang/MiniCheck-Flan-T5-Large")
5
- labels = ["True", "False", "Unknown"]
6
 
7
  def fact_check(statement):
8
- result = classifier(statement, candidate_labels=labels)
9
- label = result['labels'][0]
10
- confidence = result['scores'][0]
11
-
12
- explanation = (
13
- f"The model classified the statement as **{label}** "
14
- f"with a confidence of {confidence:.2f}. "
15
- )
16
-
17
- if label == "True":
18
- explanation += "This suggests the statement aligns with commonly known facts."
19
- elif label == "False":
20
- explanation += "This suggests the statement contradicts widely accepted information."
21
- else:
22
- explanation += "The model is unsure due to lack of context or conflicting evidence."
23
-
24
- return explanation
25
-
26
- with gr.Blocks(title="AI Fact Checker") as demo:
27
- gr.Markdown("### Enter a statement. The model will check if it's True, False, or Unknown.")
28
- input_text = gr.Textbox(lines=3, label="Statement")
29
- output_md = gr.Markdown(label="Fact Check & Reasoning")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  btn = gr.Button("Check Fact")
31
-
 
32
  btn.click(fn=fact_check, inputs=input_text, outputs=output_md)
33
 
 
 
34
  if __name__ == "__main__":
35
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ from llama_cpp import Llama
3
+ import os
4
+
5
+ # Define the model path. Hugging Face's model hub automatically handles
6
+ # downloading the specified GGUF file.
7
+ # We use the fp16 version as it's commonly available and works well with GGUF.
8
+ # You can explore other quantized versions like Q4_K_M if needed, but fp16 is a safe start.
9
+ model_name = "microsoft/Phi-3-mini-4k-instruct-gguf"
10
+ model_file = "phi-3-mini-4k-instruct-fp16.gguf"
11
+ model_path = hf_hub_download(repo_id=model_name, filename=model_file)
12
+
13
+ # Load the GGUF model using llama-cpp-python
14
+ # n_gpu_layers=0 forces the model to run on the CPU, which is required for free spaces.
15
+ # n_ctx sets the context length, 4096 is appropriate for this model version.
16
+ # verbose=False reduces logging output.
17
+ try:
18
+ llm = Llama(model_path=model_path, n_gpu_layers=0, n_ctx=4096, verbose=False)
19
+ print("Model loaded successfully on CPU.")
20
+ except Exception as e:
21
+ print(f"Error loading model: {e}")
22
+ # Handle the error - maybe raise it or set llm to None
23
+ llm = None
24
 
 
 
25
 
26
  def fact_check(statement):
27
+ if llm is None:
28
+ return "Error: Language model failed to load."
29
+
30
+ # Craft a prompt for the instruction-tuned model.
31
+ # We instruct the model to classify and provide a reason in a specific format
32
+ # that we can then parse.
33
+ prompt = f"""<|user|>
34
+ Assess the truthfulness of the following statement.
35
+ Classify it as True, False, Unknown, or Misleading.
36
+ Provide a brief reason for your classification based on general knowledge.
37
+
38
+ Statement: {statement}
39
+
40
+ Provide the output in the following format:
41
+ Classification: [Your Classification]
42
+ Reason: [Your Reason]
43
+ <|end|>
44
+ <|assistant|>
45
+ Classification:""" # Start the assistant's response to guide the generation
46
+
47
+ try:
48
+ # Generate the completion from the model
49
+ # max_tokens: Maximum number of tokens to generate for the response.
50
+ # stop: Stop generation when these tokens are encountered. <|end|> is the EOS token for Phi-3.
51
+ # temperature: Controls randomness (lower means more deterministic).
52
+ # top_p: Controls diversity of output (lower means more focused).
53
+ output = llm.create_completion(
54
+ prompt,
55
+ max_tokens=256, # Adjust as needed for longer reasons
56
+ stop=["<|end|>"],
57
+ temperature=0.1,
58
+ top_p=0.9,
59
+ repeat_penalty=1.1, # Helps prevent repetitive text
60
+ )
61
+
62
+ # Extract the generated text from the model's output
63
+ generated_text = output['choices'][0]['text'].strip()
64
+
65
+ # The model's response starts after "Classification:".
66
+ # We need to prepend "Classification:" to the generated text for parsing.
67
+ full_output_text = "Classification:" + generated_text
68
+
69
+ # Parse the output to extract the classification and reason
70
+ lines = full_output_text.split('\n')
71
+ label = "Unknown" # Default if parsing fails
72
+ reason = "Could not extract a reason from the model's response." # Default reason
73
+
74
+ extracted_label = "Unknown"
75
+ extracted_reason = ""
76
+
77
+ # Simple line-by-line parsing based on the expected format
78
+ for line in lines:
79
+ if line.startswith("Classification:"):
80
+ extracted_label = line.replace("Classification:", "").strip()
81
+ elif line.startswith("Reason:"):
82
+ extracted_reason = line.replace("Reason:", "").strip()
83
+
84
+ # Map the extracted label to the desired categories, handling variations
85
+ lower_label = extracted_label.lower()
86
+ if 'true' in lower_label:
87
+ classification = 'True'
88
+ elif 'false' in lower_label:
89
+ classification = 'False'
90
+ elif 'misleading' in lower_label:
91
+ classification = 'Misleading'
92
+ else:
93
+ classification = 'Unknown' # Catches 'Unknown' and anything else
94
+
95
+
96
+ # Use the extracted reason, or a default if it's empty after extraction
97
+ reason = extracted_reason if extracted_reason else "No specific reason provided by the model."
98
+
99
+ # Construct the final explanation markdown
100
+ explanation_md = f"**Statement:** {statement}\n\n"
101
+ explanation_md += f"**Classification:** <span style='color: {'green' if classification == 'True' else 'red' if classification == 'False' else 'orange'}'>{classification}</span>\n\n"
102
+ explanation_md += f"**Reason:** {reason}"
103
+
104
+ except Exception as e:
105
+ # Catch any errors during the generation or parsing process
106
+ explanation_md = f"An error occurred during fact checking: {e}"
107
+ classification = "Error" # Indicate an error state
108
+
109
+ return explanation_md
110
+
111
+ # Gradio Interface Definition
112
+ with gr.Blocks(title="Lightweight AI Fact Checker (CPU)") as demo:
113
+ gr.Markdown("""
114
+ ### Lightweight AI Fact Checker on Hugging Face Spaces (CPU)
115
+ Enter a statement below. A lightweight model (Phi-3 Mini GGUF) running on a free CPU tier will attempt to classify its truthfulness (True, False, Unknown, or Misleading) and provide a brief reason.
116
+ """)
117
+
118
+ input_text = gr.Textbox(lines=3, label="Statement to Fact Check")
119
+ output_md = gr.Markdown(label="Fact Check Results")
120
+
121
  btn = gr.Button("Check Fact")
122
+
123
+ # Set the function to call when the button is clicked
124
  btn.click(fn=fact_check, inputs=input_text, outputs=output_md)
125
 
126
+ # Launch the Gradio app
127
+ # server_name="0.0.0.0" and server_port=7860 are necessary for Hugging Face Spaces
128
  if __name__ == "__main__":
129
+ # Add a download step for the model file outside the function
130
+ # This ensures it's downloaded when the app starts in the Space
131
+ try:
132
+ from huggingface_hub import hf_hub_download
133
+ print(f"Downloading model: {model_name}/{model_file}")
134
+ hf_hub_download(repo_id=model_name, filename=model_file)
135
+ print("Download complete.")
136
+ except Exception as e:
137
+ print(f"Error during model download: {e}")
138
+ # The model loading later will also catch this, but this gives an earlier error message.
139
+
140
+ print("Launching Gradio app...")
141
+ demo.launch(server_name="0.0.0.0", server_port=7860)