import streamlit as st from streamlit_chat import message as st_message from streamlit_option_menu import option_menu import os import plotly.express as px from io import StringIO from langchain.schema import HumanMessage, SystemMessage, AIMessage from langchain.chat_models import AzureChatOpenAI, ChatOpenAI from langchain.memory import ConversationBufferWindowMemory from langchain.prompts import PromptTemplate import warnings import time from sqlalchemy import create_engine, Column, Integer, String, Text, Table, MetaData from sqlalchemy.orm import sessionmaker import matplotlib.pyplot as plt from langchain_groq import ChatGroq import pandas as pd import numpy as np from dotenv import load_dotenv import re warnings.filterwarnings("ignore", category=DeprecationWarning) load_dotenv() os.environ['GROQ_API_KEY'] = os.getenv("GROQ_API_KEY") llm = ChatGroq(model="llama-3.1-70b-versatile") # Streamlit page configuration st.set_page_config( page_title="TraffiTrack", page_icon="", layout="wide", initial_sidebar_state="expanded", ) # Initialize session state for messages and banned users if 'messages' not in st.session_state: st.session_state.messages = [{"message": "Hi! How can I assist you today?", "is_user": False}] if 'banned_users' not in st.session_state: st.session_state.banned_users = [] if 'flowmessages' not in st.session_state: st.session_state.flowmessages = [] # Function to handle registration def registration(): st.title("User Registration") # Ensure session state is initialized if "user_data" not in st.session_state: st.session_state.user_data = [] name = st.text_input("Enter your name") phone_number = st.text_input("Enter your phone number") if st.button("Register"): if name and phone_number: # Append user data to session state as a dictionary st.session_state.user_data.append({"name": name, "phone_number": phone_number}) st.success("Registration successful!") else: st.warning("Please fill in all fields.") # Function to simulate drug tracking data def generate_sample_data(): data = { "Drug Name": ["MDMA", "LSD", "Mephedrone", "Cocaine", "Heroin"], "Detected Instances": [10, 15, 7, 12, 5], "Flagged Users": [5, 10, 4, 7, 3], "IP Addresses": [3, 8, 2, 6, 2] } return pd.DataFrame(data) # Function to check for drug-related content and extract info def check_for_drug_content(input_text): drug_keywords = ["MDMA", "LSD", "Mephedrone", "Cocaine", "Heroin"] pattern = r'(\+?\d{1,3}[-. ]?)?\(?\d{1,4}?\)?[-. ]?\d{1,4}[-. ]?\d{1,4}[-. ]?\d{1,9}' # Regex for phone numbers ip_pattern = r'(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' # Regex for IP addresses found_drugs = [keyword for keyword in drug_keywords if keyword.lower() in input_text.lower()] phone_numbers = re.findall(pattern, input_text) ip_addresses = re.findall(ip_pattern, input_text) return found_drugs, phone_numbers, ip_addresses # Sidebar with options selected = option_menu( "Main Menu", ["Home", "Registration","Chat"], icons=['house', 'person','chat-dots'], menu_icon="cast", default_index=0, orientation="horizontal", styles={ "container": {"padding": "5px", "background-color": "#DEF9C4"}, "icon": {"color": "#468585", "font-size": "25px"}, "nav-link": { "font-size": "16px", "text-align": "left", "margin": "0px", "--hover-color": "#9CDBA6" }, "nav-link-selected": {"background-color": "#50B498"}, } ) # Function to get a response from the chat model def get_chatmodel_response(user_message): # Ensure user_message is a string if "user_data" in st.session_state and st.session_state.user_data: user_info = st.session_state.user_data[-1] # Get the most recent registered user name = user_info.get("name", "Unknown") phone_number = user_info.get("phone_number", "Unknown") else: name = "Unknown" phone_number = "Unknown" #better the prompt more formatting #chat types -> human message #response -> no drug message detected #from registration #remove debugging PROMPT_TEMPLATE = """ You are an expert assistant specializing in detecting drug-related messages for monitoring illegal drug activities. Your role is to analyze user messages carefully to identify mentions of illegal substances or any activity related to drug trafficking, sales, or use. Your task is not just to detect specific drug names but to understand the context of the conversation, even if indirect or slang terms are used. Key substances and related slang to focus on: - MDMA (Molly, Mandy) - LSD (Acid, Tabs) - Mephedrone (Meow Meow) - Cocaine (Coke, Snow, Blow, White, Charlie) - Heroin (Smack, H, Brown) - Marijuana (Weed, Pot, Mary Jane, Ganja, Bud) - Ecstasy (X, XTC, E) - Crack (Rock, Freebase) Common phrases to consider: - “Looking for Molly” (MDMA reference) - “I need some snow” (Cocaine reference) - “Got any tabs?” (LSD reference) - “Can you hook me up with some blow?” (Cocaine reference) - “I don’t want to mess with Charlie” (Cocaine reference in a negative context) Instructions: 1. If you detect any mention of the above substances, slang, or any activities related to drug sales, trafficking, or use, respond with a simple confirmation of detection, including the drug name or slang term detected. 2. Be aware of **negations** or sentences where the user may **refuse** the drugs (e.g., "I don’t want cocaine"). Do not flag these as positive detections. 3. **Do not** include the original user message in your response. 4. Ensure the format includes the following fields: sender's name, phone number, and the detected drug word/slang. However, if there is **no drug-related content**, respond with only the message "drug word detected: none." Below is the required format for your response: If a drug word is detected: {name} {phone_number} drug word detected: {{drug_word_detected}} If no drug word is detected: drug word detected: none Below is the user message User message: {user_message} Response: """ memory = ConversationBufferWindowMemory(k=5, return_messages=True) user_message = str(user_message) # Use the parameter user_message to format the prompt formatted_prompt = PROMPT_TEMPLATE.format( user_message=user_message, name=name, phone_number=phone_number ) # Add the formatted prompt to the conversation history st.session_state.flowmessages.append(HumanMessage(content=user_message)) # Generate a response from the model response = llm([SystemMessage(content=formatted_prompt)]) # Ensure the response.content is a string response_content = str(response.content) # Add the AI response to the conversation history st.session_state.flowmessages.append(AIMessage(content=response_content)) # Save the conversation context memory.save_context({"input": user_message}, {"output": response_content}) return response_content # User input for query # Button to send the message # if st.button("Send"): # if user_input: # response = get_chatmodel_response(user_input) # st.session_state.messages.append({"message": response, "is_user": False}) # st.experimental_rerun() # else: # st.warning("Please enter a message.") # Display the conversation history if "flowmessages" in st.session_state: st.subheader("Chat") for message in st.session_state.flowmessages: if isinstance(message, HumanMessage): st_message(message.content, is_user=True) elif isinstance(message, AIMessage): st_message(message.content, is_user=False) def display_home_info(): # Set background color st.markdown( """ """, unsafe_allow_html=True ) # Title with emoji st.title("🏠 Welcome to the Drug-Related Content Detector") # Section for description st.markdown( """