File size: 11,462 Bytes
428ac53
 
 
 
d153553
d9bb822
428ac53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d153553
d9bb822
 
 
 
 
 
 
d153553
 
d9bb822
 
 
 
 
 
 
 
 
 
 
d153553
 
d9bb822
 
 
 
d153553
d9bb822
 
 
 
 
 
d153553
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428ac53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d153553
 
428ac53
d153553
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428ac53
d153553
428ac53
 
d153553
428ac53
 
d153553
 
 
 
428ac53
 
 
d153553
 
428ac53
 
d153553
428ac53
d153553
 
 
 
 
 
428ac53
 
d153553
 
 
 
428ac53
 
d153553
428ac53
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9bb822
d153553
 
d9bb822
d153553
d9bb822
d153553
d9bb822
d153553
 
428ac53
d153553
 
 
 
 
 
 
 
 
428ac53
 
 
 
d9bb822
d153553
d9bb822
d153553
 
428ac53
d9bb822
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428ac53
d153553
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import streamlit as st
import os
import glob
import re
import base64
import pytz
from urllib.parse import quote
from gradio_client import Client
from datetime import datetime

# Initialize session state variables
if 'selected_file' not in st.session_state:
    st.session_state.selected_file = None
if 'view_mode' not in st.session_state:
    st.session_state.view_mode = 'view'
if 'files' not in st.session_state:
    st.session_state.files = []

# Define the markdown variables
Boxing_and_MMA_Commentary_and_Knowledge = """
# Boxing and UFC Study of 1971 - 2024 The Greatest Fights History

1. In Boxing, the most heart breaking fight in Boxing was the Boom Boom Mancini fight with Duku Kim.
2. After changes to Boxing made it more safe due to the heart break.
3. Rehydration of the brain after weight ins loss preparation for a match is life saving change.
4. Fighting went from 15 rounds to 12.

# UFC By Contrast..
1. 5 Rounds of 5 Minutes each.
2. Greatest UFC Fighters:
    - Jon Jones could be the greatest of all time (GOAT) since he never lost.
    - George St. Pierre
    - BJ Penn
    - Anderson Silva
    - Mighty Mouse MMA's heart at 125 pounds
    - Kabib retired 29 and 0
    - Fedor Milliano
    - Alex Pereira
    - James Tony
    - Randy Couture
3. You have to Judge them in their Championship Peak
4. Chris Weidman
5. Connor McGregor
6. Leg Breaking - Shin calcification and breaking baseball bats

# References:
1. Joe Rogan - Interview #2219
2. Donald J Trump
"""

Multiplayer_Custom_Hosting_Game_Servers_For_Simulated_Worlds = """
# Multiplayer Simulated Worlds

1. 7 Days To Die PC 
2. ARK: Survival Evolved PC 
3. Arma 3 PC 
4. Atlas PC 
5. Conan Exiles PC 
6. Craftopia PC 
7. DayZ PC 
8. Eco - Global Survival PC 
9. Empyrion - Galactic Survival PC 
10. Factorio PC 
11. Farming Simulator 19 PC 
12. Crossplay
13. Farming Simulator 22 
14. Last Oasis PC 
15. Last Oasis Classic PC 
16. Minecraft (Vanilla) PC 
17. Crossplay
18. Path of Titans
19. Rust PC 
20. SCP: Secret Laboratory PC 
21. SCUM PC
22. Satisfactory PC
23. Satisfactory (Experimental) PC 
24. Crossplay
25. Space Engineers 
26. Terraria (tShock & Vanilla) PC 
27. The Forest PC 
28. Crossplay
29. Valheim
"""

def sanitize_filename(text):
    """Create a safe filename from text while preserving spaces."""
    # First replace unsafe characters with spaces
    safe_text = re.sub(r'[^\w\s-]', ' ', text)
    # Remove any multiple spaces
    safe_text = re.sub(r'\s+', ' ', safe_text)
    # Trim leading/trailing spaces
    safe_text = safe_text.strip()
    return safe_text[:50]  # Limit length to 50 chars

def generate_timestamp_filename(query):
    """Generate filename with format: 1103AM 11032024 (Query).md"""
    # Get current time in Central timezone
    central = pytz.timezone('US/Central')
    current_time = datetime.now(central)
    
    # Format the timestamp parts
    time_str = current_time.strftime("%I%M%p")  # 1103AM format
    date_str = current_time.strftime("%m%d%Y")  # 11032024 format
    
    # Clean up the query for filename - now preserving spaces
    safe_query = sanitize_filename(query)
    
    # Construct filename: "1103AM 11032024 (Input with spaces).md"
    filename = f"{time_str} {date_str} ({safe_query}).md"
    
    return filename

def save_ai_interaction(query, ai_result):
    """Save AI interaction to a markdown file with new filename format."""
    filename = generate_timestamp_filename(query)
    
    # Format the content
    content = f"""# Query: {query}

## AI Response
{ai_result}
"""
    
    # Save to file
    try:
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(content)
        return filename
    except Exception as e:
        st.error(f"Error saving file: {e}")
        return None

def get_file_download_link(file_path):
    """Generate a base64 download link for a file."""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        b64 = base64.b64encode(content.encode()).decode()
        filename = os.path.basename(file_path)
        return f'<a href="data:text/markdown;base64,{b64}" download="{filename}">{filename}</a>'
    except Exception as e:
        st.error(f"Error creating download link: {e}")
        return None

# Function to parse markdown text and extract terms
def extract_terms(markdown_text):
    lines = markdown_text.strip().split('\n')
    terms = []
    for line in lines:
        line = re.sub(r'^[#*\->\d\.\s]+', '', line).strip()
        if line:
            terms.append(line)
    return terms

# Function to display terms with links
def display_terms_with_links(terms):
    search_urls = {
        "🚀🌌ArXiv": lambda k: f"/?q={quote(k)}",
        "📖": lambda k: f"https://en.wikipedia.org/wiki/{quote(k)}",
        "🔍": lambda k: f"https://www.google.com/search?q={quote(k)}",
        "▶️": lambda k: f"https://www.youtube.com/results?search_query={quote(k)}",
        "🔎": lambda k: f"https://www.bing.com/search?q={quote(k)}",
        "🐦": lambda k: f"https://twitter.com/search?q={quote(k)}",
    }
    for term in terms:
        links_md = ' '.join([f"[{emoji}]({url(term)})" for emoji, url in search_urls.items()])
        st.markdown(f"- **{term}** {links_md}", unsafe_allow_html=True)

# Function to perform AI lookup using Gradio client
def perform_ai_lookup(query):
    st.write("Performing AI Lookup...")
    client = Client("awacke1/Arxiv-Paper-Search-And-QA-RAG-Pattern")
    result1 = client.predict(
        prompt=query,
        llm_model_picked="mistralai/Mixtral-8x7B-Instruct-v0.1",
        stream_outputs=True,
        api_name="/ask_llm"
    )
    st.markdown("### Mixtral-8x7B-Instruct-v0.1 Result")
    st.markdown(result1)
    result2 = client.predict(
        prompt=query,
        llm_model_picked="mistralai/Mistral-7B-Instruct-v0.2",
        stream_outputs=True,
        api_name="/ask_llm"
    )
    st.markdown("### Mistral-7B-Instruct-v0.2 Result")
    st.markdown(result2)
    combined_result = f"{result1}\n\n{result2}"
    return combined_result

def display_file_content(file_path):
    """Display file content with editing capabilities."""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Display as code with line numbers
        st.code(content, line_numbers=True)
        
        # Edit functionality
        edited_content = st.text_area(
            "Edit content",
            content,
            height=400,
            key=f"edit_{os.path.basename(file_path)}"
        )
        
        if st.button("Save Changes", key=f"save_{os.path.basename(file_path)}"):
            try:
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(edited_content)
                st.success(f"Successfully saved changes to {file_path}")
            except Exception as e:
                st.error(f"Error saving changes: {e}")
    except Exception as e:
        st.error(f"Error reading file: {e}")

def file_management_sidebar():
    """Enhanced sidebar with file management capabilities."""
    st.sidebar.title("📁 File Management")

    # Get list of .md files
    md_files = sorted(glob.glob("*.md"))
    st.session_state.files = md_files
    
    if md_files:
        st.sidebar.markdown("### Markdown Files")
        for idx, file in enumerate(md_files):
            col1, col2, col3, col4 = st.sidebar.columns([4, 2, 1, 1])
            
            with col1:
                st.write(file)
            
            with col2:
                # Base64 download link
                st.markdown(get_file_download_link(file), unsafe_allow_html=True)
            
            with col3:
                # View button
                if st.button("📄", key=f"view_{idx}"):
                    st.session_state.selected_file = file
                    st.session_state.view_mode = 'view'
            
            with col4:
                # Edit button
                if st.button("✏️", key=f"edit_{idx}"):
                    st.session_state.selected_file = file
                    st.session_state.view_mode = 'edit'

        # Option to create a new markdown file
        if st.sidebar.button("Create New Markdown File"):
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            new_filename = f"note_{timestamp}.md"
            with open(new_filename, 'w', encoding='utf-8') as f:
                f.write("# New Markdown File\n")
            st.sidebar.success(f"Created new file: {new_filename}")
            st.session_state.selected_file = new_filename
            st.session_state.view_mode = 'edit'
    else:
        st.sidebar.write("No markdown files found.")
        if st.sidebar.button("Create New Markdown File"):
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            new_filename = f"note_{timestamp}.md"
            with open(new_filename, 'w', encoding='utf-8') as f:
                f.write("# New Markdown File\n")
            st.sidebar.success(f"Created new file: {new_filename}")
            st.session_state.selected_file = new_filename
            st.session_state.view_mode = 'edit'

def main():
    st.title("Markdown Content with AI Lookup and File Management")

    # Process query parameters and AI lookup first
    query_params = st.query_params
    query = query_params.get('q', '')
    show_initial_content = True  # Flag to control initial content display
    
    # First priority: Handle active query
    if query:
        show_initial_content = False  # Hide initial content when showing query results
        st.write(f"### Search query received: {query}")
        try:
            ai_result = perform_ai_lookup(query)
            
            # Save the interaction
            saved_file = save_ai_interaction(query, ai_result)
            if saved_file:
                st.success(f"Saved interaction to {saved_file}")
                st.session_state.selected_file = saved_file
                st.session_state.view_mode = 'view'
        except Exception as e:
            st.error(f"Error during AI lookup: {e}")

    # File management sidebar
    file_management_sidebar()

    # Second priority: Display selected file content if any
    if st.session_state.selected_file:
        show_initial_content = False  # Hide initial content when showing file content
        st.markdown(f"### Current File: {st.session_state.selected_file}")
        display_file_content(st.session_state.selected_file)

    # Show initial content: Either when first landing or when no interactive elements are active
    if show_initial_content:
        # First show the clickable terms with links
        terms1 = extract_terms(Boxing_and_MMA_Commentary_and_Knowledge)
        terms2 = extract_terms(Multiplayer_Custom_Hosting_Game_Servers_For_Simulated_Worlds)
        all_terms = terms1 + terms2

        col1, col2 = st.columns(2)
        
        with col1:
            st.markdown("### Boxing & MMA")
            st.markdown(Boxing_and_MMA_Commentary_and_Knowledge)
            st.markdown("#### Related Links")
            display_terms_with_links(terms1)
            
        with col2:
            st.markdown("### Multiplayer Games")
            st.markdown(Multiplayer_Custom_Hosting_Game_Servers_For_Simulated_Worlds)
            st.markdown("#### Related Links")
            display_terms_with_links(terms2)

if __name__ == "__main__":
    main()