mnadell commited on
Commit
93677da
Β·
verified Β·
1 Parent(s): 8ac1e4d

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +44 -7
  2. app.py +1029 -0
  3. config.json +27 -0
  4. requirements.txt +5 -0
README.md CHANGED
@@ -1,14 +1,51 @@
1
  ---
2
- title: 41134114 Translation
3
- emoji: πŸ‘€
4
- colorFrom: purple
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 5.42.0
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
- short_description: a course assistant for History and Literature
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: 41134114 Translator
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: Writing History, Writing Literature
12
  ---
13
 
14
+ # 41134114 Translator
15
+
16
+ A course assistant to help students think about the way history and literature unpack the past.
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**: anthropic/claude-3.5-sonnet
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,1029 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = '41134114 Translator'
16
+ SPACE_DESCRIPTION = 'Writing History, Writing Literature'
17
+
18
+ # Default configuration values
19
+ DEFAULT_CONFIG = {
20
+ 'name': SPACE_NAME,
21
+ 'description': SPACE_DESCRIPTION,
22
+ 'system_prompt': 'You are a story-generator for Professor Martha Nadell\'s courses, "Introduction to History and Literature" and "Theories of History and Literature" at Brooklyn College in the fall of 2025. The purpose of the course is to reflect on how different types of sources, including general history, social history, urban history, fiction, first-person accounts, visual sources, and lived experience, helps us understand the past and the nature of particular places.\n \nThe stories should vary by genre, including non-fiction for a general audience, non-fiction social history, non-fiction urban history, realist fiction, modernist fiction, crime and detective novels, romance novels, the fiction of place, fiction that mixes multiple genres. The stories should be related to the subject of the course, the history and literature of Red Hook in Brooklyn in the twentieth and twenty-first centuries. The stories can be in the style of HP Lovecraft, Hubert Selby, Arthur Miller, Jonathan Lethem, and James McBride. \n \nResponse Guidelines\nWhen students enter a narrative, provide a response that changes the genre of the narrative. Ask students if they wish to change the audience for the response and what that audience would be. Then provide a new response to that request. Ask students what their purpose is. Provide a response that reflects that purpose.\n \nWhen students enter a series of facts or ideas, ask them to identify a genre for their response.\nWhen students enter a genre for their response, provide a response in that genre and ask them if they want to try a different genre. Ask students if they wish to change the audience for the response and what that audience would be. Then provide a new response to that request. Ask students what their purpose is. Provide a response that reflects that purpose.\n \nWhen students enter a new story, ask them what ideas or themes they want to emphasize. Provide a response that emphasizes those ideas and themes.\n \nYour follow-up questions should reflect the purpose of the course.\nAfter clarifying the genre, audience, and purpose, generate a response in the genre requested by the user, with the audience and purpose identified by the user. Then and always, ask the student to reflect on the affordances and constraints on each story, whether historical or fictional. DO NOT DO THE REFLECTION FOR THE STUDENTS. Ask them questions to encourage them to reflect, to engage in the exploration of the material co-generated.',
23
+ 'temperature': 0.7,
24
+ 'max_tokens': 400,
25
+ 'model': 'anthropic/claude-3.5-sonnet',
26
+ 'api_key_var': 'API_KEY',
27
+ 'theme': 'Glass',
28
+ 'grounding_urls': ["https://classics.mit.edu/Plato/phaedrus.1b.txt", "https://plato.stanford.edu/entries/plato-rhetoric/#Pha", "https://plato.stanford.edu/entries/plato-myths/", "https://en.wikipedia.org/wiki/Socratic_method"],
29
+ 'enable_dynamic_urls': True,
30
+ 'enable_file_upload': True,
31
+ 'examples': ['Can you help me write a story about this moment in history?', 'Can you tell me about history, based on this short story?', 'Can you help me think about the differences and similarities between history and literature?', "I'm confused about how to start writing historical fiction - where do I start?", "I'm confused about how to start writing about history - where do I start?"],
32
+ 'language': 'English',
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. Format citations as plain URLs without brackets, or use markdown link format like [text](url). Never use hard brackets like 【url】 as they break the links."
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",
766
+ "openai/gpt-4o-mini-search-preview",
767
+ "openai/gpt-oss-120b",
768
+ # MistralAI models
769
+ "mistralai/mistral-medium-3",
770
+ # DeepSeek models
771
+ "deepseek/deepseek-r1-distill-qwen-32b",
772
+ # NVIDIA models
773
+ "nvidia/llama-3.1-nemotron-70b-instruct",
774
+ # Qwen models
775
+ "qwen/qwen3-30b-a3b-instruct-2507"
776
+ ],
777
+ value=config.get('model', ''),
778
+ allow_custom_value=True
779
+ )
780
+
781
+ edit_language = gr.Dropdown(
782
+ label="Language",
783
+ choices=[
784
+ "Arabic",
785
+ "Bengali",
786
+ "English",
787
+ "French",
788
+ "German",
789
+ "Hindi",
790
+ "Italian",
791
+ "Japanese",
792
+ "Korean",
793
+ "Mandarin",
794
+ "Portuguese",
795
+ "Russian",
796
+ "Spanish",
797
+ "Turkish"
798
+ ],
799
+ value=config.get('language', 'English')
800
+ )
801
+
802
+ edit_description = gr.Textbox(
803
+ label="Description",
804
+ value=config.get('description', ''),
805
+ max_lines=2
806
+ )
807
+
808
+ edit_system_prompt = gr.Textbox(
809
+ label="System Prompt",
810
+ value=config.get('system_prompt', ''),
811
+ lines=5
812
+ )
813
+
814
+ with gr.Row():
815
+ edit_temperature = gr.Slider(
816
+ label="Temperature",
817
+ minimum=0,
818
+ maximum=2,
819
+ value=config.get('temperature', 0.7),
820
+ step=0.1
821
+ )
822
+ edit_max_tokens = gr.Slider(
823
+ label="Max Tokens",
824
+ minimum=50,
825
+ maximum=4096,
826
+ value=config.get('max_tokens', 750),
827
+ step=50
828
+ )
829
+
830
+ edit_examples = gr.Textbox(
831
+ label="Example Prompts (one per line)",
832
+ value='\n'.join(config.get('examples', [])),
833
+ lines=3
834
+ )
835
+
836
+ # URL Grounding
837
+ gr.Markdown("### URL Grounding")
838
+ edit_grounding_urls = gr.Textbox(
839
+ label="Grounding URLs (one per line)",
840
+ placeholder="https://example.com/docs\nhttps://example.com/api",
841
+ value='\n'.join(config.get('grounding_urls', [])),
842
+ lines=5,
843
+ info="First 2 URLs: Primary sources (8000 chars). URLs 3+: Secondary sources (2500 chars)."
844
+ )
845
+
846
+ with gr.Row():
847
+ edit_enable_dynamic_urls = gr.Checkbox(
848
+ label="Enable Dynamic URL Extraction",
849
+ value=config.get('enable_dynamic_urls', True),
850
+ info="Extract and fetch URLs from user messages"
851
+ )
852
+ edit_enable_file_upload = gr.Checkbox(
853
+ label="Enable File Upload",
854
+ value=config.get('enable_file_upload', True),
855
+ info="Allow users to upload files for context"
856
+ )
857
+
858
+ # Configuration actions
859
+ with gr.Row():
860
+ save_btn = gr.Button("πŸ’Ύ Save Configuration", variant="primary")
861
+ reset_btn = gr.Button("↩️ Reset to Defaults", variant="secondary")
862
+
863
+ config_status = gr.Markdown()
864
+
865
+ def save_configuration(name, description, system_prompt, model, language, temp, tokens, examples, grounding_urls, enable_dynamic_urls, enable_file_upload):
866
+ """Save updated configuration"""
867
+ try:
868
+ updated_config = config.copy()
869
+ updated_config.update({
870
+ 'name': name,
871
+ 'description': description,
872
+ 'system_prompt': system_prompt,
873
+ 'model': model,
874
+ 'language': language,
875
+ 'temperature': temp,
876
+ 'max_tokens': int(tokens),
877
+ 'examples': [ex.strip() for ex in examples.split('\n') if ex.strip()],
878
+ 'grounding_urls': [url.strip() for url in grounding_urls.split('\n') if url.strip()],
879
+ 'enable_dynamic_urls': enable_dynamic_urls,
880
+ 'enable_file_upload': enable_file_upload,
881
+ 'locked': config.get('locked', False)
882
+ })
883
+
884
+ if config_manager.save(updated_config):
885
+ # Auto-commit if HF token is available
886
+ if HF_TOKEN and SPACE_ID:
887
+ try:
888
+ from huggingface_hub import HfApi, CommitOperationAdd
889
+ api = HfApi(token=HF_TOKEN)
890
+
891
+ operations = [
892
+ CommitOperationAdd(
893
+ path_or_fileobj=config_manager.config_path,
894
+ path_in_repo="config.json"
895
+ )
896
+ ]
897
+
898
+ api.create_commit(
899
+ repo_id=SPACE_ID,
900
+ operations=operations,
901
+ commit_message="Update configuration via web UI",
902
+ commit_description=f"Configuration update at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
903
+ repo_type="space",
904
+ token=HF_TOKEN
905
+ )
906
+ return "βœ… Configuration saved and committed to repository!"
907
+ except Exception as e:
908
+ return f"βœ… Configuration saved locally. ⚠️ Auto-commit failed: {str(e)}"
909
+ else:
910
+ return "βœ… Configuration saved locally (no HF token for auto-commit)"
911
+ else:
912
+ return "❌ Failed to save configuration"
913
+
914
+ except Exception as e:
915
+ return f"❌ Error: {str(e)}"
916
+
917
+ save_btn.click(
918
+ save_configuration,
919
+ inputs=[edit_name, edit_description, edit_system_prompt, edit_model, edit_language,
920
+ edit_temperature, edit_max_tokens, edit_examples, edit_grounding_urls,
921
+ edit_enable_dynamic_urls, edit_enable_file_upload],
922
+ outputs=[config_status]
923
+ )
924
+
925
+ def reset_configuration():
926
+ """Reset to default configuration"""
927
+ try:
928
+ if config_manager.save(DEFAULT_CONFIG):
929
+ return (
930
+ DEFAULT_CONFIG['name'],
931
+ DEFAULT_CONFIG['description'],
932
+ DEFAULT_CONFIG['system_prompt'],
933
+ DEFAULT_CONFIG['model'],
934
+ DEFAULT_CONFIG.get('language', 'English'),
935
+ DEFAULT_CONFIG['temperature'],
936
+ DEFAULT_CONFIG['max_tokens'],
937
+ '\n'.join(DEFAULT_CONFIG['examples']),
938
+ '\n'.join(DEFAULT_CONFIG['grounding_urls']),
939
+ DEFAULT_CONFIG['enable_dynamic_urls'],
940
+ DEFAULT_CONFIG['enable_file_upload'],
941
+ "βœ… Reset to default configuration"
942
+ )
943
+ else:
944
+ return (*[gr.update() for _ in range(11)], "❌ Failed to reset")
945
+ except Exception as e:
946
+ return (*[gr.update() for _ in range(11)], f"❌ Error: {str(e)}")
947
+
948
+ reset_btn.click(
949
+ reset_configuration,
950
+ outputs=[edit_name, edit_description, edit_system_prompt, edit_model, edit_language,
951
+ edit_temperature, edit_max_tokens, edit_examples, edit_grounding_urls,
952
+ edit_enable_dynamic_urls, edit_enable_file_upload, config_status]
953
+ )
954
+
955
+ # Configuration tab authentication handler
956
+ def handle_config_auth(password):
957
+ """Handle configuration tab authentication"""
958
+ if not HF_TOKEN:
959
+ return (
960
+ gr.update(visible=True), # Keep auth panel visible
961
+ gr.update(visible=False), # Keep config panel hidden
962
+ gr.update(value="❌ No HF_TOKEN is set in Space secrets. Configuration cannot be enabled."),
963
+ False
964
+ )
965
+
966
+ if password == HF_TOKEN:
967
+ return (
968
+ gr.update(visible=False), # Hide auth panel
969
+ gr.update(visible=True), # Show config panel
970
+ gr.update(value="βœ… Authentication successful!"),
971
+ True
972
+ )
973
+ else:
974
+ return (
975
+ gr.update(visible=True), # Keep auth panel visible
976
+ gr.update(visible=False), # Keep config panel hidden
977
+ gr.update(value="❌ Invalid HF_TOKEN. Please try again."),
978
+ False
979
+ )
980
+
981
+ config_auth_btn.click(
982
+ handle_config_auth,
983
+ inputs=[config_password],
984
+ outputs=[config_auth_panel, config_panel, config_auth_status, config_authenticated]
985
+ )
986
+
987
+ config_password.submit(
988
+ handle_config_auth,
989
+ inputs=[config_password],
990
+ outputs=[config_auth_panel, config_panel, config_auth_status, config_authenticated]
991
+ )
992
+
993
+ # Access control handler
994
+ if ACCESS_CODE:
995
+ def handle_access(code, current_state):
996
+ if code == ACCESS_CODE:
997
+ return (
998
+ gr.update(visible=False), # Hide access panel
999
+ gr.update(visible=True), # Show main panel
1000
+ gr.update(value="βœ… Access granted!"), # Status message
1001
+ True # Update state
1002
+ )
1003
+ else:
1004
+ return (
1005
+ gr.update(visible=True), # Keep access panel visible
1006
+ gr.update(visible=False), # Keep main panel hidden
1007
+ gr.update(value="❌ Invalid access code. Please try again."), # Status message
1008
+ False # State remains false
1009
+ )
1010
+
1011
+ access_btn.click(
1012
+ handle_access,
1013
+ inputs=[access_input, access_granted],
1014
+ outputs=[access_panel, main_panel, access_status, access_granted]
1015
+ )
1016
+
1017
+ access_input.submit(
1018
+ handle_access,
1019
+ inputs=[access_input, access_granted],
1020
+ outputs=[access_panel, main_panel, access_status, access_granted]
1021
+ )
1022
+
1023
+ return demo
1024
+
1025
+
1026
+ # Create and launch the interface
1027
+ if __name__ == "__main__":
1028
+ demo = create_interface()
1029
+ demo.launch()
config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "41134114 Translator",
3
+ "tagline": "Writing History, Writing Literature",
4
+ "description": "A course assistant to help students think about the way history and literature unpack the past.",
5
+ "system_prompt": "You are a story-generator for Professor Martha Nadell's courses, \"Introduction to History and Literature\" and \"Theories of History and Literature\" at Brooklyn College in the fall of 2025. The purpose of the course is to reflect on how different types of sources, including general history, social history, urban history, fiction, first-person accounts, visual sources, and lived experience, helps us understand the past and the nature of particular places.\n \nThe stories should vary by genre, including non-fiction for a general audience, non-fiction social history, non-fiction urban history, realist fiction, modernist fiction, crime and detective novels, romance novels, the fiction of place, fiction that mixes multiple genres. The stories should be related to the subject of the course, the history and literature of Red Hook in Brooklyn in the twentieth and twenty-first centuries. The stories can be in the style of HP Lovecraft, Hubert Selby, Arthur Miller, Jonathan Lethem, and James McBride. \n \nResponse Guidelines\nWhen students enter a narrative, provide a response that changes the genre of the narrative. Ask students if they wish to change the audience for the response and what that audience would be. Then provide a new response to that request. Ask students what their purpose is. Provide a response that reflects that purpose.\n \nWhen students enter a series of facts or ideas, ask them to identify a genre for their response.\nWhen students enter a genre for their response, provide a response in that genre and ask them if they want to try a different genre. Ask students if they wish to change the audience for the response and what that audience would be. Then provide a new response to that request. Ask students what their purpose is. Provide a response that reflects that purpose.\n \nWhen students enter a new story, ask them what ideas or themes they want to emphasize. Provide a response that emphasizes those ideas and themes.\n \nYour follow-up questions should reflect the purpose of the course.\nAfter clarifying the genre, audience, and purpose, generate a response in the genre requested by the user, with the audience and purpose identified by the user. Then and always, ask the student to reflect on the affordances and constraints on each story, whether historical or fictional. DO NOT DO THE REFLECTION FOR THE STUDENTS. Ask them questions to encourage them to reflect, to engage in the exploration of the material co-generated.",
6
+ "model": "anthropic/claude-3.5-sonnet",
7
+ "language": "English",
8
+ "api_key_var": "API_KEY",
9
+ "temperature": 0.7,
10
+ "max_tokens": 400,
11
+ "examples": [
12
+ "Can you help me write a story about this moment in history?",
13
+ "Can you tell me about history, based on this short story?",
14
+ "Can you help me think about the differences and similarities between history and literature?",
15
+ "I'm confused about how to start writing historical fiction - where do I start?",
16
+ "I'm confused about how to start writing about history - where do I start?"
17
+ ],
18
+ "grounding_urls": [
19
+ "https://classics.mit.edu/Plato/phaedrus.1b.txt",
20
+ "https://plato.stanford.edu/entries/plato-rhetoric/#Pha",
21
+ "https://plato.stanford.edu/entries/plato-myths/",
22
+ "https://en.wikipedia.org/wiki/Socratic_method"
23
+ ],
24
+ "enable_dynamic_urls": true,
25
+ "enable_file_upload": true,
26
+ "theme": "Glass"
27
+ }
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