vsj0702 commited on
Commit
16093e8
·
verified ·
1 Parent(s): a1f96e4

fixing bugs

Browse files
Files changed (1) hide show
  1. app.py +82 -111
app.py CHANGED
@@ -1,123 +1,94 @@
1
  import streamlit as st
2
- import streamlit_ace as st_ace
3
- from utils import execute_code, export_session
4
- from chatbot import render_chatbot
5
- import json
 
 
 
 
6
 
7
- # 1️⃣ Page configuration (must be first)
8
- st.set_page_config(
9
- page_title="Pro Code Playground",
10
- page_icon="💻",
11
- layout="wide"
12
- )
13
 
14
- # 2️⃣ Dark mode toggle
15
- if 'dark_mode' not in st.session_state:
16
- st.session_state.dark_mode = True
 
 
 
 
 
 
 
 
 
17
 
18
- dm = st.checkbox("🌙 Dark mode", value=st.session_state.dark_mode)
19
- st.session_state.dark_mode = dm
 
 
 
 
 
 
 
 
 
 
20
 
21
- # 3️⃣ Theme variables
22
- BG = "#0f1620" if dm else "#f5f5f5"
23
- PANEL_BG = "#1c2330" if dm else "#ffffff"
24
- TEXT = "#e3e8f1" if dm else "#1a1a1a"
25
- ACCENT = "#ff5252"
26
- BORDER = "#2a3240" if dm else "#dddddd"
27
- SHADOW = "rgba(0,0,0,0.3)" if dm else "rgba(0,0,0,0.1)"
28
- ACE_THEME = "monokai" if dm else "chrome"
29
 
30
- # 4️⃣ Global CSS styling
31
- st.markdown(f"""
32
- <style>
33
- .stApp {{ background-color: {BG}; color: {TEXT}; }}
34
- [data-testid="stSidebar"] {{ background-color: {PANEL_BG} !important; }}
35
- .ace_editor, .ace_scroller {{
36
- background: {PANEL_BG} !important;
37
- box-shadow: 0 4px 8px {SHADOW} !important;
38
- border-radius: 8px !important;
39
- }}
40
- textarea, input, .stTextArea textarea {{
41
- background: {PANEL_BG} !important;
42
- color: {TEXT} !important;
43
- border: 1px solid {BORDER} !important;
44
- border-radius: 4px !important;
45
- }}
46
- button, .stDownloadButton > button {{
47
- background-color: {ACCENT} !important;
48
- color: #fff !important;
49
- border-radius: 6px !important;
50
- transition: transform 0.1s;
51
- }}
52
- button:hover {{ transform: scale(1.02) !important; }}
53
- .chat-container {{ background: {PANEL_BG} !important; border: 1px solid {BORDER} !important; border-radius: 8px !important; padding: 1rem; max-height: 480px; overflow-y: auto; }}
54
- .chat-message {{ margin-bottom: 1rem; padding: 0.75rem 1rem; border-radius: 12px; }}
55
- .user-message {{ background: rgba(100,149,237,0.2); align-self: flex-end; }}
56
- .bot-message {{ background: rgba(200,200,200,0.2); align-self: flex-start; }}
57
- pre code {{ display: block; padding: 0.5rem; background: rgba(0,0,0,0.1); border-radius: 4px; overflow-x: auto; }}
58
- </style>
59
- """, unsafe_allow_html=True)
60
 
61
- # 5️⃣ App header
62
- st.title("Pro Code Playground")
63
- st.markdown("Write, execute & export Python snippets, with built‑in AI assistance.")
 
64
 
65
- # 6️⃣ Main layout
66
- gen, bot = st.columns((2,1), gap="large")
 
 
 
 
67
 
68
- with gen:
69
- st.subheader("Editor")
70
- code = st_ace.st_ace(
71
- placeholder="Start typing your Python code…",
72
- language="python",
73
- theme=ACE_THEME,
74
- keybinding="vscode",
75
- font_size=14,
76
- min_lines=20,
77
- show_gutter=True,
78
- wrap=True,
79
- auto_update=True
80
- )
81
- if st.button("▶️ Run"):
82
- out, err, exc = execute_code(code)
83
- st.session_state.code_output = out
84
- st.session_state.error_output = err or exc
85
- if st.session_state.get("code_output"):
86
- st.text_area("Output", st.session_state.code_output, height=120)
87
- if st.session_state.get("error_output"):
88
- st.error(st.session_state.error_output)
89
 
90
- with bot:
91
- st.subheader("Code Assistant")
92
- render_chatbot(
93
- code,
94
- st.session_state.get("code_output", ""),
95
- st.session_state.get("error_output", "")
96
- )
97
 
98
- # 7️⃣ Export section
99
- st.markdown("---")
100
- st.subheader("Export")
101
- export_data = export_session(
102
- code,
103
- st.session_state.get("code_output", ""),
104
- st.session_state.get("error_output", "")
105
- )
106
- col1, col2 = st.columns(2)
107
- with col1:
108
- st.download_button(
109
- "📦 JSON",
110
- data=json.dumps(export_data, indent=2),
111
- file_name="session.json",
112
- mime="application/json"
113
- )
114
- with col2:
115
- txt = f"# Code\n{code}\n\n# Output\n{st.session_state.get('code_output','')}\n\n# Errors\n{st.session_state.get('error_output','')}"
116
- st.download_button("📝 Text", txt, "session.txt", "text/plain")
117
 
118
- # 8️⃣ Footer
119
- st.markdown(f"""
120
- <div style='text-align:center; margin-top:1rem; color:{TEXT}66;'>
121
- Built with ❤️ & Streamlit
122
- </div>
123
- """, unsafe_allow_html=True)
 
 
 
 
 
 
1
  import streamlit as st
2
+ from groq import Groq
3
+ from langchain_groq import ChatGroq
4
+ from langchain_core.prompts import ChatPromptTemplate
5
+ from langchain_core.output_parsers import StrOutputParser
6
+ from html import escape
7
+ import edge_tts
8
+ import asyncio
9
+ import os
10
 
11
+ GROQ_API_KEY = os.getenv('GROQ_API_KEY')
 
 
 
 
 
12
 
13
+ class CodeAssistantBot:
14
+ def __init__(self):
15
+ self.client = Groq(api_key=GROQ_API_KEY)
16
+ self.model = ChatGroq(model="llama-3.3-70b-versatile", temperature=0.6)
17
+ self.analysis_prompt = ChatPromptTemplate.from_messages([
18
+ ("system", "You are an expert code assistant. Keep responses concise."),
19
+ ("user", "Code: {code}\nOutput: {output}\nError: {error}\nQuestion: {question}")
20
+ ])
21
+ self.summary_prompt = ChatPromptTemplate.from_messages([
22
+ ("system", "Summarize key technical points."),
23
+ ("user", "Conversation: {conversation}")
24
+ ])
25
 
26
+ def analyze_code(self, code, output, error, question):
27
+ try:
28
+ parser = StrOutputParser()
29
+ chain = self.analysis_prompt | self.model | parser
30
+ return chain.invoke({
31
+ 'code': code,
32
+ 'output': output,
33
+ 'error': error,
34
+ 'question': question
35
+ })
36
+ except Exception as e:
37
+ return f"Error: {e}"
38
 
39
+ async def text_to_speech(text, filename):
40
+ voice = "fr-FR-VivienneMultilingualNeural"
41
+ await edge_tts.Communicate(text, voice).save(filename)
 
 
 
 
 
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ def render_chatbot(code, output, error):
45
+ """Render the chatbot UI with code-block support and no deprecated APIs."""
46
+ st.session_state.setdefault('conversation', [])
47
+ st.session_state.setdefault('audio_count', 0)
48
 
49
+ # Input row
50
+ c1, c2 = st.columns([4,1], gap='small')
51
+ with c1:
52
+ question = st.text_input("Ask your question…", key="chat_input")
53
+ with c2:
54
+ send = st.button("🚀")
55
 
56
+ # Handle send
57
+ if send and question:
58
+ bot = CodeAssistantBot()
59
+ response = bot.analyze_code(code, output, error, question)
60
+ st.session_state.conversation.append((question, response))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ # Chat container
63
+ st.markdown('<div class="chat-container">', unsafe_allow_html=True)
64
+ for q, a in st.session_state.conversation:
65
+ # User message
66
+ st.markdown(f'<div class="chat-message user-message">{escape(q)}</div>', unsafe_allow_html=True)
 
 
67
 
68
+ # Bot message with code formatting
69
+ def format_response(text):
70
+ parts = text.split('```')
71
+ result = ''
72
+ for i, part in enumerate(parts):
73
+ if i % 2 == 1:
74
+ # Remove optional language tag
75
+ lines = part.splitlines()
76
+ if lines and lines[0].isalpha():
77
+ lines = lines[1:]
78
+ code_html = escape("\n".join(lines))
79
+ result += f'<pre><code>{code_html}</code></pre>'
80
+ else:
81
+ result += escape(part)
82
+ return result
 
 
 
 
83
 
84
+ formatted = format_response(a)
85
+ st.markdown(f'<div class="chat-message bot-message">{formatted}</div>', unsafe_allow_html=True)
86
+ st.markdown('</div>', unsafe_allow_html=True)
87
+
88
+ # Auto-scroll
89
+ st.markdown("""
90
+ <script>
91
+ const c = window.parent.document.querySelector('.chat-container');
92
+ if (c) c.scrollTop = c.scrollHeight;
93
+ </script>
94
+ """, unsafe_allow_html=True)