CoolFace
Apppublic

Piyusha555/PathwayAI_A3

sourceHugging Faceupdated 4mo agoView on Hugging Face
0likes
app.py243 linesDownload Raw Back to root
1import gradio as gr2import os3import numpy as np4 5from huggingface_hub import InferenceClient6from sentence_transformers import SentenceTransformer7 8# ---------------------------9# Load Knowledge Base10# ---------------------------11 12with open("knowledge_base.txt", "r", encoding="utf-8") as f:13    knowledge_base = f.read()14 15chunks = [chunk.strip() for chunk in knowledge_base.split("\n\n") if chunk.strip()]16 17# ---------------------------18# Embedding Model19# ---------------------------20 21embedding_model = SentenceTransformer("all-MiniLM-L6-v2")22chunk_embeddings = embedding_model.encode(chunks)23 24# ---------------------------25# Language Model26# ---------------------------27 28client = InferenceClient(29    "Qwen/Qwen2.5-7B-Instruct",30    token=os.environ.get("HF_TOKEN")31)32 33# ---------------------------34# Retrieval Function35# ---------------------------36 37def retrieve_context(query, top_k=3):38    query_embedding = embedding_model.encode([query])[0]39 40    similarities = np.dot(chunk_embeddings, query_embedding)41 42    top_indices = np.argsort(similarities)[-top_k:][::-1]43 44    context = "\n\n".join([chunks[i] for i in top_indices])45 46    return context47 48# ---------------------------49# Chatbot Response Function50# ---------------------------51 52def respond(message, history):53 54    context = retrieve_context(message)55 56    messages = [57        {58            "role": "system",59            "content": f"""60You are Pathway AI, an educational guidance assistant designed to help students discover opportunities, resources, mentorship programs, scholarships, and career pathways.61 62Your mission is to make educational and professional opportunities more accessible, especially for students who may not have access to strong guidance networks.63 64Guidelines:65- Use the provided context as your primary source of information.66- If the answer is not available in the provided context, clearly state that you do not currently have that information in your knowledge base.67- Do not invent scholarships, organizations, opportunities, or facts.68- Be friendly, encouraging, supportive, and informative.69- Keep responses concise and easy to understand.70- When appropriate, suggest actionable next steps.71- When discussing careers, recommend relevant skills, resources, and opportunities.72- When discussing scholarships or programs, summarize eligibility and benefits when available.73 74Context:75{context}76"""77        },78        {79            "role": "user",80            "content": message81        }82    ]83 84    response = client.chat_completion(85        messages=messages,86        max_tokens=50087    )88 89    return response.choices[0].message.content.strip()90# ---------------------------91# UI Theme92# ---------------------------93 94theme = gr.themes.Soft(95    primary_hue="purple",96    secondary_hue="pink"97)98 99css = """100footer {101    display: none;102}103 104.gradio-container {105    max-width: 1000px !important;106    margin: auto !important;107    background: linear-gradient(108        180deg,109        #faf5ff 0%,110        #fdf4ff 100%111    );112}113 114.hero-card {115    text-align: center;116    background: white;117    padding: 25px;118    border-radius: 20px;119    margin-bottom: 20px;120    box-shadow: 0 4px 12px rgba(0,0,0,0.08);121}122 123.feature-card {124    background: white;125    padding: 20px;126    border-radius: 20px;127    margin-bottom: 20px;128    box-shadow: 0 4px 12px rgba(0,0,0,0.08);129}130 131 132.hero-card,133.feature-card {134    color: #1f2937 !important;135}136 137.hero-card h1,138.hero-card h2,139.hero-card h3,140.feature-card h1,141.feature-card h2,142.feature-card h3,143.feature-card p {144    color: #1f2937 !important;145}146 147body {148    color: #1f2937 !important;149}150 151.gradio-container {152    color: #1f2937 !important;153}154 155"""156 157# ---------------------------158# Build UI159# ---------------------------160 161with gr.Blocks(theme=theme, css=css) as demo:162 163    gr.Image(164        "banner.png.png",165        show_label=False,166        container=False167    )168 169    gr.HTML("""170    <div class="feature-card">171        <h3>๐Ÿš€ What can Pathway AI help with?</h3>172 173        ๐ŸŽ“ Scholarships<br>174        ๐Ÿš€ Opportunities<br>175        ๐Ÿ’œ Women in STEM<br>176        ๐Ÿค Mentorship<br>177        ๐Ÿ’ป Learning Resources<br>178        ๐Ÿงญ Career Exploration179    </div>180    """)181 182    gr.Markdown(183        "### ๐Ÿ’ก Try asking one of the example questions below to get started!"184    )185 186    chatbot = gr.Chatbot(187        height=500,188        show_label=False189    )190 191    msg = gr.Textbox(192        placeholder="Ask Pathway AI a question...",193        label=""194    )195 196    with gr.Row():197        send_btn = gr.Button("Send")198        clear_btn = gr.Button("Clear Chat")199 200    examples = gr.Examples(201        examples=[202            ["What scholarships are available for women in STEM?"],203            ["How can I find a mentor in technology?"],204            ["What opportunities are available for high school students interested in AI?"],205            ["I want to become a software engineer. Where should I start?"],206            ["What coding resources are best for beginners?"],207            ["Tell me about women leaders in STEM."],208            ["I want to learn machine learning. What resources would you recommend?"]209        ],210        inputs=msg211    )212 213    def chat(message, history):214        response = respond(message, history)215        history = history + [216            {"role": "user", "content": message},217            {"role": "assistant", "content": response}218        ]219        return "", history220 221    send_btn.click(222        chat,223        inputs=[msg, chatbot],224        outputs=[msg, chatbot]225    )226 227    msg.submit(228        chat,229        inputs=[msg, chatbot],230        outputs=[msg, chatbot]231    )232 233    clear_btn.click(234        lambda: [],235        outputs=chatbot236    )237 238    gr.Markdown("""239---240Built by KWK '26 AI/ML Scholars - Group A3 ๐Ÿ’œ241""")242 243demo.launch()