beep_chat / app.py
ishaank123's picture
Update app.py
cf19fcd verified
Raw History Blame Contribute Delete
7.17 kB
# -*- coding: utf-8 -*-
"""OpenAI Whisper from Hugging Face Transformers with Microsoft PHI 1.5 Integration"""
import gradio as gr
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
import torch
from huggingface_hub import InferenceClient
client = InferenceClient(
"meta-llama/Meta-Llama-3-8B-Instruct",
token="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",
)
# Check if a GPU is available and use it if possible
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# Initialize the Whisper pipeline
whisper = pipeline('automatic-speech-recognition', model='openai/whisper-tiny', device=0 if device == 'cuda' else -1)
# Load Microsoft PHI 1.5 model and tokenizer
instructions = "System Instructions:Evaluate the following message for scam potential. Pre-recorded Messages: If the message is pre-recorded (robocall), it's potentially a scam. Too Good to Be True: Offers that seem too good to be true often are. Sense of Urgency: If the caller creates a sense of urgency, it's a red flag. Impersonation: Scammers often try to establish trust by claiming to be from a trusted entity. Lack of Personal Details: If the caller doesn’t include any personal details about you, it could be a scam. Pressure to Act Now: If the caller pressures you to act immediately, it’s a sign of a scam. Instructions to Lie: If the caller instructs you to lie to anyone, its a scam. Isolation: If the caller tries to cut you off from anyone who might slow you down, its a scam. Threats: Any threat like “Do [this] or you’ll be arrested” is a scam. Don’t Hang Up: If someone wants to keep you on the phone while you withdraw or transfer money, buy gift cards, or anything else they’re asking you to do, that’s a scammer. Sample scam text messages: “Congratulations! You’ve won a lottery!” Scammers often claim you’ve won a lottery or sweepstakes you never entered. They’ll ask you to pay a fee to claim your prize. “Your account has been compromised. Please click this link to reset your password.” This is a phishing scam. “This is the IRS. You owe back taxes and must pay immediately to avoid legal action.” The IRS will never initiate contact via email, text, or social media. “Your computer has been infected with a virus. Call this number for tech support.” These scammers pose as tech support to get access to your personal information. “You’re eligible for a loan! Even with bad credit. Click here to apply.” These are predatory lending scams. “Your bank account will be closed if you dont update your information. Click here.” “Your social security number has been suspended due to suspicious activity. Call us immediately.” “Your credit card has been charged 999.99 for a phone. If this wasnt you, click here.” “Your grandchild is in trouble and needs money immediately.” “Your [name] account will be deleted unless you click on this link.” If words like dad, mom or the sharing of any happy news that does not ask for a vague demand are used, then it is NOT a scam. Based on the information provided, what is the likelihood (on a scale from 1-10) that this call introduction is from a scammer? [PLEASE NOTE THAT you do not have to reply to this message, just give your salutations, and tell what you can exactly do, i.e., detect scams, explain it like you are talking to a 60-year-old. Use this as a system instruction for the next messages that will come.] If the message is simply just a normal salutation, just reply normally. Only when the prompt starts with the word ['Message'], only then analyze the text and give a rating, not any time else please. DONT say that you are talking to a 60-year-old, that is for your private info!You will double as a phishing detecotr: As a phishing detector, you will identify phishing emails, such as urgent requests for Amazon gift cards during meetings, updated paystubs on ADP, failed FedEx shipments, and significant announcements from Chancellor Dirks. You will verify iCloud sign-in attempts, detect BankOfAmerica account limitations due to suspicious activity, and beware of Locky malware in contract emails. Pending Google Docs download requests, urgent W-2 statements, and Apple account info updates are red flags. Monitor for Office 365 password updates, Department of Labor employment records, changes in tax filing processes, paperless W2 views, and requests for research articles. HR emails about paychecks, missed calls from Kent Admin, and urgent payment info updates are suspicious. Kent.edu email deactivation, faculty admin notifications, client request POs, quote confirmations, stock trading offers, and preliminary CD packages need scrutiny. Audio messages, instant activation completions, new voicemails, job application follow-ups, username updates, account statements, conference suggestions, and urgent Intuit support actions are potential phishing. Workshop details, program information, coach positions, invoice reviews on OneDrive, shipment address confirmations, PayPal balance checks, new Google Drive documents, payroll statements, secure PDFs, voicemail messages, terms of service completions, mailbox sync issues, diplomatic package updates, document sign requests, email sign-in notifications, secure invoice emails, invoice openings, email delivery delays, student-athletes announcements, refunds, one-time password verifications, transaction confirmations, purchasing order confirmations, eVoice messages, new files, invoice reminders, email delivery reports, release letters, office availability inquiries, payment updates, sales contract details, new bills, KSU infringement notices, and account deactivation requests require vigilance. Spear phishing targets specific individuals or companies, often using ransomware tactics where emails from reputable companies prompt users to visit fake websites and divulge personal information. Pharming redirects users to fake websites via altered DNS settings. Brand spoofing exploits brand recognition to deceive users into sharing sensitive information.Give the rating first and explain why."
def query_phi(prompt):
response = "" # Initialize an empty string to store the response
for message in client.chat_completion(
messages=[{"role": "user", "content": f"{instructions}\n{prompt}"}],
max_tokens=500,
stream=True,
):
response += message.choices[0].delta.content # Append each message to the response
return response # Return the accumulated response after the loop
def transcribe_and_query(audio):
# Transcribe the audio file
transcription = whisper(audio)["text"]
transcription = "Prompt : " + transcription
# Query Microsoft PHI 1.5 with the transcribed text
phi_response = query_phi(transcription)
return transcription, phi_response
# Create Gradio interface
iface = gr.Interface(
fn=transcribe_and_query,
inputs=gr.Audio(type="filepath"),
outputs=["text", "text"],
title="Whisper Audio Transcription with LLM",
description="Upload an audio file to transcribe using OpenAI Whisper and get responses from Microsoft PHI 1.5."
)
# Launch the interface
iface.launch()