liucen56 commited on
Commit
69ff5ef
Β·
verified Β·
1 Parent(s): 91857dd

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +44 -7
  2. app.py +1028 -0
  3. config.json +21 -0
  4. requirements.txt +5 -0
README.md CHANGED
@@ -1,14 +1,51 @@
1
  ---
2
- title: Frenchlearning
3
- emoji: 🐠
4
- colorFrom: gray
5
- colorTo: purple
6
  sdk: gradio
7
- sdk_version: 5.41.1
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
- short_description: French learning
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Language Learning Partner
3
+ emoji: πŸ’¬
4
+ colorFrom: blue
5
+ colorTo: green
6
  sdk: gradio
7
+ sdk_version: 5.39.0
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
+ short_description: AI French conversation partner
12
  ---
13
 
14
+ # Language Learning Partner
15
+
16
+ AI French conversation partner
17
+
18
+ ## Quick Setup
19
+
20
+ ### Step 1: Configure API Key (Required)
21
+ 1. Get your API key from https://openrouter.ai/keys
22
+ 2. In Settings β†’ Variables and secrets
23
+ 3. Add secret: `API_KEY`
24
+ 4. Paste your OpenRouter API key
25
+
26
+ ### Step 2: Configure HuggingFace Token (Optional)
27
+ 1. Get your token from https://huggingface.co/settings/tokens
28
+ 2. In Settings β†’ Variables and secrets
29
+ 3. Add secret: `HF_TOKEN`
30
+ 4. Paste your HuggingFace token (needs write permissions)
31
+ 5. This enables automatic configuration updates
32
+
33
+
34
+ ### Step 3: Set Access Code
35
+ 1. In Settings β†’ Variables and secrets
36
+ 2. Add secret: `ACCESS_CODE`
37
+ 3. Set your chosen password
38
+ 4. Share with authorized users
39
+
40
+
41
+ ### Step 3: Test Your Space
42
+ Your Space should now be running! Try the example prompts or ask your own questions.
43
+
44
+ ## Configuration
45
+ - **Model**: google/gemma-3-27b-it
46
+ - **API Key Variable**: API_KEY
47
+ - **HF Token Variable**: HF_TOKEN (for auto-updates)
48
+ - **Access Control**: Enabled (ACCESS_CODE)
49
+
50
+ ## Support
51
+ For help, visit the HuggingFace documentation or community forums.
app.py ADDED
@@ -0,0 +1,1028 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tempfile
3
+ import os
4
+ import requests
5
+ import json
6
+ import re
7
+ from bs4 import BeautifulSoup
8
+ from datetime import datetime
9
+ import urllib.parse
10
+ from pathlib import Path
11
+ from typing import List, Dict, Optional, Any, Tuple
12
+
13
+
14
+ # Configuration
15
+ SPACE_NAME = 'Language Learning Partner'
16
+ SPACE_DESCRIPTION = 'AI French conversation partner'
17
+
18
+ # Default configuration values
19
+ DEFAULT_CONFIG = {
20
+ 'name': SPACE_NAME,
21
+ 'description': SPACE_DESCRIPTION,
22
+ 'system_prompt': "You are Genevieve from Paris, a native French speaker serving as a conversational partner for university students in a French 101 class. Students will interact and converse with you in French, and you must respond EXCLUSIVELY IN FRENCH without providing English translations, using vocabulary appropriate for beginner-level French 101 students. Focus your responses on topics suitable for beginners such as daily life, routines, food, numbers, films, arts, literature, hobbies. When students make errors, model the correct forms naturally in your response without explicitly pointing out mistakes, allowing them to learn through exposure to proper usage. Recognize when students demonstrate more advanced abilities and adjust your language complexity accordingly, while ensuring your French remains error-free. Keep all responses between 50-100 words, making sure sentences are grammatically complete. Limit all verb conjugations to the present tense only, avoiding all other verb forms and tenses. Address students using the informal second-person singular 'tu' form. Use passe participle, passe recent, futur proche, futur, present tenses. ",
23
+ 'temperature': 0.5,
24
+ 'max_tokens': 1300,
25
+ 'model': 'google/gemma-3-27b-it',
26
+ 'api_key_var': 'API_KEY',
27
+ 'theme': 'Default',
28
+ 'grounding_urls': [],
29
+ 'enable_dynamic_urls': True,
30
+ 'enable_file_upload': True,
31
+ 'examples': ['Tu a fait quoi le semaine?', 'Tu va faire quoi le soir?', 'A che ora ti svegli la mattina?', 'Qual Γ¨ il tuo sport preferito?'],
32
+ 'language': 'French',
33
+ 'locked': False
34
+ }
35
+
36
+ # Available themes with proper instantiation
37
+ AVAILABLE_THEMES = {
38
+ "Default": gr.themes.Default(),
39
+ "Soft": gr.themes.Soft(),
40
+ "Glass": gr.themes.Glass(),
41
+ "Monochrome": gr.themes.Monochrome(),
42
+ "Base": gr.themes.Base()
43
+ }
44
+
45
+
46
+ class ConfigurationManager:
47
+ """Manage configuration with validation and persistence"""
48
+
49
+ def __init__(self):
50
+ self.config_path = "config.json"
51
+ self.backup_dir = "config_backups"
52
+ self._config = None
53
+
54
+ def load(self) -> Dict[str, Any]:
55
+ """Load configuration from file with fallback to defaults"""
56
+ try:
57
+ with open(self.config_path, 'r') as f:
58
+ self._config = json.load(f)
59
+ print("βœ… Loaded configuration from config.json")
60
+ return self._config
61
+ except FileNotFoundError:
62
+ print("ℹ️ No config.json found, using default configuration")
63
+ self._config = DEFAULT_CONFIG.copy()
64
+ self.save(self._config)
65
+ return self._config
66
+ except Exception as e:
67
+ print(f"⚠️ Error loading config.json: {e}, using defaults")
68
+ self._config = DEFAULT_CONFIG.copy()
69
+ return self._config
70
+
71
+ def save(self, config: Dict[str, Any]) -> bool:
72
+ """Save configuration with automatic backup"""
73
+ try:
74
+ # Create backup if config exists
75
+ if os.path.exists(self.config_path):
76
+ self._create_backup()
77
+
78
+ # Save new configuration
79
+ with open(self.config_path, 'w') as f:
80
+ json.dump(config, f, indent=2)
81
+
82
+ self._config = config
83
+ return True
84
+ except Exception as e:
85
+ print(f"❌ Error saving configuration: {e}")
86
+ return False
87
+
88
+ def _create_backup(self):
89
+ """Create timestamped backup"""
90
+ try:
91
+ os.makedirs(self.backup_dir, exist_ok=True)
92
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
93
+ backup_path = os.path.join(self.backup_dir, f"config_{timestamp}.json")
94
+
95
+ with open(self.config_path, 'r') as source:
96
+ config_data = json.load(source)
97
+ with open(backup_path, 'w') as backup:
98
+ json.dump(config_data, backup, indent=2)
99
+
100
+ self._cleanup_old_backups()
101
+ except Exception as e:
102
+ print(f"⚠️ Error creating backup: {e}")
103
+
104
+ def _cleanup_old_backups(self, keep=10):
105
+ """Keep only the most recent backups"""
106
+ try:
107
+ backups = sorted([
108
+ f for f in os.listdir(self.backup_dir)
109
+ if f.startswith('config_') and f.endswith('.json')
110
+ ])
111
+
112
+ if len(backups) > keep:
113
+ for old_backup in backups[:-keep]:
114
+ os.remove(os.path.join(self.backup_dir, old_backup))
115
+ except Exception as e:
116
+ print(f"⚠️ Error cleaning up backups: {e}")
117
+
118
+ def get(self, key: str, default: Any = None) -> Any:
119
+ """Get configuration value"""
120
+ if self._config is None:
121
+ self.load()
122
+ return self._config.get(key, default)
123
+
124
+
125
+ # Initialize configuration manager
126
+ config_manager = ConfigurationManager()
127
+ config = config_manager.load()
128
+
129
+ # Load configuration values
130
+ SPACE_NAME = config.get('name', DEFAULT_CONFIG['name'])
131
+ SPACE_DESCRIPTION = config.get('description', DEFAULT_CONFIG['description'])
132
+ SYSTEM_PROMPT = config.get('system_prompt', DEFAULT_CONFIG['system_prompt'])
133
+ temperature = config.get('temperature', DEFAULT_CONFIG['temperature'])
134
+ max_tokens = config.get('max_tokens', DEFAULT_CONFIG['max_tokens'])
135
+ MODEL = config.get('model', DEFAULT_CONFIG['model'])
136
+ THEME = config.get('theme', DEFAULT_CONFIG['theme'])
137
+ GROUNDING_URLS = config.get('grounding_urls', DEFAULT_CONFIG['grounding_urls'])
138
+ ENABLE_DYNAMIC_URLS = config.get('enable_dynamic_urls', DEFAULT_CONFIG['enable_dynamic_urls'])
139
+ ENABLE_FILE_UPLOAD = config.get('enable_file_upload', DEFAULT_CONFIG.get('enable_file_upload', True))
140
+ LANGUAGE = config.get('language', DEFAULT_CONFIG.get('language', 'English'))
141
+
142
+ # Environment variables
143
+ ACCESS_CODE = os.environ.get("ACCESS_CODE")
144
+ API_KEY_VAR = config.get('api_key_var', DEFAULT_CONFIG['api_key_var'])
145
+ API_KEY = os.environ.get(API_KEY_VAR, "").strip() or None
146
+ HF_TOKEN = os.environ.get('HF_TOKEN', '')
147
+ SPACE_ID = os.environ.get('SPACE_ID', '')
148
+
149
+
150
+ # Utility functions
151
+ def validate_api_key() -> bool:
152
+ """Validate API key configuration"""
153
+ if not API_KEY:
154
+ print(f"⚠️ API KEY CONFIGURATION ERROR:")
155
+ print(f" Variable name: {API_KEY_VAR}")
156
+ print(f" Status: Not set or empty")
157
+ print(f" Action needed: Set '{API_KEY_VAR}' in HuggingFace Space secrets")
158
+ return False
159
+ elif not API_KEY.startswith('sk-or-'):
160
+ print(f"⚠️ API KEY FORMAT WARNING:")
161
+ print(f" Variable name: {API_KEY_VAR}")
162
+ print(f" Note: OpenRouter keys should start with 'sk-or-'")
163
+ return True
164
+ else:
165
+ print(f"βœ… API Key configured successfully")
166
+ return True
167
+
168
+
169
+ def validate_url_domain(url: str) -> bool:
170
+ """Validate URL domain"""
171
+ try:
172
+ from urllib.parse import urlparse
173
+ parsed = urlparse(url)
174
+ return bool(parsed.netloc and parsed.scheme in ['http', 'https'])
175
+ except:
176
+ return False
177
+
178
+
179
+ def fetch_url_content(url: str, max_length: int = 3000) -> str:
180
+ """Fetch and convert URL content to text"""
181
+ try:
182
+ if not validate_url_domain(url):
183
+ return f"❌ Invalid URL format: {url}"
184
+
185
+ headers = {
186
+ 'User-Agent': 'Mozilla/5.0 (compatible; HuggingFace-Space/1.0)'
187
+ }
188
+
189
+ response = requests.get(url, headers=headers, timeout=5)
190
+ response.raise_for_status()
191
+
192
+ content_type = response.headers.get('content-type', '').lower()
193
+
194
+ if 'text/html' in content_type:
195
+ soup = BeautifulSoup(response.text, 'html.parser')
196
+
197
+ # Remove script and style elements
198
+ for script in soup(["script", "style"]):
199
+ script.extract()
200
+
201
+ # Get text content
202
+ text = soup.get_text(separator=' ', strip=True)
203
+
204
+ # Clean up whitespace
205
+ text = ' '.join(text.split())
206
+
207
+ # Limit content length
208
+ if len(text) > max_length:
209
+ text = text[:max_length] + "... [truncated]"
210
+
211
+ return f"πŸ“„ **Content from:** {url}\n\n{text}\n"
212
+
213
+ elif any(ct in content_type for ct in ['text/plain', 'application/json']):
214
+ text = response.text
215
+ if len(text) > max_length:
216
+ text = text[:max_length] + "... [truncated]"
217
+ return f"πŸ“„ **Content from:** {url}\n\n{text}\n"
218
+
219
+ else:
220
+ return f"⚠️ Unsupported content type at {url}: {content_type}"
221
+
222
+ except requests.exceptions.Timeout:
223
+ return f"⏱️ Timeout accessing {url}"
224
+ except requests.exceptions.RequestException as e:
225
+ return f"❌ Error accessing {url}: {str(e)}"
226
+ except Exception as e:
227
+ return f"❌ Unexpected error with {url}: {str(e)}"
228
+
229
+
230
+ def extract_urls_from_text(text: str) -> List[str]:
231
+ """Extract URLs from message text"""
232
+ url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+(?:\.[^\s<>"{}|\\^`\[\]])*'
233
+ urls = re.findall(url_pattern, text)
234
+ return [url.rstrip('.,;:)?!') for url in urls]
235
+
236
+
237
+ def process_file_upload(file_path: str) -> str:
238
+ """Process uploaded file with Gradio best practices"""
239
+ if not file_path or not os.path.exists(file_path):
240
+ return "❌ File not found"
241
+
242
+ try:
243
+ file_size = os.path.getsize(file_path)
244
+ file_name = os.path.basename(file_path)
245
+ _, ext = os.path.splitext(file_path.lower())
246
+
247
+ # Text file extensions
248
+ text_extensions = {
249
+ '.txt', '.md', '.markdown', '.rst',
250
+ '.py', '.js', '.jsx', '.ts', '.tsx', '.json', '.yaml', '.yml',
251
+ '.html', '.htm', '.xml', '.css', '.scss',
252
+ '.java', '.c', '.cpp', '.h', '.cs', '.go', '.rs',
253
+ '.sh', '.bash', '.log', '.csv', '.sql'
254
+ }
255
+
256
+ max_chars = 5000 # Define max_chars limit for file reading
257
+
258
+ if ext in text_extensions:
259
+ with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
260
+ content = f.read(max_chars)
261
+ if len(content) == max_chars:
262
+ content += "\n... [truncated]"
263
+ return f"πŸ“„ **{file_name}** ({file_size:,} bytes)\n```{ext[1:]}\n{content}\n```"
264
+
265
+ # Special file types
266
+ elif ext == '.pdf':
267
+ return f"πŸ“‘ **{file_name}** (PDF, {file_size:,} bytes)\n⚠️ PDF support requires PyPDF2"
268
+ elif ext in {'.jpg', '.jpeg', '.png', '.gif', '.webp'}:
269
+ return f"πŸ–ΌοΈ **{file_name}** (Image, {file_size:,} bytes)"
270
+ elif ext in {'.xlsx', '.xls'}:
271
+ return f"πŸ“Š **{file_name}** (Spreadsheet, {file_size:,} bytes)"
272
+ elif ext in {'.zip', '.tar', '.gz', '.rar'}:
273
+ return f"πŸ—œοΈ **{file_name}** (Archive, {file_size:,} bytes)"
274
+ else:
275
+ return f"πŸ“Ž **{file_name}** ({ext or 'no extension'}, {file_size:,} bytes)"
276
+
277
+ except Exception as e:
278
+ return f"❌ Error processing file: {str(e)}"
279
+
280
+
281
+ # URL content cache
282
+ _url_content_cache = {}
283
+
284
+
285
+ def get_grounding_context() -> str:
286
+ """Get grounding context from configured URLs with caching"""
287
+ urls = GROUNDING_URLS
288
+ if isinstance(urls, str):
289
+ try:
290
+ urls = json.loads(urls)
291
+ except:
292
+ return ""
293
+
294
+ if not urls:
295
+ return ""
296
+
297
+ context_parts = []
298
+
299
+ # Process primary sources (first 2 URLs with 8000 char limit)
300
+ primary_urls = urls[:2]
301
+ if primary_urls:
302
+ context_parts.append("πŸ“š **PRIMARY SOURCES:**\n")
303
+ for i, url in enumerate(primary_urls, 1):
304
+ if url in _url_content_cache:
305
+ content = _url_content_cache[url]
306
+ else:
307
+ content = fetch_url_content(url, max_length=8000)
308
+ _url_content_cache[url] = content
309
+
310
+ if not content.startswith("❌") and not content.startswith("⏱️"):
311
+ context_parts.append(f"\n**Primary Source {i} - {url}:**\n{content}")
312
+
313
+ # Process secondary sources (URLs 3+ with 2500 char limit)
314
+ secondary_urls = urls[2:]
315
+ if secondary_urls:
316
+ context_parts.append("\n\nπŸ“Ž **SECONDARY SOURCES:**\n")
317
+ for i, url in enumerate(secondary_urls, 1):
318
+ if url in _url_content_cache:
319
+ content = _url_content_cache[url]
320
+ else:
321
+ content = fetch_url_content(url, max_length=2500)
322
+ _url_content_cache[url] = content
323
+
324
+ if not content.startswith("❌") and not content.startswith("⏱️"):
325
+ context_parts.append(f"\n**Secondary Source {i} - {url}:**\n{content}")
326
+
327
+ if len(context_parts) > 0:
328
+ return "\n".join(context_parts)
329
+ return ""
330
+
331
+
332
+ def export_conversation_to_markdown(history: List[Dict[str, str]]) -> str:
333
+ """Export conversation history to markdown"""
334
+ if not history:
335
+ return "No conversation to export."
336
+
337
+ markdown_content = f"""# Conversation Export
338
+ Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
339
+ Space: {SPACE_NAME}
340
+ Model: {MODEL}
341
+
342
+ ---
343
+
344
+ """
345
+
346
+ message_count = 0
347
+ for message in history:
348
+ if isinstance(message, dict):
349
+ role = message.get('role', 'unknown')
350
+ content = message.get('content', '')
351
+
352
+ if role == 'user':
353
+ message_count += 1
354
+ markdown_content += f"## User Message {message_count}\n\n{content}\n\n"
355
+ elif role == 'assistant':
356
+ markdown_content += f"## Assistant Response {message_count}\n\n{content}\n\n---\n\n"
357
+
358
+ return markdown_content
359
+
360
+
361
+ def generate_response(message: str, history: List[Dict[str, str]], files: Optional[List] = None) -> str:
362
+ """Generate response using OpenRouter API with file support"""
363
+
364
+ # API key validation
365
+ if not API_KEY:
366
+ return f"""πŸ”‘ **API Key Required**
367
+
368
+ Please configure your OpenRouter API key:
369
+ 1. Go to Settings (βš™οΈ) in your HuggingFace Space
370
+ 2. Click 'Variables and secrets'
371
+ 3. Add secret: **{API_KEY_VAR}**
372
+ 4. Value: Your OpenRouter API key (starts with `sk-or-`)
373
+
374
+ Get your API key at: https://openrouter.ai/keys"""
375
+
376
+ # Process files if provided
377
+ file_context = ""
378
+ file_notification = ""
379
+
380
+ if files:
381
+ file_contents = []
382
+ file_names = []
383
+
384
+ for file_info in files:
385
+ if isinstance(file_info, dict):
386
+ file_path = file_info.get('path', file_info.get('name', ''))
387
+ else:
388
+ file_path = str(file_info)
389
+
390
+ if file_path and os.path.exists(file_path):
391
+ try:
392
+ content = process_file_upload(file_path)
393
+ file_contents.append(content)
394
+ file_names.append(os.path.basename(file_path))
395
+ print(f"πŸ“„ Processed file: {os.path.basename(file_path)}")
396
+ except Exception as e:
397
+ print(f"❌ Error processing file: {e}")
398
+
399
+ if file_contents:
400
+ file_context = "\n\n[UPLOADED FILES]\n" + "\n\n".join(file_contents) + "\n"
401
+ file_notification = f"\n\n[Note: Uploaded files: {', '.join(file_names)}]"
402
+
403
+ # Get grounding context
404
+ grounding_context = get_grounding_context()
405
+
406
+ # Check for dynamic URLs in message
407
+ if ENABLE_DYNAMIC_URLS:
408
+ urls_in_message = extract_urls_from_text(message)
409
+ if urls_in_message:
410
+ print(f"πŸ”— Found {len(urls_in_message)} URLs in message")
411
+ dynamic_context = "\nπŸ“Ž **Dynamic Context:**\n"
412
+ for url in urls_in_message[:3]: # Limit to 3 URLs
413
+ content = fetch_url_content(url)
414
+ if not content.startswith("❌"):
415
+ dynamic_context += f"\n{content}"
416
+ grounding_context += dynamic_context
417
+
418
+ # Build messages with grounding context and file context in system prompt
419
+ system_content = SYSTEM_PROMPT
420
+
421
+ # Add language instruction if not English
422
+ if LANGUAGE != 'English':
423
+ system_content += f"\n\nIMPORTANT: You must respond EXCLUSIVELY in {LANGUAGE}. All your responses should be written entirely in {LANGUAGE}, even when user input is in a different language, particularly English."
424
+
425
+ if grounding_context:
426
+ system_content += "\n\nIMPORTANT: When providing information from the reference sources below, please cite the specific URL(s) where the information can be found."
427
+ system_content = f"{system_content}\n\n{grounding_context}"
428
+ if file_context:
429
+ system_content = f"{system_content}\n\n{file_context}"
430
+
431
+ messages = [{"role": "system", "content": system_content}]
432
+
433
+ # Add conversation history
434
+ for msg in history:
435
+ if isinstance(msg, dict) and 'role' in msg and 'content' in msg:
436
+ messages.append({
437
+ "role": msg['role'],
438
+ "content": msg['content']
439
+ })
440
+
441
+ # Add current message
442
+ messages.append({
443
+ "role": "user",
444
+ "content": message
445
+ })
446
+
447
+ # Make API request
448
+ try:
449
+ # Make API request
450
+ headers = {
451
+ "Authorization": f"Bearer {API_KEY}",
452
+ "Content-Type": "application/json",
453
+ "HTTP-Referer": f"https://huggingface.co/spaces/{SPACE_ID}" if SPACE_ID else "https://huggingface.co",
454
+ "X-Title": SPACE_NAME
455
+ }
456
+
457
+ data = {
458
+ "model": MODEL,
459
+ "messages": messages,
460
+ "temperature": temperature,
461
+ "max_tokens": max_tokens,
462
+ "stream": False
463
+ }
464
+
465
+ response = requests.post(
466
+ "https://openrouter.ai/api/v1/chat/completions",
467
+ headers=headers,
468
+ json=data,
469
+ timeout=30
470
+ )
471
+
472
+ if response.status_code == 200:
473
+ result = response.json()
474
+ ai_response = result['choices'][0]['message']['content']
475
+
476
+ # Add file notification if files were uploaded
477
+ if file_notification:
478
+ ai_response += file_notification
479
+
480
+ return ai_response
481
+ else:
482
+ error_data = response.json()
483
+ error_message = error_data.get('error', {}).get('message', 'Unknown error')
484
+ return f"❌ API Error ({response.status_code}): {error_message}"
485
+
486
+ except requests.exceptions.Timeout:
487
+ return "⏰ Request timeout (30s limit). Try a shorter message or different model."
488
+ except requests.exceptions.ConnectionError:
489
+ return "🌐 Connection error. Check your internet connection and try again."
490
+ except Exception as e:
491
+ return f"❌ Error: {str(e)}"
492
+
493
+
494
+ # Chat history for export
495
+ chat_history_store = []
496
+
497
+
498
+ def verify_hf_token_access() -> Tuple[bool, str]:
499
+ """Verify HuggingFace token and access"""
500
+ if not HF_TOKEN:
501
+ return False, "No HF_TOKEN found"
502
+
503
+ if not SPACE_ID:
504
+ return False, "No SPACE_ID found - running locally?"
505
+
506
+ try:
507
+ headers = {"Authorization": f"Bearer {HF_TOKEN}"}
508
+ response = requests.get(
509
+ f"https://huggingface.co/api/spaces/{SPACE_ID}",
510
+ headers=headers,
511
+ timeout=5
512
+ )
513
+ if response.status_code == 200:
514
+ return True, f"HF Token valid for {SPACE_ID}"
515
+ else:
516
+ return False, f"HF Token invalid or no access to {SPACE_ID}"
517
+ except Exception as e:
518
+ return False, f"Error verifying HF token: {str(e)}"
519
+
520
+
521
+ # Create main interface with clean tab structure
522
+ def create_interface():
523
+ """Create the Gradio interface with clean tab structure"""
524
+
525
+ # Get theme
526
+ theme = AVAILABLE_THEMES.get(THEME, gr.themes.Default())
527
+
528
+ # Validate API key on startup
529
+ API_KEY_VALID = validate_api_key()
530
+
531
+ # Check HuggingFace access
532
+ HF_ACCESS_VALID, HF_ACCESS_MESSAGE = verify_hf_token_access()
533
+
534
+ # Access control check
535
+ has_access = ACCESS_CODE is None # No access code required
536
+
537
+ with gr.Blocks(title=SPACE_NAME, theme=theme) as demo:
538
+ # State for access control
539
+ access_granted = gr.State(has_access)
540
+
541
+ # Header - always visible
542
+ gr.Markdown(f"# {SPACE_NAME}")
543
+ gr.Markdown(SPACE_DESCRIPTION)
544
+
545
+ # Access control panel (visible when access not granted)
546
+ with gr.Column(visible=(not has_access)) as access_panel:
547
+ gr.Markdown("### πŸ” Access Required")
548
+ gr.Markdown("Please enter the access code:")
549
+
550
+ with gr.Row():
551
+ access_input = gr.Textbox(
552
+ label="Access Code",
553
+ placeholder="Enter access code...",
554
+ type="password",
555
+ scale=3
556
+ )
557
+ access_btn = gr.Button("Submit", variant="primary", scale=1)
558
+
559
+ access_status = gr.Markdown()
560
+
561
+ # Main interface (visible when access granted)
562
+ with gr.Column(visible=has_access) as main_panel:
563
+ with gr.Tabs() as tabs:
564
+ # Chat Tab
565
+ with gr.Tab("πŸ’¬ Chat"):
566
+ # Get examples
567
+ examples = config.get('examples', [])
568
+ if isinstance(examples, str):
569
+ try:
570
+ examples = json.loads(examples)
571
+ except:
572
+ examples = []
573
+
574
+ # State to hold uploaded files
575
+ uploaded_files = gr.State([])
576
+
577
+ # Create chat interface
578
+ chatbot = gr.Chatbot(type="messages", height=400)
579
+ msg = gr.Textbox(label="Message", placeholder="Type your message here...", lines=2)
580
+
581
+ with gr.Row():
582
+ submit_btn = gr.Button("Send", variant="primary")
583
+ clear_btn = gr.Button("Clear")
584
+
585
+ # Export functionality
586
+ with gr.Row():
587
+ export_btn = gr.DownloadButton(
588
+ "πŸ“₯ Export Conversation",
589
+ variant="secondary",
590
+ size="sm"
591
+ )
592
+
593
+ # Export handler
594
+ def prepare_export():
595
+ if not chat_history_store:
596
+ return None
597
+
598
+ content = export_conversation_to_markdown(chat_history_store)
599
+
600
+ # Create filename
601
+ space_name_safe = re.sub(r'[^a-zA-Z0-9]+', '_', SPACE_NAME).lower()
602
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
603
+ filename = f"{space_name_safe}_conversation_{timestamp}.md"
604
+
605
+ # Save to temp file
606
+ temp_path = Path(tempfile.gettempdir()) / filename
607
+ temp_path.write_text(content, encoding='utf-8')
608
+
609
+ return str(temp_path)
610
+
611
+ export_btn.click(
612
+ prepare_export,
613
+ outputs=[export_btn]
614
+ )
615
+
616
+ # Examples section
617
+ if examples:
618
+ gr.Examples(examples=examples, inputs=msg)
619
+
620
+ # Chat functionality
621
+ def respond(message, chat_history, files_state, is_granted):
622
+ if not is_granted:
623
+ return chat_history, "", is_granted
624
+
625
+ if not message:
626
+ return chat_history, "", is_granted
627
+
628
+ # Format history for the generate_response function
629
+ formatted_history = []
630
+ for h in chat_history:
631
+ if isinstance(h, dict):
632
+ formatted_history.append(h)
633
+
634
+ # Get response
635
+ response = generate_response(message, formatted_history, files_state)
636
+
637
+ # Update chat history
638
+ chat_history = chat_history + [
639
+ {"role": "user", "content": message},
640
+ {"role": "assistant", "content": response}
641
+ ]
642
+
643
+ # Update stored history for export
644
+ global chat_history_store
645
+ chat_history_store = chat_history
646
+
647
+ return chat_history, "", is_granted
648
+
649
+ # Wire up the interface
650
+ msg.submit(respond, [msg, chatbot, uploaded_files, access_granted], [chatbot, msg, access_granted])
651
+ submit_btn.click(respond, [msg, chatbot, uploaded_files, access_granted], [chatbot, msg, access_granted])
652
+ clear_btn.click(lambda: ([], ""), outputs=[chatbot, msg])
653
+
654
+ # File upload accordion
655
+ if ENABLE_FILE_UPLOAD:
656
+ with gr.Accordion("πŸ“Ž Upload Files", open=False):
657
+ file_upload = gr.File(
658
+ label="Upload Files",
659
+ file_types=None,
660
+ file_count="multiple",
661
+ visible=True,
662
+ interactive=True
663
+ )
664
+ clear_files_btn = gr.Button("Clear Files", size="sm", variant="secondary")
665
+ uploaded_files_display = gr.Markdown("", visible=False)
666
+
667
+ def handle_file_upload(files):
668
+ if not files:
669
+ return [], "", gr.update(visible=False)
670
+
671
+ file_names = []
672
+ for file_info in files:
673
+ if isinstance(file_info, dict):
674
+ file_path = file_info.get('path', file_info.get('name', ''))
675
+ else:
676
+ file_path = str(file_info)
677
+
678
+ if file_path and os.path.exists(file_path):
679
+ file_names.append(os.path.basename(file_path))
680
+
681
+ if file_names:
682
+ display_text = f"πŸ“Ž **Uploaded files:** {', '.join(file_names)}"
683
+ return files, display_text, gr.update(visible=True)
684
+ return [], "", gr.update(visible=False)
685
+
686
+ def clear_files():
687
+ return None, [], "", gr.update(visible=False)
688
+
689
+ file_upload.change(
690
+ handle_file_upload,
691
+ inputs=[file_upload],
692
+ outputs=[uploaded_files, uploaded_files_display, uploaded_files_display]
693
+ )
694
+
695
+ clear_files_btn.click(
696
+ clear_files,
697
+ outputs=[file_upload, uploaded_files, uploaded_files_display, uploaded_files_display]
698
+ )
699
+
700
+ # Configuration accordion
701
+ with gr.Accordion("ℹ️ Configuration", open=False):
702
+ gr.JSON(
703
+ value=config,
704
+ label="config.json",
705
+ show_label=True
706
+ )
707
+
708
+ # Configuration Tab
709
+ with gr.Tab("βš™οΈ Configuration"):
710
+ gr.Markdown("## Configuration Management")
711
+
712
+ # State for config tab authentication
713
+ config_authenticated = gr.State(False)
714
+
715
+ # Authentication panel
716
+ with gr.Column(visible=True) as config_auth_panel:
717
+ gr.Markdown("### πŸ” Authentication Required")
718
+ gr.Markdown("Enter your HF_TOKEN to access configuration settings:")
719
+
720
+ with gr.Row():
721
+ config_password = gr.Textbox(
722
+ label="HF Token",
723
+ placeholder="Enter your HF_TOKEN...",
724
+ type="password",
725
+ scale=3
726
+ )
727
+ config_auth_btn = gr.Button("Authenticate", variant="primary", scale=1)
728
+
729
+ config_auth_status = gr.Markdown()
730
+
731
+ # Configuration panel (hidden until authenticated)
732
+ with gr.Column(visible=False) as config_panel:
733
+ # Show authentication status
734
+ if HF_ACCESS_VALID:
735
+ gr.Markdown(f"βœ… {HF_ACCESS_MESSAGE}")
736
+ gr.Markdown("Configuration changes will be saved to the HuggingFace repository.")
737
+ else:
738
+ gr.Markdown(f"ℹ️ {HF_ACCESS_MESSAGE}")
739
+ gr.Markdown("Set HF_TOKEN in Space secrets to enable auto-save.")
740
+
741
+ # Configuration editor
742
+ gr.Markdown("### βš™οΈ Configuration Editor")
743
+
744
+ # Show lock status if locked
745
+ if config.get('locked', False):
746
+ gr.Markdown("⚠️ **Note:** Configuration is locked.")
747
+
748
+ # Basic settings
749
+ with gr.Column():
750
+ edit_name = gr.Textbox(
751
+ label="Space Name",
752
+ value=config.get('name', ''),
753
+ max_lines=1
754
+ )
755
+ edit_model = gr.Dropdown(
756
+ label="Model",
757
+ choices=[
758
+ # Google models
759
+ "google/gemini-2.0-flash-001",
760
+ "google/gemma-3-27b-it",
761
+ # Anthropic models
762
+ "anthropic/claude-3.5-sonnet",
763
+ "anthropic/claude-3.5-haiku",
764
+ # OpenAI models
765
+ "openai/gpt-4o-mini-search-preview",
766
+ "openai/gpt-4.1-nano",
767
+ # MistralAI models
768
+ "mistralai/mistral-medium-3",
769
+ # DeepSeek models
770
+ "deepseek/deepseek-r1-distill-qwen-32b",
771
+ # NVIDIA models
772
+ "nvidia/llama-3.1-nemotron-70b-instruct",
773
+ # Qwen models
774
+ "qwen/qwen3-30b-a3b-instruct-2507"
775
+ ],
776
+ value=config.get('model', ''),
777
+ allow_custom_value=True
778
+ )
779
+
780
+ edit_language = gr.Dropdown(
781
+ label="Language",
782
+ choices=[
783
+ "Arabic",
784
+ "Bengali",
785
+ "English",
786
+ "French",
787
+ "German",
788
+ "Hindi",
789
+ "Italian",
790
+ "Japanese",
791
+ "Korean",
792
+ "Mandarin",
793
+ "Portuguese",
794
+ "Russian",
795
+ "Spanish",
796
+ "Turkish"
797
+ ],
798
+ value=config.get('language', 'English')
799
+ )
800
+
801
+ edit_description = gr.Textbox(
802
+ label="Description",
803
+ value=config.get('description', ''),
804
+ max_lines=2
805
+ )
806
+
807
+ edit_system_prompt = gr.Textbox(
808
+ label="System Prompt",
809
+ value=config.get('system_prompt', ''),
810
+ lines=5
811
+ )
812
+
813
+ with gr.Row():
814
+ edit_temperature = gr.Slider(
815
+ label="Temperature",
816
+ minimum=0,
817
+ maximum=2,
818
+ value=config.get('temperature', 0.7),
819
+ step=0.1
820
+ )
821
+ edit_max_tokens = gr.Slider(
822
+ label="Max Tokens",
823
+ minimum=50,
824
+ maximum=4096,
825
+ value=config.get('max_tokens', 750),
826
+ step=50
827
+ )
828
+
829
+ edit_examples = gr.Textbox(
830
+ label="Example Prompts (one per line)",
831
+ value='\n'.join(config.get('examples', [])),
832
+ lines=3
833
+ )
834
+
835
+ # URL Grounding
836
+ gr.Markdown("### URL Grounding")
837
+ edit_grounding_urls = gr.Textbox(
838
+ label="Grounding URLs (one per line)",
839
+ placeholder="https://example.com/docs\nhttps://example.com/api",
840
+ value='\n'.join(config.get('grounding_urls', [])),
841
+ lines=5,
842
+ info="First 2 URLs: Primary sources (8000 chars). URLs 3+: Secondary sources (2500 chars)."
843
+ )
844
+
845
+ with gr.Row():
846
+ edit_enable_dynamic_urls = gr.Checkbox(
847
+ label="Enable Dynamic URL Extraction",
848
+ value=config.get('enable_dynamic_urls', True),
849
+ info="Extract and fetch URLs from user messages"
850
+ )
851
+ edit_enable_file_upload = gr.Checkbox(
852
+ label="Enable File Upload",
853
+ value=config.get('enable_file_upload', True),
854
+ info="Allow users to upload files for context"
855
+ )
856
+
857
+ # Configuration actions
858
+ with gr.Row():
859
+ save_btn = gr.Button("πŸ’Ύ Save Configuration", variant="primary")
860
+ reset_btn = gr.Button("↩️ Reset to Defaults", variant="secondary")
861
+
862
+ config_status = gr.Markdown()
863
+
864
+ def save_configuration(name, description, system_prompt, model, language, temp, tokens, examples, grounding_urls, enable_dynamic_urls, enable_file_upload):
865
+ """Save updated configuration"""
866
+ try:
867
+ updated_config = config.copy()
868
+ updated_config.update({
869
+ 'name': name,
870
+ 'description': description,
871
+ 'system_prompt': system_prompt,
872
+ 'model': model,
873
+ 'language': language,
874
+ 'temperature': temp,
875
+ 'max_tokens': int(tokens),
876
+ 'examples': [ex.strip() for ex in examples.split('\n') if ex.strip()],
877
+ 'grounding_urls': [url.strip() for url in grounding_urls.split('\n') if url.strip()],
878
+ 'enable_dynamic_urls': enable_dynamic_urls,
879
+ 'enable_file_upload': enable_file_upload,
880
+ 'locked': config.get('locked', False)
881
+ })
882
+
883
+ if config_manager.save(updated_config):
884
+ # Auto-commit if HF token is available
885
+ if HF_TOKEN and SPACE_ID:
886
+ try:
887
+ from huggingface_hub import HfApi, CommitOperationAdd
888
+ api = HfApi(token=HF_TOKEN)
889
+
890
+ operations = [
891
+ CommitOperationAdd(
892
+ path_or_fileobj=config_manager.config_path,
893
+ path_in_repo="config.json"
894
+ )
895
+ ]
896
+
897
+ api.create_commit(
898
+ repo_id=SPACE_ID,
899
+ operations=operations,
900
+ commit_message="Update configuration via web UI",
901
+ commit_description=f"Configuration update at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
902
+ repo_type="space",
903
+ token=HF_TOKEN
904
+ )
905
+ return "βœ… Configuration saved and committed to repository!"
906
+ except Exception as e:
907
+ return f"βœ… Configuration saved locally. ⚠️ Auto-commit failed: {str(e)}"
908
+ else:
909
+ return "βœ… Configuration saved locally (no HF token for auto-commit)"
910
+ else:
911
+ return "❌ Failed to save configuration"
912
+
913
+ except Exception as e:
914
+ return f"❌ Error: {str(e)}"
915
+
916
+ save_btn.click(
917
+ save_configuration,
918
+ inputs=[edit_name, edit_description, edit_system_prompt, edit_model, edit_language,
919
+ edit_temperature, edit_max_tokens, edit_examples, edit_grounding_urls,
920
+ edit_enable_dynamic_urls, edit_enable_file_upload],
921
+ outputs=[config_status]
922
+ )
923
+
924
+ def reset_configuration():
925
+ """Reset to default configuration"""
926
+ try:
927
+ if config_manager.save(DEFAULT_CONFIG):
928
+ return (
929
+ DEFAULT_CONFIG['name'],
930
+ DEFAULT_CONFIG['description'],
931
+ DEFAULT_CONFIG['system_prompt'],
932
+ DEFAULT_CONFIG['model'],
933
+ DEFAULT_CONFIG.get('language', 'English'),
934
+ DEFAULT_CONFIG['temperature'],
935
+ DEFAULT_CONFIG['max_tokens'],
936
+ '\n'.join(DEFAULT_CONFIG['examples']),
937
+ '\n'.join(DEFAULT_CONFIG['grounding_urls']),
938
+ DEFAULT_CONFIG['enable_dynamic_urls'],
939
+ DEFAULT_CONFIG['enable_file_upload'],
940
+ "βœ… Reset to default configuration"
941
+ )
942
+ else:
943
+ return (*[gr.update() for _ in range(11)], "❌ Failed to reset")
944
+ except Exception as e:
945
+ return (*[gr.update() for _ in range(11)], f"❌ Error: {str(e)}")
946
+
947
+ reset_btn.click(
948
+ reset_configuration,
949
+ outputs=[edit_name, edit_description, edit_system_prompt, edit_model, edit_language,
950
+ edit_temperature, edit_max_tokens, edit_examples, edit_grounding_urls,
951
+ edit_enable_dynamic_urls, edit_enable_file_upload, config_status]
952
+ )
953
+
954
+ # Configuration tab authentication handler
955
+ def handle_config_auth(password):
956
+ """Handle configuration tab authentication"""
957
+ if not HF_TOKEN:
958
+ return (
959
+ gr.update(visible=True), # Keep auth panel visible
960
+ gr.update(visible=False), # Keep config panel hidden
961
+ gr.update(value="❌ No HF_TOKEN is set in Space secrets. Configuration cannot be enabled."),
962
+ False
963
+ )
964
+
965
+ if password == HF_TOKEN:
966
+ return (
967
+ gr.update(visible=False), # Hide auth panel
968
+ gr.update(visible=True), # Show config panel
969
+ gr.update(value="βœ… Authentication successful!"),
970
+ True
971
+ )
972
+ else:
973
+ return (
974
+ gr.update(visible=True), # Keep auth panel visible
975
+ gr.update(visible=False), # Keep config panel hidden
976
+ gr.update(value="❌ Invalid HF_TOKEN. Please try again."),
977
+ False
978
+ )
979
+
980
+ config_auth_btn.click(
981
+ handle_config_auth,
982
+ inputs=[config_password],
983
+ outputs=[config_auth_panel, config_panel, config_auth_status, config_authenticated]
984
+ )
985
+
986
+ config_password.submit(
987
+ handle_config_auth,
988
+ inputs=[config_password],
989
+ outputs=[config_auth_panel, config_panel, config_auth_status, config_authenticated]
990
+ )
991
+
992
+ # Access control handler
993
+ if ACCESS_CODE:
994
+ def handle_access(code, current_state):
995
+ if code == ACCESS_CODE:
996
+ return (
997
+ gr.update(visible=False), # Hide access panel
998
+ gr.update(visible=True), # Show main panel
999
+ gr.update(value="βœ… Access granted!"), # Status message
1000
+ True # Update state
1001
+ )
1002
+ else:
1003
+ return (
1004
+ gr.update(visible=True), # Keep access panel visible
1005
+ gr.update(visible=False), # Keep main panel hidden
1006
+ gr.update(value="❌ Invalid access code. Please try again."), # Status message
1007
+ False # State remains false
1008
+ )
1009
+
1010
+ access_btn.click(
1011
+ handle_access,
1012
+ inputs=[access_input, access_granted],
1013
+ outputs=[access_panel, main_panel, access_status, access_granted]
1014
+ )
1015
+
1016
+ access_input.submit(
1017
+ handle_access,
1018
+ inputs=[access_input, access_granted],
1019
+ outputs=[access_panel, main_panel, access_status, access_granted]
1020
+ )
1021
+
1022
+ return demo
1023
+
1024
+
1025
+ # Create and launch the interface
1026
+ if __name__ == "__main__":
1027
+ demo = create_interface()
1028
+ demo.launch()
config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "Language Learning Partner",
3
+ "tagline": "AI French conversation partner",
4
+ "description": "AI French conversation partner",
5
+ "system_prompt": "You are Genevieve from Paris, a native French speaker serving as a conversational partner for university students in a French 101 class. Students will interact and converse with you in French, and you must respond EXCLUSIVELY IN FRENCH without providing English translations, using vocabulary appropriate for beginner-level French 101 students. Focus your responses on topics suitable for beginners such as daily life, routines, food, numbers, films, arts, literature, hobbies. When students make errors, model the correct forms naturally in your response without explicitly pointing out mistakes, allowing them to learn through exposure to proper usage. Recognize when students demonstrate more advanced abilities and adjust your language complexity accordingly, while ensuring your French remains error-free. Keep all responses between 50-100 words, making sure sentences are grammatically complete. Limit all verb conjugations to the present tense only, avoiding all other verb forms and tenses. Address students using the informal second-person singular 'tu' form. Use passe participle, passe recent, futur proche, futur, present tenses. ",
6
+ "model": "google/gemma-3-27b-it",
7
+ "language": "French",
8
+ "api_key_var": "API_KEY",
9
+ "temperature": 0.5,
10
+ "max_tokens": 1300,
11
+ "examples": [
12
+ "Tu a fait quoi le semaine?",
13
+ "Tu va faire quoi le soir?",
14
+ "A che ora ti svegli la mattina?",
15
+ "Qual \u00e8 il tuo sport preferito?"
16
+ ],
17
+ "grounding_urls": [],
18
+ "enable_dynamic_urls": true,
19
+ "enable_file_upload": true,
20
+ "theme": "Default"
21
+ }
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio>=5.39.0
2
+ requests>=2.32.3
3
+ beautifulsoup4>=4.12.3
4
+ python-dotenv>=1.0.0
5
+ huggingface-hub>=0.20.0