awacke1 commited on
Commit
6bb6281
Β·
verified Β·
1 Parent(s): 3e503f0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +137 -0
app.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ import os
3
+ import shutil
4
+ import glob
5
+ import base64
6
+ import streamlit as st
7
+ import pandas as pd
8
+ import torch
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer
10
+ from torch.utils.data import Dataset, DataLoader
11
+ import csv
12
+ import time
13
+ from dataclasses import dataclass
14
+ from typing import Optional, Tuple
15
+ import zipfile
16
+ import math
17
+ from PIL import Image
18
+ import random
19
+ import logging
20
+
21
+ # Set up logging for feedback
22
+ logging.basicConfig(level=logging.INFO)
23
+ logger = logging.getLogger(__name__)
24
+
25
+ # Page Configuration with Humor
26
+ st.set_page_config(
27
+ page_title="SFT Tiny Titans πŸš€",
28
+ page_icon="πŸ€–",
29
+ layout="wide",
30
+ initial_sidebar_state="expanded",
31
+ menu_items={
32
+ 'Get Help': 'https://huggingface.co/awacke1',
33
+ 'Report a bug': 'https://huggingface.co/spaces/awacke1',
34
+ 'About': "Tiny Titans: Small models, big dreams, and a sprinkle of chaos! 🌌"
35
+ }
36
+ )
37
+
38
+ # [Previous sections like ModelConfig, SFTDataset, ModelBuilder, Utility Functions remain unchanged...]
39
+
40
+ # Cargo Travel Time Tool (Now a Proper smolagents Tool)
41
+ from smolagents import tool
42
+
43
+ @tool
44
+ def calculate_cargo_travel_time(origin_coords: Tuple[float, float], destination_coords: Tuple[float, float], cruising_speed_kmh: float = 750.0) -> float:
45
+ """Calculate cargo plane travel time between two coordinates."""
46
+ def to_radians(degrees: float) -> float:
47
+ return degrees * (math.pi / 180)
48
+ lat1, lon1 = map(to_radians, origin_coords)
49
+ lat2, lon2 = map(to_radians, destination_coords)
50
+ EARTH_RADIUS_KM = 6371.0
51
+ dlon = lon2 - lon1
52
+ dlat = lat2 - lat1
53
+ a = (math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2)
54
+ c = 2 * math.asin(math.sqrt(a))
55
+ distance = EARTH_RADIUS_KM * c
56
+ actual_distance = distance * 1.1
57
+ flight_time = (actual_distance / cruising_speed_kmh) + 1.0
58
+ return round(flight_time, 2)
59
+
60
+ # Main App
61
+ st.title("SFT Tiny Titans πŸš€ (Small but Mighty!)")
62
+
63
+ # Sidebar with Galleries (unchanged)
64
+ st.sidebar.header("Galleries & Shenanigans 🎨")
65
+ st.sidebar.subheader("Image Gallery πŸ“Έ")
66
+ img_files = get_gallery_files(["png", "jpg", "jpeg"])
67
+ if img_files:
68
+ img_cols = st.sidebar.slider("Image Columns πŸ“Έ", 1, 5, 3)
69
+ cols = st.sidebar.columns(img_cols)
70
+ for idx, img_file in enumerate(img_files[:img_cols * 2]):
71
+ with cols[idx % img_cols]:
72
+ st.image(Image.open(img_file), caption=f"{img_file} πŸ–Ό", use_column_width=True)
73
+
74
+ st.sidebar.subheader("CSV Gallery πŸ“Š")
75
+ csv_files = get_gallery_files(["csv"])
76
+ if csv_files:
77
+ for csv_file in csv_files[:5]:
78
+ st.sidebar.markdown(get_download_link(csv_file, "text/csv", f"{csv_file} πŸ“Š"), unsafe_allow_html=True)
79
+
80
+ st.sidebar.subheader("Model Management πŸ—‚οΈ")
81
+ model_dirs = get_model_files()
82
+ selected_model = st.sidebar.selectbox("Select Saved Model", ["None"] + model_dirs)
83
+ if selected_model != "None" and st.sidebar.button("Load Model πŸ“‚"):
84
+ if 'builder' not in st.session_state:
85
+ st.session_state['builder'] = ModelBuilder()
86
+ config = ModelConfig(name=os.path.basename(selected_model), base_model="unknown", size="small", domain="general")
87
+ st.session_state['builder'].load_model(selected_model, config)
88
+ st.session_state['model_loaded'] = True
89
+ st.rerun()
90
+
91
+ # Main UI with Tabs (only Tab 4 updated here)
92
+ tab1, tab2, tab3, tab4 = st.tabs(["Build Tiny Titan 🌱", "Fine-Tune Titan πŸ”§", "Test Titan πŸ§ͺ", "Agentic RAG Party 🌐"])
93
+
94
+ # [Tab 1, Tab 2, Tab 3 remain unchanged...]
95
+
96
+ with tab4:
97
+ st.header("Agentic RAG Party 🌐 (Party Like It’s 2099!)")
98
+ st.write("This demo uses Tiny Titans with Agentic RAG to plan a superhero party, powered by DuckDuckGo retrieval!")
99
+
100
+ if st.button("Run Agentic RAG Demo πŸŽ‰"):
101
+ try:
102
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool
103
+ from transformers import AutoModelForCausalLM
104
+
105
+ # Load the model
106
+ with st.spinner("Loading SmolLM-135M... ⏳ (Titan’s suiting up!)"):
107
+ model = AutoModelForCausalLM.from_pretrained("HuggingFaceTB/SmolLM-135M")
108
+ st.write("Model loaded! πŸ¦Έβ€β™‚οΈ (Ready to party!)")
109
+
110
+ # Initialize agent with proper tools
111
+ agent = CodeAgent(
112
+ model=model,
113
+ tools=[DuckDuckGoSearchTool(), VisitWebpageTool(), calculate_cargo_travel_time],
114
+ additional_authorized_imports=["pandas"],
115
+ planning_interval=5,
116
+ verbosity_level=2,
117
+ max_steps=15,
118
+ )
119
+
120
+ task = """
121
+ Plan a luxury superhero-themed party at Wayne Manor (42.3601Β° N, 71.0589Β° W). Use DuckDuckGo to search for the latest superhero party trends,
122
+ refine results for luxury elements (decorations, entertainment, catering), and calculate cargo travel times from key locations
123
+ (New York: 40.7128Β° N, 74.0060Β° W; LA: 34.0522Β° N, 118.2437Β° W; London: 51.5074Β° N, 0.1278Β° W) to Wayne Manor.
124
+ Synthesize a plan with at least 6 entries in a pandas dataframe, including locations, travel times, and luxury ideas.
125
+ Add a random superhero catchphrase to each entry for fun!
126
+ """
127
+ with st.spinner("Planning the ultimate superhero bash... ⏳ (Calling all caped crusaders!)"):
128
+ result = agent.run(task)
129
+ st.write("Agentic RAG Party Plan:")
130
+ st.write(result)
131
+ st.write("Party on, Wayne! πŸ¦Έβ€β™‚οΈπŸŽ‰")
132
+ except ImportError:
133
+ st.error("Please install required packages: `pip install smolagents pandas transformers`")
134
+ except TypeError as e:
135
+ st.error(f"Agent setup failed: {str(e)} (Looks like the Titans need a tune-up!)")
136
+ except Exception as e:
137
+ st.error(f"Error running demo: {str(e)} (Even Batman has off days!)")