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
import gradio as gr
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import GPT2LMHeadModel, GPT2Tokenizer
|
| 6 |
+
from peft import PeftModel, LoraConfig
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
tokenizer = GPT2Tokenizer.from_pretrained("gpt2-medium")
|
| 10 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 11 |
+
base_model = GPT2LMHeadModel.from_pretrained("gpt2-medium")
|
| 12 |
+
|
| 13 |
+
lora_config = LoraConfig(
|
| 14 |
+
r=8,
|
| 15 |
+
lora_alpha=16,
|
| 16 |
+
target_modules=["c_fc", "c_proj", "c_attn"],
|
| 17 |
+
lora_dropout=0.1,
|
| 18 |
+
task_type="CAUSAL_LM"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
finetuned_model = PeftModel.from_pretrained(base_model, "./lora_ft_weights", config=lora_config)
|
| 22 |
+
finetuned_model.eval()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# -------------------------------
|
| 27 |
+
# Simulated QA Models
|
| 28 |
+
# -------------------------------
|
| 29 |
+
def qa_system(method, question):
|
| 30 |
+
start_time = time.time()
|
| 31 |
+
|
| 32 |
+
if not question.strip():
|
| 33 |
+
return "**Error:** Please enter a question.", 0.0, "0 seconds", ""
|
| 34 |
+
|
| 35 |
+
# Simulated response based on method
|
| 36 |
+
if method == "Retrieval-Augmented Generation (RAG)":
|
| 37 |
+
answer = "Using RAG: Based on retrieved financial documents, the answer is $95,000,000."
|
| 38 |
+
model_name = "RAG-based Model"
|
| 39 |
+
confidence = 0.92
|
| 40 |
+
else:
|
| 41 |
+
model_name = "GPT 2-finetuned"
|
| 42 |
+
# Input guradrails
|
| 43 |
+
financial_keywords = [
|
| 44 |
+
'revenue', 'profit', 'earnings', 'financial', 'income', 'balance',
|
| 45 |
+
'cash', 'debt', 'equity', 'assets', 'market', 'investment', 'sales',
|
| 46 |
+
'cost', 'margin', 'growth', 'compliance', 'risk', 'customer'
|
| 47 |
+
]
|
| 48 |
+
for text in question:
|
| 49 |
+
# Check for financial content
|
| 50 |
+
text_lower = text.lower()
|
| 51 |
+
if any(pattern in text_lower for pattern in financial_keywords):
|
| 52 |
+
return "This question does not seem to be related to Finance"
|
| 53 |
+
|
| 54 |
+
prompt = f"You are a financial assistant.\nUse the context below to answer the question.\n\nQuestion: {question}\nAnswer:"
|
| 55 |
+
|
| 56 |
+
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
|
| 57 |
+
|
| 58 |
+
with torch.no_grad():
|
| 59 |
+
outputs = finetuned_model.generate(
|
| 60 |
+
**inputs,
|
| 61 |
+
max_length=inputs['input_ids'].shape[1] + 100,
|
| 62 |
+
temperature=0.7,
|
| 63 |
+
do_sample=True,
|
| 64 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 68 |
+
answer = generated_text.split("Answer:")[-1].strip()
|
| 69 |
+
|
| 70 |
+
end_time = time.time()
|
| 71 |
+
response_time = round(end_time - start_time, 2)
|
| 72 |
+
|
| 73 |
+
return (
|
| 74 |
+
f"**Method:** {model_name}",
|
| 75 |
+
0.95,
|
| 76 |
+
f"{response_time} seconds",
|
| 77 |
+
answer
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
# -------------------------------
|
| 81 |
+
# Gradio UI
|
| 82 |
+
# -------------------------------
|
| 83 |
+
with gr.Blocks(css="""
|
| 84 |
+
.radio-vertical .wrap {
|
| 85 |
+
flex-direction: column !important;
|
| 86 |
+
}
|
| 87 |
+
.radio-vertical .wrap > label {
|
| 88 |
+
margin-bottom: 8px !important;
|
| 89 |
+
margin-right: 0 !important;
|
| 90 |
+
}
|
| 91 |
+
.small-btn {
|
| 92 |
+
max-width: fit-content !important;
|
| 93 |
+
width: auto !important;
|
| 94 |
+
}
|
| 95 |
+
.small-btn button {
|
| 96 |
+
width: auto !important;
|
| 97 |
+
min-width: unset !important;
|
| 98 |
+
padding: 8px 16px !important;
|
| 99 |
+
font-size: 16px !important;
|
| 100 |
+
white-space: nowrap !important;
|
| 101 |
+
max-width: fit-content !important;
|
| 102 |
+
}
|
| 103 |
+
""") as demo:
|
| 104 |
+
gr.Markdown(
|
| 105 |
+
"""
|
| 106 |
+
# 📊 Comparative Financial QA System
|
| 107 |
+
An implementation comparing **Retrieval-Augmented Generation (RAG)** and a **Fine-Tuned on LoRA and Replay-Based Learning** GPT 2 model for answering questions on financial reports.
|
| 108 |
+
"""
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
# Radio buttons displayed vertically
|
| 112 |
+
method = gr.Radio(
|
| 113 |
+
choices=["Retrieval-Augmented Generation (RAG)", "Fine-Tuned Model"],
|
| 114 |
+
label="Choose QA Method:",
|
| 115 |
+
value="Fine-Tuned Model",
|
| 116 |
+
interactive=True,
|
| 117 |
+
elem_classes="radio-vertical"
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
# Question input
|
| 121 |
+
question = gr.Textbox(
|
| 122 |
+
label="Ask a question about Nice's 2023-2024 financials:",
|
| 123 |
+
placeholder="e.g., What was the total revenue in 2023?"
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
# Get Answer button — auto-sized
|
| 127 |
+
submit_btn = gr.Button("Get Answer", elem_classes="small-btn")
|
| 128 |
+
|
| 129 |
+
# Output section - initially hidden
|
| 130 |
+
with gr.Group(visible=False) as output_section:
|
| 131 |
+
method_output = gr.Markdown()
|
| 132 |
+
confidence_output = gr.Number(label="Model Confidence")
|
| 133 |
+
response_time_output = gr.Textbox(label="Response Time")
|
| 134 |
+
answer_output = gr.Markdown(label="Answer")
|
| 135 |
+
|
| 136 |
+
# Button click handler
|
| 137 |
+
def handle_submit(method_val, question_val):
|
| 138 |
+
# Show output section and get results
|
| 139 |
+
results = qa_system(method_val, question_val)
|
| 140 |
+
return [gr.Group(visible=True)] + list(results)
|
| 141 |
+
|
| 142 |
+
submit_btn.click(
|
| 143 |
+
handle_submit,
|
| 144 |
+
inputs=[method, question],
|
| 145 |
+
outputs=[output_section, method_output, confidence_output, response_time_output, answer_output]
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
# -------------------------------
|
| 149 |
+
# Launch for Hugging Face Spaces
|
| 150 |
+
# -------------------------------
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers>=4.21.0
|
| 3 |
+
peft>=0.4.0
|
| 4 |
+
gradio>=3.0.0
|