Spaces:
Running
on
Zero
Running
on
Zero
File size: 110,685 Bytes
f27460e 482bc30 94b8cb6 5609a56 756ea61 cb022bb f672e00 43647c4 f672e00 43647c4 f672e00 43647c4 f672e00 43647c4 f672e00 43647c4 f672e00 f27460e 482bc30 5609a56 482bc30 ed49cfb 482bc30 ed49cfb 482bc30 879ad5c 482bc30 a075dd7 56ffade 482bc30 879ad5c ed49cfb 0e03629 879ad5c a075dd7 482bc30 8eafcce 482bc30 8eafcce 482bc30 8eafcce 16eaa95 482bc30 5609a56 0e03629 5609a56 0e03629 5609a56 ad97da8 9cb6ce3 ad97da8 9cb6ce3 ad97da8 756ea61 ed49cfb 9cb6ce3 ed49cfb 9cb6ce3 ed49cfb 9cb6ce3 ed49cfb 9cb6ce3 756ea61 ad97da8 a4229ac 9cb6ce3 a4229ac 9cb6ce3 756ea61 9cb6ce3 e1c091b 9cb6ce3 a4229ac 9cb6ce3 ad97da8 756ea61 76fdd6c 756ea61 74a1a54 756ea61 5609a56 8eafcce 5609a56 482bc30 94b8cb6 482bc30 743b06e 94b8cb6 482bc30 743b06e 94b8cb6 743b06e 94b8cb6 482bc30 94b8cb6 743b06e 94b8cb6 482bc30 94b8cb6 743b06e 94b8cb6 743b06e 94b8cb6 743b06e 94b8cb6 482bc30 743b06e 94b8cb6 743b06e 94b8cb6 482bc30 94b8cb6 743b06e 94b8cb6 482bc30 94b8cb6 743b06e 94b8cb6 482bc30 94b8cb6 482bc30 94b8cb6 482bc30 94b8cb6 482bc30 94b8cb6 482bc30 94b8cb6 482bc30 94b8cb6 482bc30 94b8cb6 482bc30 94b8cb6 d9f8b8b 482bc30 94b8cb6 482bc30 d9f8b8b 482bc30 94b8cb6 482bc30 d9f8b8b 482bc30 756ea61 94b8cb6 cbac46a 984e889 cbac46a 6cfe6de cbac46a 94b8cb6 8937fd4 482bc30 cb022bb f27460e 2c366e0 f61b6ea a075dd7 8d48459 a075dd7 ad97da8 a075dd7 e578809 4dd165c 43647c4 3dc2230 f672e00 43647c4 f672e00 d1a28c0 3dc2230 fdeec3f b602b14 fdeec3f b602b14 fdeec3f d1a28c0 fdeec3f d1a28c0 3dc2230 9c26e86 43647c4 9c26e86 4dd165c 9c26e86 ca00fa5 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e ca00fa5 743b06e 142dcfb 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e 3e45414 743b06e b22d8dd 9c26e86 743b06e fdeec3f b602b14 9c26e86 b602b14 cb022bb b602b14 8937fd4 b602b14 cb022bb b602b14 0e03629 b602b14 2d211c9 b602b14 0e03629 b602b14 39f526c b602b14 f8bbf62 b602b14 4dd165c b602b14 43647c4 b602b14 4dd165c b602b14 743b06e b602b14 9c26e86 b602b14 43647c4 b602b14 4dd165c f672e00 43647c4 d1a28c0 3dc2230 43647c4 f672e00 fdeec3f 4dd165c f672e00 d1a28c0 b602b14 3dc2230 b602b14 fdeec3f 9c26e86 b602b14 d1a28c0 fdeec3f 3dc2230 d1a28c0 f672e00 b602b14 9c26e86 b602b14 9c26e86 d1a28c0 9c26e86 43647c4 d1a28c0 3dc2230 fdeec3f d1a28c0 9c26e86 b602b14 4dd165c d1a28c0 4dd165c b602b14 d1a28c0 b602b14 142dcfb b602b14 21ccdf9 142dcfb d1a28c0 142dcfb 9c26e86 29857f3 cb022bb b19b854 482bc30 9c26e86 b826437 4dd165c 9c26e86 73be982 c6fa314 b19b854 c6fa314 a075dd7 c6fa314 ad97da8 c6fa314 ad97da8 482bc30 b78075f b826437 09ce032 83e773c 09ce032 83e773c 0e03629 ec2dcdb 0e03629 f27460e f672e00 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 |
import gradio as gr
import random
import json
import re
import os
import shutil
from PIL import Image
import spaces
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
from threading import Thread
import time
import psutil
from sentence_transformers import SentenceTransformer
# # Initialize the zero tensor on CUDA
# zero = torch.Tensor([0]).cuda()
# print(zero.device) # This will print 'cpu' outside the @spaces.GPU decorated function
# # Load the model and tokenizer
# llmguide_model = AutoModelForCausalLM.from_pretrained(
# "Qwen/Qwen2-0.5B-Instruct",
# torch_dtype="auto",
# device_map="auto"
# )
# llmguide_tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
# @spaces.GPU
# def llmguide_generate_response(prompt, stream=False):
# print(zero.device) # This will print 'cuda:0' inside the @spaces.GPU decorated function
# messages = [
# {"role": "system", "content": "You are a helpful assistant."},
# {"role": "user", "content": prompt}
# ]
# text = llmguide_tokenizer.apply_chat_template(
# messages,
# tokenize=False,
# add_generation_prompt=True
# )
# model_inputs = llmguide_tokenizer([text], return_tensors="pt").to(zero.device)
# start_time = time.time()
# total_tokens = 0
# if stream:
# streamer = TextIteratorStreamer(llmguide_tokenizer, skip_special_tokens=True)
# generation_kwargs = dict(
# model_inputs,
# streamer=streamer,
# max_new_tokens=512,
# temperature=0.7,
# )
# thread = Thread(target=llmguide_model.generate, kwargs=generation_kwargs)
# thread.start()
# generated_text = ""
# for new_text in streamer:
# generated_text += new_text
# total_tokens += 1
# current_time = time.time()
# tokens_per_second = total_tokens / (current_time - start_time)
# yield generated_text, f"{tokens_per_second:.2f}"
# else:
# generated_ids = llmguide_model.generate(
# model_inputs.input_ids,
# max_new_tokens=512
# )
# generated_ids = [
# output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
# ]
# response = llmguide_tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
# total_tokens = len(generated_ids[0])
# end_time = time.time()
# tokens_per_second = total_tokens / (end_time - start_time)
# yield response, f"{tokens_per_second:.2f}"
# Initialize GPU tensor
zero = torch.Tensor([0]).cuda()
print(zero.device) # This will print 'cpu' outside the @spaces.GPU decorated function
# Load the embedding model
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
# Load the Qwen model and tokenizer
llmguide_model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen2-0.5B-Instruct",
torch_dtype="auto",
device_map="auto"
)
llmguide_tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B-Instruct")
# Sample knowledge base (replace with your own data)
knowledge_base = [
"The capital of France is Paris.",
"Python is a popular programming language.",
"Machine learning is a subset of artificial intelligence.",
"The Earth orbits around the Sun.",
]
# Create embeddings for the knowledge base
knowledge_base_embeddings = embedding_model.encode(knowledge_base)
def retrieve(query, k=2):
query_embedding = embedding_model.encode([query])
similarities = torch.nn.functional.cosine_similarity(torch.tensor(query_embedding), torch.tensor(knowledge_base_embeddings))
top_k_indices = similarities.argsort(descending=True)[:k]
return [knowledge_base[i] for i in top_k_indices]
def get_resource_usage():
ram_usage = psutil.virtual_memory().percent
gpu_memory_allocated = torch.cuda.memory_allocated() / (1024 ** 3) # Convert to GB
gpu_memory_reserved = torch.cuda.memory_reserved() / (1024 ** 3) # Convert to GB
return f"RAM Usage: {ram_usage:.2f}%, GPU Memory Allocated: {gpu_memory_allocated:.2f}GB, GPU Memory Reserved: {gpu_memory_reserved:.2f}GB"
@spaces.GPU
def llmguide_generate_response(prompt, stream=False):
print(zero.device) # This will print 'cuda:0' inside the @spaces.GPU decorated function
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
]
text = llmguide_tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True
)
model_inputs = llmguide_tokenizer([text], return_tensors="pt").to(zero.device)
start_time = time.time()
total_tokens = 0
if stream:
streamer = TextIteratorStreamer(llmguide_tokenizer, skip_special_tokens=True)
generation_kwargs = dict(
model_inputs,
streamer=streamer,
max_new_tokens=512,
temperature=0.7,
)
thread = Thread(target=llmguide_model.generate, kwargs=generation_kwargs)
thread.start()
generated_text = ""
for new_text in streamer:
generated_text += new_text
total_tokens += 1
current_time = time.time()
tokens_per_second = total_tokens / (current_time - start_time)
yield generated_text, f"{tokens_per_second:.2f}", ""
resource_usage = get_resource_usage()
yield generated_text, f"{tokens_per_second:.2f}", resource_usage
else:
generated_ids = llmguide_model.generate(
model_inputs.input_ids,
max_new_tokens=512
)
generated_ids = [
output_ids[len(input_ids):] for input_ids, output_ids in zip(model_inputs.input_ids, generated_ids)
]
response = llmguide_tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
total_tokens = len(generated_ids[0])
end_time = time.time()
tokens_per_second = total_tokens / (end_time - start_time)
resource_usage = get_resource_usage()
yield response, f"{tokens_per_second:.2f}", resource_usage
# Clear CUDA cache
# torch.cuda.empty_cache()
# gc.collect()
def rag(query, stream=False):
retrieved_docs = retrieve(query)
context = " ".join(retrieved_docs)
prompt = f"Context: {context}\nQuestion: {query}\nAnswer:"
return llmguide_generate_response(prompt, stream)
#--------------------------------------------------------------------------------------------------------------------------------
# Default configuration template
default_config = {
'background': '/AutoGameBackgrounds/1stGameLoc123.png',
'inventory': [],
'skills': [],
'objectives': [],
'targets': [],
'story': [],
'actions': {}
}
# Helper functions to dynamically add items
def add_inventory_item(inventory_items, type, name, description):
new_item = {"type": type, "name": name, "description": description}
inventory_items.append(new_item)
return inventory_items
def add_skill(skills_items, branch, name, learned):
new_skill = {"branch": branch, "name": name, "learned": learned == 'True'}
skills_items.append(new_skill)
return skills_items
def add_objective(objectives_items, id, name, complete):
new_objective = {"id": id, "name": name, "complete": complete == 'True'}
objectives_items.append(new_objective)
return objectives_items
def add_target(targets_items, name, x, y, collisionType, collisiontext):
new_target = {"name": name, "x": int(x), "y": int(y), "collisionType": collisionType, "collisiontext": collisiontext}
targets_items.append(new_target)
return targets_items
#-----------------------------------------------------------------------------------------------------------------------------------
# List of player engagement UI elements
player_engagement_items = [
"Health Bar", "Mana/Energy Bar", "Experience Bar", "Mini-Map", "Quest Tracker",
"Inventory Quick Access Slots", "Skill Cooldown Indicators", "Currency Display",
"Compass", "Timer/Clock", "Action Prompts", "Reticle/Crosshair", "Enemy Health Bars",
"Score Display", "Inventory Grid", "Item Tooltip", "Item Categories/Tabs",
"Equip/Unequip Buttons", "Item Sorting Options", "Character Stats Panel",
"Character Model Viewer", "Quick Equip Slots", "Dialogue Box", "Dialogue Choices",
"Character Portraits", "Character Name Display", "Subtitle Text", "World Map",
"Local Map", "Fast Travel Points", "Map Markers", "Map Legend", "Crafting Recipe List",
"Ingredient Slots", "Craft Button", "Crafting Progress Bar", "Skill Nodes",
"Skill Descriptions", "Skill Point Counter", "Unlock Button", "Skill Path Highlight",
"Quest List", "Quest Details Panel", "Quest Objectives", "Quest Rewards",
"Quest Status Indicators", "Chat Box", "Player List", "Voice Chat Indicators",
"Ping/Latency Indicator", "Party/Team UI", "Scoreboard", "Matchmaking Screen",
"Pop-up Notifications", "Achievement Unlocks", "System Messages",
"On-screen Key Prompts", "Environmental Interaction Icons", "Save/Auto-Save Indicators",
"Credits Screen"
]
# List of character-based story events
story_events = [
'exploreLocation', 'discoverClue', 'meetCharacter', 'solveRiddle', 'findItem',
'faceChallenge', 'makeDecision', 'engageBattle', 'unlockAbility', 'learnSecret',
'completeMission', 'experienceSetback', 'earnReward', 'uncoverMystery', 'formAlliance',
'faceBetrayal', 'confrontNemesis', 'makeDiscovery', 'overcomeLoss', 'achieveVictory'
]
def pick_random_items(items, n):
return random.sample(items, n)
def generate_timeline(events, label):
timeline = []
for event in events:
timeline.append((random.randint(1, 100), label, event))
return timeline
def create_story(timeline):
story = []
for entry in timeline:
if entry[1] == "Story":
story.append(f"The hero {entry[2].replace('engageBattle', 'engaged in a fierce battle').replace('solveRiddle', 'solved a complex riddle').replace('exploreLocation', 'explored a mysterious location')}.")
else:
story.append(f"The player interacted with {entry[2]}.")
return " ".join(story)
def generate_story_and_timeline(no_ui_timeline_points=10, no_media_timeline_points=5, include_media=True):
# Pick 10 random UI items
random_ui_items = pick_random_items(player_engagement_items, no_ui_timeline_points)
# Generate UI and story timelines
ui_timeline = generate_timeline(random_ui_items, "UI")
story_timeline = generate_timeline(story_events, "Story")
# Initialize merged timeline with UI and story timelines
merged_timeline = ui_timeline + story_timeline
no_media_merged_timeline = ui_timeline + story_timeline
#print(merged_timeline)
#print(no_media_merged_timeline)
# Include media-related items if specified
if include_media:
media_files = generate_media_file_list(no_media_timeline_points)
#rendered_media = render_media_with_dropdowns(media_files)
media_timeline = generate_timeline(media_files, "Media")
merged_timeline += media_timeline
print(merged_timeline)
# Sort the merged timeline based on the random numbers
merged_timeline.sort(key=lambda x: x[0])
no_media_merged_timeline.sort(key=lambda x: x[0])
# Create the story
story = create_story(merged_timeline)
# Format the timeline for display
formatted_timeline = "\n".join([f"{entry[0]}: {entry[1]} - {entry[2]}" for entry in merged_timeline])
no_media_formatted_timeline = "\n".join([f"{entry[0]}: {entry[1]} - {entry[2]}" for entry in no_media_merged_timeline])
game_structure_with_media, game_structure_without_media = generate_game_structures(formatted_timeline, no_media_formatted_timeline)
return formatted_timeline, no_media_formatted_timeline, story, json.dumps(game_structure_with_media, indent=2), json.dumps(game_structure_without_media, indent=2) #, game_structure_with_media
media_file_types = ["image", "video", "audio"]
def generate_media_file_list(n):
return [random.choice(media_file_types) for _ in range(n)]
def show_elements(text):
# Parse the input text
pattern = r'(\d+): (UI|Story|Media) - (.+)'
blocks = re.findall(pattern, text)
# Sort blocks by their timestamp
blocks.sort(key=lambda x: int(x[0]))
outputs = []
for timestamp, block_type, content in blocks:
if block_type == 'UI':
# Create HTML for UI elements
ui_html = f'<div class="ui-element">{content}</div>'
outputs.append(gr.HTML(ui_html))
elif block_type == 'Story':
# Display story elements as Markdown
outputs.append(gr.Markdown(f"**{content}**"))
elif block_type == 'Media':
if content.lower() == 'audio':
# Placeholder for audio element
outputs.append(gr.Audio(label=f"Audio at {timestamp} in the order"))
elif content.lower() == 'video':
# Placeholder for video element
outputs.append(gr.Video(label=f"Video at {timestamp} in the order"))
elif content.lower() == 'image':
# Placeholder for image element
outputs.append(gr.Image(label=f"Image at {timestamp} in the order"))
return outputs
def show_elements_json_input(json_input):
data = json.loads(json_input)
masterlocation1 = data['masterlocation1']
outputs = []
for location, details in masterlocation1.items():
if location == 'end':
continue
with gr.Accordion(f"Location: {location} - Previous description {details['description']}", open=False):
description = gr.Textbox(label="Description", value=details['description'], interactive=True)
outputs.append(description)
events = gr.Textbox(label="Events", value=json.dumps(details['events']), interactive=True)
outputs.append(events)
choices = gr.Textbox(label="Choices", value=json.dumps(details['choices']), interactive=True)
outputs.append(choices)
transitions = gr.Textbox(label="Transitions", value=json.dumps(details['transitions']), interactive=True)
outputs.append(transitions)
# New media field
media = gr.Textbox(label="Media", value=json.dumps(details.get('media', [])), interactive=True)
outputs.append(media)
def update_json(*current_values):
updated_data = {"masterlocation1": {}}
locations = [loc for loc in masterlocation1.keys() if loc != 'end']
for i, location in enumerate(locations):
updated_data["masterlocation1"][location] = {
"description": current_values[i*5],
"events": json.loads(current_values[i*5 + 1]),
"choices": json.loads(current_values[i*5 + 2]),
"transitions": json.loads(current_values[i*5 + 3]),
"media": json.loads(current_values[i*5 + 4]) # New media field
}
updated_data["masterlocation1"]["end"] = masterlocation1["end"]
return json.dumps(updated_data, indent=2)
update_button = gr.Button("Update JSON")
json_output = gr.Textbox(label="Updated JSON", lines=10)
update_button.click(update_json, inputs=outputs, outputs=json_output)
return outputs + [update_button, json_output]
def create_media_component(file_path):
print(file_path)
_, extension = os.path.splitext(file_path)
extension = extension.lower()[1:] # Remove the dot and convert to lowercase
if extension in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
return gr.Image(value=file_path, label="Image Input")
elif extension in ['mp4', 'avi', 'mov']:
return gr.Video(value=file_path, label="Video Input")
elif extension in ['mp3', 'wav', 'ogg']:
return gr.Audio(value=file_path, label="Audio Input")
else:
return gr.Textbox(value=file_path, label=f"File: {os.path.basename(file_path)}")
def convert_timeline_to_game_structure(timeline):
lines = timeline.split('\n')
game_structure = {}
current_location = 0
sub_location = 0
for i, line in enumerate(lines):
if line.strip() == "":
continue
if line[0].isdigit(): # New location starts
current_location += 1
sub_location = 0
location_key = f"location{current_location}"
game_structure[location_key] = {
"description": "",
"events": [],
"choices": ["continue"],
"transitions": {}
}
else: # Continue with sub-locations or media entries
sub_location += 1
location_key = f"location{current_location}_{sub_location}"
# Extract the event description
parts = line.split(': ', 1)
if len(parts) == 2:
prefix, rest = parts
event_parts = rest.split(' - ', 1)
if len(event_parts) == 2:
event_type, event_description = event_parts
else:
event_type, event_description = "Unknown", rest
else:
event_type, event_description = "Unknown", line
description = rest.strip() if event_type in ["Media", "UI"] else f"{event_type}: {event_description}"
if sub_location == 0:
game_structure[f"location{current_location}"]["description"] = description
else:
game_structure[f"location{current_location}"]["events"].append({
"description": description,
"type": event_type
})
# Set the transition to the next location or to the end
if i < len(lines) - 1:
next_line = lines[i + 1].strip()
if next_line and next_line[0].isdigit(): # New location starts
game_structure[f"location{current_location}"]["transitions"]["continue"] = f"masterlocation1_location{current_location + 1}"
else:
#game_structure[f"location{current_location}"]["transitions"]["continue"] = f"location_{current_location}_{sub_location + 1}"
game_structure[f"location{current_location}"]["transitions"]["continue"] = "end"
else:
game_structure[f"location{current_location}"]["transitions"]["continue"] = "end"
# Add an end location
game_structure["end"] = {
"description": "The adventure ends here.",
# "choices": [],
# "transitions": {}
"choices": ["restart"],
"transitions": {"restart": "location1"} # Assuming location_1 is the start
}
# Wrap the game structure in master_location1
wrapped_structure = {"masterlocation1": game_structure}
return wrapped_structure
def generate_game_structures(timeline_with_media, timeline_without_media):
game_structure_with_media = convert_timeline_to_game_structure(timeline_with_media)
game_structure_without_media = convert_timeline_to_game_structure(timeline_without_media)
return game_structure_with_media, game_structure_without_media
#-----------------------------------------------------------------------------------------------------------------------------------
class Player:
def __init__(self):
self.inventory = []
self.money = 20
self.knowledge = {}
def add_item(self, item):
self.inventory.append(item)
def has_item(self, item):
return item in self.inventory
def update_knowledge(self, topic):
self.knowledge[topic] = True
# Define the states
all_states = {
'village': {
'start': {
"description": "You wake up in a small village. You hear a rumor about a lost treasure.",
"choices": ['explore village', 'gather supplies', 'rest'],
"transitions": {'explore village': 'village_rumor', 'gather supplies': 'village_supplies', 'rest': 'village_start'},
"consequences": {
'gather supplies': lambda player: player.add_item('basic supplies')
},
"media": []
},
'rumor': {
"description": "You hear more details about the treasure hidden in the ancient ruins nearby.",
"choices": ['decide to go', 'ignore'],
"transitions": {'decide to go': 'village_supplies', 'ignore': 'village_start'},
"consequences": {
'decide to go': lambda player: player.update_knowledge('treasure location')
},
"media": []
},
'supplies': {
"description": "You gather supplies for your journey.",
"choices": ['head to forest', 'stay in village'],
"transitions": {'head to forest': 'forest_forest', 'stay in village': 'village_start'},
"media": []
},
},
'forest': {
'forest': {
"description": "You enter the dense forest, heading towards the ruins.",
"choices": ['travel further', 'return to village'],
"transitions": {'travel further': 'ruins_ruins', 'return to village': 'village_start'},
"media": []
},
},
'ruins': {
'ruins': {
"description": "You reach the ancient ruins. The entrance is dark and eerie.",
"choices": ['enter ruins', 'return to forest'],
"transitions": {'enter ruins': 'ruins_explore', 'return to forest': 'forest_forest'},
"media": []
},
'explore': {
"description": "You explore the ruins, encountering traps and puzzles.",
"choices": ['solve puzzle', 'avoid traps'],
"transitions": {'solve puzzle': 'ruins_hiddenPassage', 'avoid traps': 'ruins_ruins'},
"media": []
},
'hiddenPassage': {
"description": "You solve a challenging puzzle and unlock a hidden passage.",
"choices": ['enter passage', 'go back'],
"transitions": {'enter passage': 'ruins_treasureRoom', 'go back': 'ruins_explore'},
"media": []
},
'treasureRoom': {
"description": "You enter the treasure room and find the treasure chest.",
"choices": ['take treasure', 'leave'],
"transitions": {'take treasure': 'ruins_celebrate', 'leave': 'ruins_ruins'},
"consequences": {
'take treasure': lambda player: player.add_item('treasure')
},
"media": []
},
'celebrate': {
"description": "You celebrate your discovery and decide to bring the treasure back to the village.",
"choices": ['return to village'],
"transitions": {'return to village': 'village_return'},
"media": []
},
},
'village_return': {
'village_return': {
"description": "You return to the village with the treasure and share it with the villagers.",
"choices": ['end adventure'],
"transitions": {'end adventure': 'end_end'},
"media": []
},
},
'end': {
'end': {
"description": "Your adventure ends here. The villagers are grateful and everyone's lives improve.",
"choices": [],
"transitions": {},
"media": []
},
}
}
def validate_transitions(all_states):
errors = []
for location, states in all_states.items():
for state_key, state in states.items():
for transition_key, transition_state in state['transitions'].items():
# Check if the transition is to another location
if transition_state in all_states:
trans_location, trans_state = transition_state, 'start' # Assuming 'start' state for new locations
elif '_' in transition_state:
trans_location, trans_state = transition_state.split('_')
else:
trans_location, trans_state = location, transition_state
# Validate the transition state
if trans_location not in all_states or trans_state not in all_states[trans_location]:
errors.append(f"Invalid transition from {location}.{state_key} to {trans_location}.{trans_state}")
return errors
path_errors = validate_transitions(all_states)
if path_errors:
for error in path_errors:
print(error)
else:
print("All transitions are valid.")
class GameSession:
def __init__(self, starting_location='village', starting_state='start'):
self.player = Player()
self.current_location = starting_location
self.current_state = starting_state
self.game_log = []
def make_choice(self, choice_index):
state = all_states[self.current_location][self.current_state]
if 0 <= choice_index < len(state['choices']):
choice = state['choices'][choice_index]
next_state = state['transitions'][choice]
self.game_log.append(f"You chose: {choice}")
self.game_log.append(state['description'])
if 'consequences' in state and choice in state['consequences']:
if state['consequences'][choice]:
state['consequences'][choice](self.player)
else:
# Handle empty consequence, e.g., log a message or provide a default action
print(f"No consequence for choice: {choice}")
# You can add any default action here if needed
if '_' in next_state:
self.current_location, self.current_state = next_state.split('_')
else:
self.current_state = next_state
return self.get_current_state_info()
else:
return "Invalid choice. Please try again."
def get_current_state_info(self):
state = all_states[self.current_location][self.current_state]
choices = [f"{idx + 1}. {choice}" for idx, choice in enumerate(state['choices'])]
return state['description'], choices, "\n".join(self.game_log)
def get_current_state_media(self):
media = all_states[self.current_location][self.current_state]['media']
return media
def start_game(starting_location='village', starting_state='start'):
game_session = GameSession(starting_location, starting_state)
description, choices, game_log = game_session.get_current_state_info()
return description, choices, game_log, game_session
def make_choice(choice, game_session, with_media=False): #Calls the nested make choice function in the game session class
if not choice:
description, choices, game_log = game_session.get_current_state_info()
return description, choices, "Please select a choice before proceeding.", game_session
choice_index = int(choice.split('.')[0]) - 1
result = game_session.make_choice(choice_index)
if with_media:
media = game_session.get_current_state_media()
return result[0], gr.update(choices=result[1]), result[2], game_session, media
else:
return result[0], gr.update(choices=result[1]), result[2], game_session
def load_game(custom_config=None, with_media=False):
global all_states
if not custom_config:
return gr.update(value="No custom configuration provided."), None, None, None, None, None, None
try:
new_config = json.loads(custom_config)
all_states = new_config
# Determine the starting location and state
starting_location = next(iter(all_states.keys()))
starting_state = next(iter(all_states[starting_location].keys()))
print(f"Starting location: {starting_location}, Starting state: {starting_state}")
game_session = GameSession(starting_location, starting_state)
description, choices, game_log = game_session.get_current_state_info()
new_path_errors = validate_transitions(all_states)
output_media = []
if with_media:
media_list = all_states[starting_location][starting_state].get('media', [])
print(f"Media list: {media_list}")
if media_list:
for media_path in media_list:
#media_component = create_media_component(media_path)
output_media.append(media_path)
print(f"Created {len(output_media)} media components")
success_message = f"Custom configuration loaded successfully!\n{new_path_errors}"
return (
gr.update(value=success_message),
game_log,
description,
gr.update(choices=choices),
gr.update(value=custom_config),
game_session,
output_media if with_media else None
)
except json.JSONDecodeError as e:
error_message = format_json_error(custom_config, e)
return gr.update(value=error_message), None, None, None, None, gr.update(value=custom_config), None
except Exception as e:
error_message = f"Error loading custom configuration: {str(e)}"
return gr.update(value=error_message), None, None, None, None, gr.update(value=custom_config), None
def format_json_error(config, error):
lineno, colno = error.lineno, error.colno
lines = config.split('\n')
error_line = lines[lineno - 1] if lineno <= len(lines) else ""
pointer = ' ' * (colno - 1) + '^'
return f"""Invalid JSON format in custom configuration:
Error at line {lineno}, column {colno}:
{error_line}
{pointer}
Error details: {str(error)}"""
def display_website(link):
html = f"<iframe src='{link}' width='100%' height='1000px'></iframe>"
gr.Info("If 404 then the space/page has probably been disabled - normally due to a better alternative")
return html
initgameinfo = start_game()
#-----------------------------------------------------------------------------------------------------------------------------------
# Set the directory where files will be saved
SAVE_DIR = os.path.abspath("saved_media")
# Ensure the save directory exists
os.makedirs(SAVE_DIR, exist_ok=True)
# Define supported file extensions
SUPPORTED_EXTENSIONS = {
"image": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"],
"audio": [".mp3", ".wav", ".ogg"],
"video": [".mp4", ".avi", ".mov", ".webm"]
}
def save_file(file):
if file is None:
return "No file uploaded.", gr.update()
try:
# Get the original filename and extension
original_filename = os.path.basename(file.name)
_, extension = os.path.splitext(original_filename)
# Check if the file extension is supported
if not any(extension.lower() in exts for exts in SUPPORTED_EXTENSIONS.values()):
return f"Unsupported file type: {extension}", gr.update()
# Create a unique filename to avoid overwriting
base_name = os.path.splitext(original_filename)[0]
counter = 1
new_filename = f"{base_name}{extension}"
while os.path.exists(os.path.join(SAVE_DIR, new_filename)):
new_filename = f"{base_name}_{counter}{extension}"
counter += 1
# Copy the file from the temporary location to our save directory
dest_path = os.path.join(SAVE_DIR, new_filename)
shutil.copy2(file.name, dest_path)
# Return success message and updated FileExplorer
return f"File saved as {new_filename} in {SAVE_DIR}", gr.update(value=SAVE_DIR), gr.update(value=None)
except Exception as e:
return f"Error saving file: {str(e)}", gr.update(value=SAVE_DIR), gr.update()
def view_file(file_path):
if not file_path:
return None, None, None, "No file selected."
try:
full_path = os.path.join(SAVE_DIR, file_path)
_, extension = os.path.splitext(full_path)
extension = extension.lower()
if extension in SUPPORTED_EXTENSIONS["image"]:
return Image.open(full_path), None, None, None
elif extension in SUPPORTED_EXTENSIONS["audio"]:
return None, full_path, None, None
elif extension in SUPPORTED_EXTENSIONS["video"]:
return None, None, full_path, None
else:
return None, None, None, f"Unsupported file type: {extension}"
except Exception as e:
return None, None, None, f"Error viewing file: {str(e)}"
def refresh_file_explorer():
return gr.update()
#-----------------------------------------------------------------------------------------------------------------------------------
with gr.Blocks() as demo:
gr.HTML("""<div style="width: 100%; text-align: center">Main ideas for this space is (June 2024) (Custom component planning?):</div>
<div style="display: flex; justify-content: center; margin-bottom: 20px; align-items: center;">
<div style="width: 20%; text-align: center">We can generate almost any media data and more </div>
<div style="width: 20%; text-align: center">A program exist around data </div>
<div style="width: 20%; text-align: center">Time moves in a straight so all considerations are flattend by the nature of time </div>
<div style="width: 20%; text-align: center">llms good at short questions </div>
<div style="width: 20%; text-align: center">HF + Gradio allows for api use so this my prototype tool for tool use test</div>
</div>""")
with gr.Accordion("Qwen 0.5B as Space Guide Tests", open=False):
gr.HTML("Placeholder for FAQ type - front end as prompt engineering for the first message to force direction of conversion")
gr.HTML("Placeholder for weak RAG Type - Explanations through an opensource embeddings engine")
gr.Interface(
fn=rag,
inputs=[
gr.Textbox(lines=2, placeholder="Enter your question here..."),
gr.Checkbox(label="Stream output")
],
outputs=[
gr.Textbox(label="Generated Response"),
gr.Textbox(label="Tokens per second"),
gr.Textbox(label="Resource Usage")
],
title="RAG Q&A System with GPU Acceleration and Resource Monitoring",
description="Ask a question and get an answer based on the retrieved context. The response is generated using a GPU-accelerated model. Resource usage is logged at the end of generation."
)
("Placeholder for https://huggingface.co/h2oai/h2o-danube3-500m-chat-GGUF as alternative")
("Placeholder for qwen 2 72b as alternative use checkbox and gradio client api call")
gr.Markdown("# Qwen-0.5B-Instruct Language Model")
gr.Markdown("This demo uses the Qwen-0.5B-Instruct model to generate responses based on your input.")
gr.HTML("Example prompts: <br>I am writing a story about a chef. please write dishes to appear on the menu. <br>What are the most common decisions that a chef story would include? <br>What are the kinds problems that a chef story would include? <br>What are the kinds of out of reach goals that a chef story would include? <br>Continue this config - Paste any complete block of the config")
with gr.Row():
with gr.Column():
llmguide_prompt = gr.Textbox(lines=2, placeholder="Enter your prompt here...")
llmguide_stream_checkbox = gr.Checkbox(label="Enable streaming")
llmguide_submit_button = gr.Button("Generate")
with gr.Column():
llmguide_output = gr.Textbox(lines=10, label="Generated Response")
llmguide_tokens_per_second = gr.Textbox(label="Tokens per Second")
llmguide_submit_button.click(
llmguide_generate_response,
inputs=[llmguide_prompt, llmguide_stream_checkbox],
outputs=[llmguide_output, llmguide_tokens_per_second],
)
Frontendpromptengforguide = """Suggest descriptions for media to fill the empty media fields -
{
"village": {
"start": {
"description": "You wake up in a small village. You hear a rumor about a lost treasure.",
"choices": [
"explore village",
"gather supplies",
"rest"
],
"transitions": {
"explore village": "village_rumor",
"gather supplies": "village_supplies",
"rest": "village_start"
},
"consequences": {
"gather supplies": {}
},
"media": []
},
"rumor": {
"description": "You hear more details about the treasure hidden in the ancient ruins nearby.",
"choices": [
"decide to go",
"ignore"
],
"transitions": {
"decide to go": "village_supplies",
"ignore": "village_start"
},
"consequences": {
"decide to go": {}
},
"media": []
},
"supplies": {
"description": "You gather supplies for your journey.",
"choices": [
"head to forest",
"stay in village"
],
"transitions": {
"head to forest": "forest_forest",
"stay in village": "village_start"
},
"media": []
}
},
"forest": {
"forest": {
"description": "You enter the dense forest, heading towards the ruins.",
"choices": [
"travel further",
"return to village"
],
"transitions": {
"travel further": "ruins_ruins",
"return to village": "village_start"
},
"media": []
}
},
"ruins": {
"ruins": {
"description": "You reach the ancient ruins. The entrance is dark and eerie.",
"choices": [
"enter ruins",
"return to forest"
],
"transitions": {
"enter ruins": "ruins_explore",
"return to forest": "forest_forest"
},
"media": []
},
"explore": {
"description": "You explore the ruins, encountering traps and puzzles.",
"choices": [
"solve puzzle",
"avoid traps"
],
"transitions": {
"solve puzzle": "ruins_hiddenPassage",
"avoid traps": "ruins_ruins"
},
"media": []
},
"hiddenPassage": {
"description": "You solve a challenging puzzle and unlock a hidden passage.",
"choices": [
"enter passage",
"go back"
],
"transitions": {
"enter passage": "ruins_treasureRoom",
"go back": "ruins_explore"
},
"media": []
},
"treasureRoom": {
"description": "You enter the treasure room and find the treasure chest.",
"choices": [
"take treasure",
"leave"
],
"transitions": {
"take treasure": "ruins_celebrate",
"leave": "ruins_ruins"
},
"consequences": {
"take treasure": {}
},
"media": []
},
"celebrate": {
"description": "You celebrate your discovery and decide to bring the treasure back to the village.",
"choices": [
"return to village"
],
"transitions": {
"return to village": "village_return"
},
"media": []
}
},
"village_return": {
"village_return": {
"description": "You return to the village with the treasure and share it with the villagers.",
"choices": [
"end adventure"
],
"transitions": {
"end adventure": "end_end"
},
"media": []
}
},
"end": {
"end": {
"description": "Your adventure ends here. The villagers are grateful and everyone's lives improve.",
"choices": [],
"transitions": {},
"media": []
}
}
}
"""
with gr.Accordion("Decisions Creation to Story to Config Conversation", open=False):
with gr.Tab("Timeline Guide for Config Generation or evelution"):
with gr.Accordion("Empty Config shape for explaining to LLM", open=False):
gr.HTML(f"placeholder for current empty JSON config shape")
gr.HTML("Structural indicators of quality of config")
with gr.Tabs("Config Specific"):
gr.HTML("Timeline for making Timelines?")
gr.HTML("Componets (outside Code Support for Config): Decisions (and context explanation), Nested Sections, Media (Especially to affect decisions), Replayability (GTA and Tekken type mechanics in text form), Theme integration (Modified Varibles that affect UI or config order)")
gr.HTML("From Nothing <br>")
gr.HTML("From Existing <br>")
with gr.Tabs("Existing Game Analysis"):
gr.HTML("Existing Games eg. GTA Heists - Same Map with overlapping branching narratives, Battlefront - Elites amongst Commoners, Tekken Casino (one mistake = 1/2 or 1/3 of your Resources) and Turn based: 'Tactics' type nintendo games, Chess (and any other tile based game) ")
gr.HTML("Existing Game Rules for text - Cyberpunk RED, ")
with gr.Tabs("Multiplayer options"):
gr.HTML("Community playthrough = Tally of players choices, Random item placed in a random location - first person to get it wins, Survival by location or characters met")
with gr.Tab("Some Workflow Helpers (Removed as built into Semi-Auto)"):
gr.HTML("Song / Random Scenario to 'full game' manual or auto is end goal ")
gr.HTML("Main Priority is to make rails for the story to work on as a simplified view of a game is a linear path with loops (gameplay mechanics) <br> Below = Manual Edit (At bottom you can save the changes and copy it to test) <br>For LLM edit copy either the Timeline")
gr.HTML("The problem is the assets generation isnt free and using spaces as api also clogs them (no way to know when ZeroGPUs are at lowest usage) so using iFrame is better for now <br> So worklfow -- Make Skeleton -- Use Iframe to get media -- then ask for details / story / gameplay loop ideas and add back to config")
with gr.Tab("Schema First"):
gr.HTML("Some Kinds of game skeletons ideas - Timelines, Graph as State machine paths, Economy ecosystem")
gr.HTML("One prompt to be used to test models - <br>Please make 10 python lists for the types of media files and their purposes in a game and then use those lists to random generate a timeline of 20 items when the function is called <br>Great next suggest ways to improve this function to create better timelines")
with gr.Accordion("Test for config to gradio components order - ignore for now", open=False ):
gr.Markdown("Asset Generation")
gr.HTML("Splits by new line - The idea here was to allow for saving the file ")
input_text = gr.Textbox(label="Input Text", lines=10)
output_group = gr.Group()
@gr.render(inputs=input_text)
def update(text):
return show_elements(text)
with gr.Accordion("Proto Config Assist"):
with gr.Accordion("Can copy in the Test Example State Machine tab - only linear path for now", open=False):
gr.Markdown("# Story and Timeline Generator")
gr.Markdown("Click the button to generate a random timeline and story based on UI elements and story events. <br>Ask an LLM to use this to write a story around")
with gr.Row():
game_structure_output_text_with_media = gr.Code(language="json")
game_structure_output_text = gr.Code(language="json")
with gr.Accordion("JSON with no edits"):
with gr.Row():
timeline_output_with_assets = gr.Textbox(label="Timeline with Assets Considered", lines=20)
timeline_output = gr.Textbox(label="Timeline (Order might be different for now)", lines=20)
story_output = gr.Textbox(label="Generated Story (Order might be different for now)", lines=20)
with gr.Row():
generate_no_ui_timeline_points = gr.Slider(minimum=1, value=10, step=1, maximum=30, label="Choose the amount of ui timeline points")
generate_no_media_timeline_points = gr.Slider(minimum=1, value=5, step=1, maximum=30, label="Choose the amount of media timeline points")
generate_with_media_check = gr.Checkbox(label="Generate with media", value=True)
generate_button = gr.Button("Generate Story and Timeline")
@gr.render(inputs=game_structure_output_text_with_media)
def update(game_structure_output_text_with_media):
return show_elements_json_input(game_structure_output_text_with_media)
generate_button.click(generate_story_and_timeline, inputs=[generate_no_ui_timeline_points, generate_no_media_timeline_points, generate_with_media_check], outputs=[timeline_output_with_assets, timeline_output, story_output, game_structure_output_text_with_media, game_structure_output_text])
with gr.Tab("Asset First"):
gr.HTML("Make Asset and make the transitions using LLM")
with gr.Tab("Export Options"):
gr.HTML("Placeholder - My Custom JS, Playcanvas, Unreal Engine")
with gr.Tab("Config Writing Considerations"):
gr.HTML("Player Stats, Inventory and NPCS not implemented yet, so traversal type games best aka graph like structures <br> Game is like a universal translator so any concept can be covered")
with gr.Accordion("Existing Config Crafting Progression - click to open", open=False):
with gr.Tab("Quick Ways to evaluate current config"):
gr.HTML("Ask SOTA LLMs This prompt: <br> This config is for a basic text based game engine. I dont have any structural metrics to assess the quality of the config. What JSON things can we look at to see if it may be too bland for a person testing the game? <br> Then Paste the Config with the prompt")
gr.HTML("""Original Claude 3.5 Sonnet Response snippets: <br>
Limited state variety: With only 13 states across 5 locations, the game might feel short and lacking in diversity. Consider adding more locations or states within existing locations.
Low average choices: An average of 1.92 choices per state might make the game feel linear. Increasing the number of choices in more states could improve player engagement.
Limited consequences: Only 3 states have consequences, which might make player choices feel less impactful. Adding more consequences could increase the sense of agency.
Short descriptions: The average description length of 13.15 words might not provide enough detail to immerse players. Consider expanding descriptions to create a richer narrative.
Lack of media: No states currently use media elements, which could make the game feel less engaging. Adding images, sound effects, or other media could enhance the player experience.
Limited narrative branching: While there are some loops and choices, the overall structure is relatively linear. Adding more branching paths could increase replayability and player interest.
To make the game less bland, consider:
Adding more states and locations
Increasing the number of choices in each state
Implementing more consequences for player actions
Expanding descriptions to create a richer narrative
Incorporating media elements
Creating more diverse paths through the game""")
with gr.Tab("Main areas of considerations"):
with gr.Tab("Mermaid Graphs and Nesting"):
gr.HTML("Claude Artifacts to illustrate nested structure brainstorms - <br> https://claude.site/artifacts/4a910d81-1541-49f4-8531-4f27fe56cd1e <br> https://claude.site/artifacts/265e9242-2093-46e1-9011-ed6ad938be90?fullscreen=false <br> ")
gr.HTML("")
with gr.Tab(""):
gr.HTML("")
with gr.Tab("Structural Inspirations"):
gr.HTML("GTA Heists - Replayability and stakes, Tekken - 2/3 mistakes = lost round ")
gr.HTML("Sports Scores, ")
with gr.Tab("Themes"):
gr.HTML("")
originalconfigatbeinningofthisspace = """{
"village": {
"start": {
"description": "You wake up in a small village. You hear a rumor about a lost treasure.",
"choices": ['explore village', 'gather supplies', 'rest'],
"transitions": {'explore village': 'village_rumor', 'gather supplies': 'village_supplies', 'rest': 'village_start'},
"consequences": {
'gather supplies': lambda player: player.add_item('basic supplies')
},
"media": []
},
"rumor": {
"description": "You hear more details about the treasure hidden in the ancient ruins nearby.",
"choices": ['decide to go', 'ignore'],
"transitions": {'decide to go': 'village_supplies', 'ignore': 'village_start'},
"consequences": {
'decide to go': lambda player: player.update_knowledge('treasure location')
},
"media": []
},
"supplies": {
"description": "You gather supplies for your journey.",
"choices": ['head to forest', 'stay in village'],
"transitions": {'head to forest': 'forest_forest', 'stay in village': 'village_start'},
"media": []
},
},
"forest": {
"forest": {
"description": "You enter the dense forest, heading towards the ruins.",
"choices": ['travel further', 'return to village'],
"transitions": {'travel further': 'ruins_ruins', 'return to village': 'village_start'},
"media": []
},
},
"ruins": {
"ruins": {
"description": "You reach the ancient ruins. The entrance is dark and eerie.",
"choices": ['enter ruins', 'return to forest'],
"transitions": {'enter ruins': 'ruins_explore', 'return to forest': 'forest_forest'},
"media": []
},
"explore": {
"description": "You explore the ruins, encountering traps and puzzles.",
"choices": ['solve puzzle', 'avoid traps'],
"transitions": {'solve puzzle': 'ruins_hiddenPassage', 'avoid traps': 'ruins_ruins'},
"media": []
},
"hiddenPassage": {
"description": "You solve a challenging puzzle and unlock a hidden passage.",
"choices": ['enter passage', 'go back'],
"transitions": {'enter passage': 'ruins_treasureRoom', 'go back': 'ruins_explore'},
"media": []
},
"treasureRoom": {
"description": "You enter the treasure room and find the treasure chest.",
"choices": ['take treasure', 'leave'],
"transitions": {'take treasure': 'ruins_celebrate', 'leave': 'ruins_ruins'},
"consequences": {
'take treasure': lambda player: player.add_item('treasure')
},
"media": []
},
"celebrate": {
"description": "You celebrate your discovery and decide to bring the treasure back to the village.",
"choices": ['return to village'],
"transitions": {'return to village': 'village_return'},
"media": []
},
},
"village_return": {
"village_return": {
"description": "You return to the village with the treasure and share it with the villagers.",
"choices": ['end adventure'],
"transitions": {'end adventure': 'end_end'},
"media": []
},
},
"end": {
"end": {
"description": "Your adventure ends here. The villagers are grateful and everyone's lives improve.",
"choices": [],
"transitions": {},
"media": []
},
}
}"""
#Analyzing Game Configuration Metrics - was the thread name of where the
claude3_5_06072024configtips = """Example Config Development Tab - Claude 3.5 Sonnet as the LLM Assitant
This config is for a basic text based game engine I made with help many llms including you.
Thanks to all the help it loads which presented another problem, I dont have any structural metrics to assess the quality of the config.
What JSON things can we look at to see if it may be too bland for a person testing the game
Text-Based Game Configuration Analysis
1. State Variety
Total number of states: 13
Number of unique locations: 5 (village, forest, ruins, village_return, end)
2. Choice Diversity
Average choices per state: 1.92
States with no choices: 1 (end state)
States with most choices: 3 (village_start with 3 choices)
Unique choices across all states: 17
3. Transition Complexity
Total number of transitions: 25
Average transitions per state: 1.92
States with most transitions: 3 (village_start with 3 transitions)
4. Consequence Implementation
States with consequences: 3
Total number of consequences: 3
Types of consequences: Adding items, Updating knowledge
5. Description Length
Average description length: 13.15 words
Longest description: 24 words (village_return)
Shortest description: 4 words (village_supplies)
6. Cyclic Paths
Presence of loops: Yes (e.g., village_start -> village_supplies -> village_start)
7. Dead Ends
Number of dead ends: 1 (end state)
8. Media Integration
States with media: 0
Total media elements: 0
9. Narrative Progression
Clear beginning (village_start) and end (end) states
Multiple paths to reach the end
10. Player Agency
Choices affect game progression
Some choices have consequences (3 instances)
11. Game Length
Minimum steps to complete: 6 (village_start -> village_supplies -> forest_forest -> ruins_ruins -> ruins_explore -> ruins_hiddenPassage -> ruins_treasureRoom -> ruins_celebrate -> village_return -> end)
Maximum steps (including loops): Potentially infinite due to cycles
12. Replayability
Multiple paths through the game
Some variability in outcomes based on choices
#=============================================
To assess the quality and potential blandness of your game configuration, we can analyze several structural metrics within the JSON. Here are some aspects we can examine:
Text-Based Game Configuration AnalysisClick to open document
Based on this analysis, here are some observations about the potential blandness of the game:
Limited state variety: With only 13 states across 5 locations, the game might feel short and lacking in diversity. Consider adding more locations or states within existing locations.
Low average choices: An average of 1.92 choices per state might make the game feel linear. Increasing the number of choices in more states could improve player engagement.
Limited consequences: Only 3 states have consequences, which might make player choices feel less impactful. Adding more consequences could increase the sense of agency.
Short descriptions: The average description length of 13.15 words might not provide enough detail to immerse players. Consider expanding descriptions to create a richer narrative.
Lack of media: No states currently use media elements, which could make the game feel less engaging. Adding images, sound effects, or other media could enhance the player experience.
Limited narrative branching: While there are some loops and choices, the overall structure is relatively linear. Adding more branching paths could increase replayability and player interest.
To make the game less bland, consider:
Adding more states and locations
Increasing the number of choices in each state
Implementing more consequences for player actions
Expanding descriptions to create a richer narrative
Incorporating media elements
Creating more diverse paths through the game
#===============================================
# Text-Based Game Improvement Suggestions
## 1. Expand State Variety
- Add a new location: "Mountain Pass"
- Include states like "steep_climb", "avalanche_risk", "hidden_cave"
- Expand the "forest" location:
- Add states like "dense_thicket", "mysterious_clearing", "ancient_tree"
## 2. Increase Choice Diversity
- Add more choices to existing states. For example, in "village_start":
- "talk to elder"
- "visit market"
- "investigate strange noises"
- Ensure most states have at least 3 choices
## 3. Enhance Transition Complexity
- Create more interconnected states. For example:
- Allow travel between "forest" and "mountain_pass"
- Add shortcuts or secret passages between non-adjacent locations
## 4. Implement More Consequences
- Add consequences to more choices. For example:
- In "forest_forest":
- "forage for food" -> `lambda player: player.add_item('wild berries')`
- "take shortcut" -> `lambda player: player.update_status('lost')`
## 5. Enrich Descriptions
- Expand existing descriptions with more vivid details
- Example for "village_start":
```python
"description": "You wake up in a small village nestled between rolling hills. The air is filled with the scent of freshly baked bread and the sound of a distant waterfall. Villagers bustle about, whispering excitedly about a rumor of lost treasure."
```
## 6. Introduce Cyclic Content with Variations
- Add time-based changes to revisited locations
- Example:
```python
'village_start': {
"description": lambda player: f"You return to the village square. It's now {player.time_of_day()}. " +
("The market is bustling with activity." if player.time_of_day() == "day" else
"The streets are quiet, lit by flickering torches.")
}
```
## 7. Create Meaningful Dead Ends
- Add optional quests or side adventures
- Example: "help_lost_child" state in the village that doesn't progress main story but provides rewards
## 8. Integrate Media Elements
- Add placeholder media to enhance immersion:
```python
"media": [
{"type": "image", "url": "/api/placeholder/400/300", "alt": "A picturesque village at dawn"},
{"type": "sound", "url": "village_ambience.mp3"}
]
```
## 9. Enhance Narrative Progression
- Add a main quest storyline with multiple stages
- Introduce side quests for additional depth
## 10. Increase Player Agency
- Add more impactful choices that significantly alter the game's direction
- Implement a simple inventory or skill system that affects available choices
## 11. Extend Game Length
- Add more locations and states to create a longer, more involved adventure
- Implement quest chains that span multiple locations
## 12. Improve Replayability
- Add random events that can occur in each location
- Implement multiple endings based on player choices and achievements
#===============================================
# Updated Text-Based Game Configuration with Side Quest
## New State: help_lost_child
Add this new state to the 'village' section of your `all_states` dictionary:
```python
'village': {
# ... existing states ...
'help_lost_child': {
"description": "You encounter a crying child in the village square. They seem to have lost their way home.",
"choices": ['help child', 'ignore and continue'],
"transitions": {
'help child': 'village_child_quest',
'ignore and continue': 'village_start'
},
"consequences": {
'help child': lambda player: player.update_status('helping_child')
},
"media": []
},
'child_quest': {
"description": "You decide to help the lost child. After asking around and searching the village, you finally locate their home.",
"choices": ['return child', 'ask for reward'],
"transitions": {
'return child': 'village_child_reunion',
'ask for reward': 'village_child_reward'
},
"media": []
},
'child_reunion': {
"description": "You return the child to their grateful parents. They thank you profusely for your kindness.",
"choices": ['accept thanks', 'request reward'],
"transitions": {
'accept thanks': 'village_start',
'request reward': 'village_child_reward'
},
"consequences": {
'accept thanks': lambda player: player.update_status('local_hero')
},
"media": []
},
'child_reward': {
"description": "The child's parents offer you a small pouch of coins as a reward for your help.",
"choices": ['accept reward', 'decline reward'],
"transitions": {
'accept reward': 'village_start',
'decline reward': 'village_start'
},
"consequences": {
'accept reward': lambda player: player.add_item('coin pouch'),
'decline reward': lambda player: player.update_status('selfless_hero')
},
"media": []
},
}
```
## Updated Transitions
To incorporate this side quest into the existing game flow, we need to update some transitions in the 'village_start' state:
```python
'village': {
'start': {
"description": "You're in the village square. The usual bustle of village life surrounds you.",
"choices": ['explore village', 'gather supplies', 'rest', 'look around'], # Added 'look around'
"transitions": {
'explore village': 'village_rumor',
'gather supplies': 'village_supplies',
'rest': 'village_start',
'look around': 'village_help_lost_child' # New transition
},
"consequences": {
'gather supplies': lambda player: player.add_item('basic supplies')
},
"media": []
},
# ... other states ...
}
```
## Explanation of Changes
1. New States:
- `help_lost_child`: Introduces the side quest
- `child_quest`: Represents the process of helping the child
- `child_reunion`: Concludes the quest if you don't ask for a reward
- `child_reward`: Offers a choice to accept or decline a reward
2. Updated `village_start`:
- Added a new choice: 'look around'
- Added a new transition to `village_help_lost_child`
3. Consequences:
- Added status updates: 'helping_child', 'local_hero', 'selfless_hero'
- Added item reward: 'coin pouch'
These changes create a meaningful dead end by:
1. Providing an optional quest that doesn't directly progress the main treasure hunt story
2. Offering multiple choices within the side quest, allowing for different outcomes
3. Implementing consequences that affect the player's status or inventory, providing rewards for engagement
4. Allowing the player to return to the main story flow after completing (or ignoring) the side quest
This side quest adds depth to the village location, gives the player more to do, and provides character-building opportunities without derailing the main narrative. It also demonstrates how you can implement similar side quests or meaningful dead ends in other locations of your game.
#================================================================================
Certainly! Let's implement the "help_lost_child" side quest as a meaningful dead end in the village. This will add depth to the game without necessarily progressing the main story. Here's how we can incorporate this into your current configuration:
Updated Text-Based Game Configuration with Side QuestClick to open document
To further improve this side quest and make it even more engaging, you could consider:
Time sensitivity: Make the quest available only at certain times or for a limited number of turns.
Skill checks: If your game has a skill system, you could add checks for persuasion or perception that affect the outcome.
Long-term consequences: The status changes (like 'local_hero') could affect how NPCs interact with the player later in the game.
Branching outcomes: You could add more complex branches, such as the child being in actual danger, leading to a mini-adventure.
Would you like me to elaborate on any of these ideas or show how to implement them in your configuration?
"""
tipsupdatedconfigatbeinningofthisspace = """{
"village": {
"start": {
"description": "You wake up in a small village. You hear a rumor about a lost treasure.",
"choices": ['explore village', 'gather supplies', 'rest', 'look around'],
"transitions": {'explore village': 'village_rumor', 'gather supplies': 'village_supplies', 'rest': 'village_start', 'look around': 'village_help_lost_child'},
"consequences": {
'gather supplies': lambda player: player.add_item('basic supplies')
},
"media": []
},
"rumor": {
"description": "You hear more details about the treasure hidden in the ancient ruins nearby.",
"choices": ['decide to go', 'ignore'],
"transitions": {'decide to go': 'village_supplies', 'ignore': 'village_start'},
"consequences": {
'decide to go': lambda player: player.update_knowledge('treasure location')
},
"media": []
},
"supplies": {
"description": "You gather supplies for your journey.",
"choices": ['head to forest', 'stay in village'],
"transitions": {'head to forest': 'forest_forest', 'stay in village': 'village_start'},
"media": []
},
"help_lost_child": {
"description": "You encounter a crying child in the village square. They seem to have lost their way home.",
"choices": ['help child', 'ignore and continue'],
"transitions": {
'help child': 'village_child_quest',
'ignore and continue': 'village_start'
},
"consequences": {
'help child': lambda player: player.update_status('helping_child')
},
"media": []
},
"child_quest": {
"description": "You decide to help the lost child. After asking around and searching the village, you finally locate their home.",
"choices": ['return child', 'ask for reward'],
"transitions": {
'return child': 'village_child_reunion',
'ask for reward': 'village_child_reward'
},
"media": []
},
"child_reunion": {
"description": "You return the child to their grateful parents. They thank you profusely for your kindness.",
"choices": ['accept thanks', 'request reward'],
"transitions": {
'accept thanks': 'village_start',
'request reward': 'village_child_reward'
},
"consequences": {
'accept thanks': lambda player: player.update_status('local_hero')
},
"media": []
},
"child_reward": {
"description": "The child's parents offer you a small pouch of coins as a reward for your help.",
"choices": ['accept reward', 'decline reward'],
"transitions": {
'accept reward': 'village_start',
'decline reward': 'village_start'
},
"consequences": {
'accept reward': lambda player: player.add_item('coin pouch'),
'decline reward': lambda player: player.update_status('selfless_hero')
},
"media": []
},
},
"forest": {
"forest": {
"description": "You enter the dense forest, heading towards the ruins.",
"choices": ['travel further', 'return to village'],
"transitions": {'travel further': 'ruins_ruins', 'return to village': 'village_start'},
"media": []
},
},
"ruins": {
"ruins": {
"description": "You reach the ancient ruins. The entrance is dark and eerie.",
"choices": ['enter ruins', 'return to forest'],
"transitions": {'enter ruins': 'ruins_explore', 'return to forest': 'forest_forest'},
"media": []
},
"explore": {
"description": "You explore the ruins, encountering traps and puzzles.",
"choices": ['solve puzzle', 'avoid traps'],
"transitions": {'solve puzzle': 'ruins_hiddenPassage', 'avoid traps': 'ruins_ruins'},
"media": []
},
"hiddenPassage": {
"description": "You solve a challenging puzzle and unlock a hidden passage.",
"choices": ['enter passage', 'go back'],
"transitions": {'enter passage': 'ruins_treasureRoom', 'go back': 'ruins_explore'},
"media": []
},
"treasureRoom": {
"description": "You enter the treasure room and find the treasure chest.",
"choices": ['take treasure', 'leave'],
"transitions": {'take treasure': 'ruins_celebrate', 'leave': 'ruins_ruins'},
"consequences": {
'take treasure': lambda player: player.add_item('treasure')
},
"media": []
},
'celebrate': {
"description": "You celebrate your discovery and decide to bring the treasure back to the village.",
"choices": ['return to village'],
"transitions": {'return to village': 'village_return'},
"media": []
},
},
"village_return": {
"village_return": {
"description": "You return to the village with the treasure and share it with the villagers.",
"choices": ['end adventure'],
"transitions": {'end adventure': 'end_end'},
"media": []
},
},
"end": {
"end": {
"description": "Your adventure ends here. The villagers are grateful and everyone's lives improve.",
"choices": [],
"transitions": {},
"media": []
},
}
}"""
with gr.Tab("Improvement of the default config"):
gr.HTML("Example of how to advance a game config with LLM - end goal is to have automatic worflow that takes these considerations into account <br> Things missing from the game engine - Economics and Basic Politics (NPC affiliation)")
gr.HTML("Suggestions from claude 3.5 on how to change config")
display_originalconfigatbeinningofthisspace = originalconfigatbeinningofthisspace.replace(' ', ' ').replace('\n', '<br>')
display_claude3_5_06072024configtips = claude3_5_06072024configtips.replace(' ', ' ').replace('\n', '<br>')
display_tipsupdatedconfigatbeinningofthisspace = tipsupdatedconfigatbeinningofthisspace.replace(' ', ' ').replace('\n', '<br>')
gr.HTML("""<div style="display: flex; justify-content: space-between; height: 900px; overflow: auto; ">
<div style="flex: 1; margin: 0 10px; padding: 20px;">
""" + display_originalconfigatbeinningofthisspace + """
</div>
<div style="flex: 1; margin: 0 10px; padding: 20px; width: 50%">
""" + display_claude3_5_06072024configtips + """
</div>
<div style="flex: 1; margin: 0 10px; padding: 20px;">
""" + display_tipsupdatedconfigatbeinningofthisspace + """
</div>
</div>""")
with gr.Accordion("Temporary Asset Management Assist - click to open", open=False):
gr.HTML("Make Files and Text ideas for the field and paste <br>When Space is restarted it will clear - zip export and import will be added later")
with gr.Accordion("Upload Files for config"):
gr.Markdown("# Media Saver and Explorer (refresh file list to be resolved - for now upload all files and reload the space - they persist as long as the space creator doesnt reset/update the space - will add manual clear options later)")
with gr.Tab("Upload Files"):
file_input = gr.File(label="Choose File to Upload")
save_output = gr.Textbox(label="Upload Status")
with gr.Tab("File Explorer"):
file_explorer = gr.FileExplorer(
root_dir=SAVE_DIR,
glob="*.*",
file_count="single",
height=300,
label="Select a file to view"
)
with gr.Row():
refresh_button = gr.Button("Refresh", scale=1)
view_button = gr.Button("View File")
image_output = gr.Image(label="Image Output", type="pil")
audio_output = gr.Audio(label="Audio Output")
video_output = gr.Video(label="Video Output")
error_output = gr.Textbox(label="Error")
file_input.upload(
save_file,
inputs=file_input,
outputs=[save_output, file_explorer, file_input]
)
view_button.click(
view_file,
inputs=file_explorer,
outputs=[image_output, audio_output, video_output, error_output]
)
refresh_button.click(
refresh_file_explorer,
outputs=file_explorer
)
with gr.Tab("Batch add files to config"):
gr.HTML("Placeholder for Config parser to allow dropdowns for the media parts of the config inserted to make assigning media quick")
gr.HTML("Placeholder for Config parser to allow for current zerospace creation and placement into the config (LLM can give list of media but still have to figure out workflow from there)")
gr.HTML("Placeholder for clearing uploaded assets (public space and temporary persistence = sharing and space problems)")
with gr.Tab("Test and Edit Config"):
gr.HTML("The main issue is frequent changes add more chances for bugs in how - manual and auto refer mainly to ensuring correct JSON format ")
with gr.Tab("Full Manual - Test Example State Machine"):
with gr.Tab("Config Without Assets"):
with gr.Row():
with gr.Column(scale=2):
gr.Markdown("# Text-based Adventure Game")
description = gr.Textbox(label="Current Situation", lines=4, value=initgameinfo[0])
choices = gr.Radio(label="Your Choices", choices=initgameinfo[1])
submit_btn = gr.Button("Make Choice")
game_log = gr.Textbox(label="Game Log", lines=20, value=initgameinfo[2])
game_session = gr.State(value=initgameinfo[3])
submit_btn.click(
make_choice,
inputs=[choices, game_session],
outputs=[description, choices, game_log, game_session]
)
with gr.Column(scale=1):
gr.Markdown("# Debugging")
error_box = gr.Textbox(label="Path Errors", lines=4, value=path_errors)
with gr.Accordion("Config (Game Spoiler and Example for llm to remix)", open=False):
custom_config = gr.Textbox(label="Custom Configuration (JSON)", value=json.dumps(all_states, default=lambda o: o.__dict__, indent=2), lines=8)
custom_configbtn = gr.Button("Load Custom Config")
custom_configbtn.click(
load_game,
inputs=[custom_config],
outputs=[error_box, game_log, description, choices, game_session, custom_config]
)
with gr.Tab("Config With Assets"):
gr.HTML("Placeholder as not complete yet (still only text, current issue is how to switch gradio output, maybe output is gr.Group and we constantly add the appropriate gr for each file type? What about multi file types on one state?)")
with gr.Row():
with gr.Column(scale=2):
gr.Markdown("# Text-based Adventure Game")
wadescription = gr.Textbox(label="Current Situation", lines=4, value=initgameinfo[0])
wamediabool = gr.State(value=True)
wamedia = gr.State(["testmedia/Stable Audio - Raindrops, output.wav"])
@gr.render(inputs=wamedia)
def dynamic_with_media(media_items):
print(media_items)
with gr.Group() as wamediagrouping:
gr.HTML("Placeholder to load all media tests - still need to test clearing media on ")
if media_items == []:
gr.Markdown("No media items to display.")
else:
for item in media_items:
render = create_media_component(item)
return wamediagrouping
wachoices = gr.Radio(label="Your Choices", choices=initgameinfo[1])
wasubmit_btn = gr.Button("Make Choice")
wagame_log = gr.Textbox(label="Game Log", lines=20, value=initgameinfo[2])
wagame_session = gr.State(value=initgameinfo[3])
wasubmit_btn.click(
make_choice,
inputs=[wachoices, wagame_session, wamediabool],
outputs=[wadescription, wachoices, wagame_log, wagame_session, wamedia]
)
with gr.Column(scale=1):
gr.Markdown("# Debugging")
waerror_box = gr.Textbox(label="Path Errors", lines=4, value=path_errors)
with gr.Accordion("Config (Game Spoiler and Example for llm to remix)", open=False):
wacustom_config = gr.Textbox(label="Custom Configuration (JSON)", value=json.dumps(all_states, default=lambda o: o.__dict__, indent=2), lines=8)
wacustom_configbtn = gr.Button("Load Custom Config")
wacustom_configbtn.click(
load_game,
inputs=[wacustom_config, wamediabool],
outputs=[waerror_box, wagame_log, wadescription, wachoices, wacustom_config, wagame_session, wamedia]
)
with gr.Tab("Config With Minimal 3D considered"):
gr.HTML("Placeholder for Config with 3D assets")
with gr.Tab("Semi-Auto - Edit config while playing game"):
gr.HTML("-- Incomplete -- Issue here is updating all variables <br> Current problem is passing values from rendered items to the config box <br>Generate Timline also makes config without mmedia key <br>Need a way have dropdowns for the filelist and transitions eg. changing transitions must auto update choices <br>Config to components has hardcoded variables based on the auto gen so changes break it")
with gr.Row():
with gr.Column(scale=1):
with gr.Group():
gr.Markdown("# Text-based Adventure Game")
ewpwadescription = gr.Textbox(label="Current Situation", lines=4, value=initgameinfo[0])
ewpwamediabool = gr.State(value=True)
ewpwamedia = gr.State(["testmedia/Stable Audio - Raindrops, output.wav"])
@gr.render(inputs=ewpwamedia)
def dynamic_with_media(media_items):
print(media_items)
with gr.Group() as ewpwamediagrouping:
gr.HTML("Placeholder to load all media tests - still need to test clearing media on ")
if media_items == []:
gr.Markdown("No media items to display.")
else:
for item in media_items:
render = create_media_component(item)
return ewpwamediagrouping
ewpwachoices = gr.Radio(label="Your Choices", choices=initgameinfo[1])
ewpwasubmit_btn = gr.Button("Make Choice")
ewpwagame_log = gr.Textbox(label="Game Log", lines=20, value=initgameinfo[2])
ewpwagame_session = gr.State(value=initgameinfo[3])
ewpwasubmit_btn.click(
make_choice,
inputs=[ewpwachoices, ewpwagame_session, ewpwamediabool],
outputs=[ewpwadescription, ewpwachoices, ewpwagame_log, ewpwagame_session, ewpwamedia]
)
with gr.Column(scale=1):
gr.Markdown("# Debugging")
ewpwaerror_box = gr.Textbox(label="Path Errors", lines=4, value=path_errors)
ewpwacustom_config = gr.Textbox(label="Custom Configuration (JSON)", value=json.dumps(all_states, default=lambda o: o.__dict__, indent=2), lines=8)
ewpwacustom_configbtn = gr.Button("Load Custom Config")
ewpwacustom_configbtn.click(
load_game,
inputs=[ewpwacustom_config, ewpwamediabool],
outputs=[ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia]
)
with gr.Accordion("Can copy in the Test Example State Machine tab - only linear path for now", open=False):
gr.Markdown("# Story and Timeline Generator")
gr.Markdown("Click the button to generate a random timeline and story based on UI elements and story events. <br>Ask an LLM to use this to write a story around")
with gr.Row():
ewpgame_structure_output_text_with_media = gr.Code(language="json")
ewpgame_structure_output_text = gr.Code(language="json")
with gr.Row():
ewptimeline_output_with_assets = gr.Textbox(label="Timeline with Assets Considered", lines=20)
ewptimeline_output = gr.Textbox(label="Timeline (Order might be different for now)", lines=20)
ewpstory_output = gr.Textbox(label="Generated Story (Order might be different for now)", lines=20)
with gr.Row():
ewpgenerate_no_ui_timeline_points = gr.Slider(minimum=1, value=10, step=1, maximum=30, label="Choose the amount of ui timeline points")
ewpgenerate_no_media_timeline_points = gr.Slider(minimum=1, value=5, step=1, maximum=30, label="Choose the amount of media timeline points")
ewpgenerate_with_media_check = gr.Checkbox(label="Generate with media", value=True)
ewpgenerate_button = gr.Button("Generate Story and Timeline")
@gr.render(inputs=ewpwacustom_config) #ewpgame_structure_output_text_with_media
def update(ewpwacustom_config):
return show_elements_json_input(ewpwacustom_config)
ewpgenerate_button.click(generate_story_and_timeline, inputs=[ewpgenerate_no_ui_timeline_points, ewpgenerate_no_media_timeline_points, ewpgenerate_with_media_check], outputs=[ewptimeline_output_with_assets, ewptimeline_output, ewpstory_output, ewpwacustom_config, ewpgame_structure_output_text]) #ewpgame_structure_output_text_with_media, ewpgame_structure_output_text])
with gr.Tab("Asset Generation Considerations"):
gr.HTML("With some asset category ideas from gemini-1.5-flash-api-0514 and reka-flash-preview-20240611 <br><br>Licenses for the spaces still to be evaluated - June 2024 <br> Users to follow with cool spaces - https://huggingface.co/fffiloni, https://huggingface.co/artificialguybr, https://huggingface.co/radames, https://huggingface.co/multimodalart, ")
with gr.Accordion("LLM HF Spaces/Sites (Click Here to Open) - Ask for a story and suggestions based on the autoconfig", open=False):
with gr.Row():
linktochat = gr.Dropdown(choices=["https://labs.perplexity.ai/", "https://chat.lmsys.org", "https://sdk.vercel.ai/docs", "https://qwen-qwen-max-0428.hf.space", "https://cohereforai-c4ai-command-r-plus.hf.space", "https://huggingface.co/spaces/eswardivi/Phi-3-mini-128k-instruct", "https://eswardivi-phi-3-mini-4k-instruct.hf.space", "https://cyzgab-catch-me-if-you-can.hf.space", "https://snowflake-snowflake-arctic-st-demo.hf.space", "https://qwen-qwen1-5-110b-chat-demo.hf.space", "https://ysharma-chat-with-meta-llama3-8b.hf.space", "https://databricks-dbrx-instruct.hf.space", "https://qwen-qwen1-5-moe-a2-7b-chat-demo.hf.space", "https://cohereforai-c4ai-command-r-v01.hf.space", "https://ehristoforu-mixtral-46-7b-chat.hf.space", "https://stabilityai-stablelm-2-1-6b-zephyr.hf.space", "https://qwen-qwen1-5-72b-chat.hf.space", "https://deepseek-ai-deepseek-coder-7b-instruct.hf.space", "https://01-ai-yi-34b-chat.hf.space", "https://ysharma-zephyr-playground.hf.space", "https://huggingfaceh4-zephyr-chat.hf.space", "https://osanseviero-mistral-super-fast.hf.space", "https://artificialguybr-qwen-14b-chat-demo.hf.space", "https://huggingface-projects-llama-2-7b-chat.hf.space", "https://ysharma-explore-llamav2-with-tgi.hf.space", "https://mosaicml-mpt-30b-chat.hf.space", "https://huggingfaceh4-falcon-chat.hf.space", "https://uwnlp-guanaco-playground-tgi.hf.space", "https://stabilityai-stablelm-tuned-alpha-chat.hf.space", "https://mosaicml-mpt-7b-storywriter.hf.space", "https://huggingfaceh4-starchat-playground.hf.space", "https://bigcode-bigcode-playground.hf.space", "https://mosaicml-mpt-7b-chat.hf.space", "https://huggingchat-chat-ui.hf.space", "https://togethercomputer-openchatkit.hf.space"], label="Choose/Cancel type any .hf.space link here (can also type a link)'", allow_custom_value=True)
chatspacebtn = gr.Button("Use the chosen URL to load interface with a chat model. For sdk.vercel click the chat button on the top left. For lymsys / chat arena copy the link and use a new tab")
chatspace = gr.HTML("Chat Space Chosen will load here")
chatspacebtn.click(display_website, inputs=linktochat, outputs=chatspace)
with gr.Tab("Save files"):
gr.HTML("For Dynamic events overnight or when player is not active what can LLMS edit? <br><br>eg. Waiting for a letter from a random npc can be decided by the llm <br>eg. Improved Stats on certain days (eg. bitrthday) <br>Privacy <br>User Directed DLC eg. Rockstar Editor with local llm guide")
gr.HTML("Some ideas - In game websites eg. GTA esp stock markets, news; ")
gr.HTML("Placeholder for huggingface spaces that can assist - https://huggingface.co/nvidia/Nemotron-4-340B-Instruct (Purpose is supposed to be synthetic data generation), https://huggingface.co/spaces/gokaygokay/Gemma-2-llamacpp ")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist (9b and under) <br>initial floor for testing can be https://huggingface.co/spaces/Qwen/Qwen2-0.5B-Instruct, https://huggingface.co/spaces/Qwen/Qwen2-1.5b-instruct-demo, https://huggingface.co/spaces/stabilityai/stablelm-2-1_6b-zephyr, https://huggingface.co/spaces/IndexTeam/Index-1.9B, https://huggingface.co/microsoft/Phi-3-mini-4k-instruct")
with gr.Tab("Diagrams"):
gr.HTML("Claude 3.5 sonnet is very good with mermaid graphs - can used for maps, situational explanations")
with gr.Tab("Maths"):
gr.HTML("https://huggingface.co/spaces/AI-MO/math-olympiad-solver")
with gr.Tab("Media Understanding"):
gr.HTML("NPC Response Engines? Camera, Shopkeeper, Companion, Enemies, etc.")
with gr.Accordion("Media understanding model Spaces/Sites (Click Here to Open) - Image to Blender?", open=False):
with gr.Row():
linktomediaunderstandingspace = gr.Dropdown(choices=[ "--Weak Audio Understanding = Audio to text, Weak Video Understanding = Video to Image to Image Understanding", "https://skalskip-florence-2-video.hf.space", "https://kingnish-opengpt-4o.hf.space",
"--Image Understanding--", "https://qnguyen3-nanollava.hf.space", "https://skalskip-better-florence-2.hf.space", ],
label="Choose/Cancel type any .hf.space link here (can also type a link)'", allow_custom_value=True)
mediaunderstandingspacebtn = gr.Button("Use the chosen URL to load interface with a media understanding space")
mediaunderstandingspace = gr.HTML("Audio Space Chosen will load here")
mediaunderstandingspacebtn.click(display_website, inputs=linktomediaunderstandingspace, outputs=mediaunderstandingspace)
with gr.Tab("Images"):
with gr.Accordion("Image Gen or Animation HF Spaces/Sites (Click Here to Open) - Have to download and upload at the the top", open=False):
# with gr.Tabs("General"):
with gr.Row():
linktoimagegen = gr.Dropdown(choices=["Text-Interleaved", "https://ethanchern-anole.hf.space",
"--General--", "https://pixart-alpha-pixart-sigma.hf.space", "https://stabilityai-stable-diffusion-3-medium.hf.space", "https://prodia-sdxl-stable-diffusion-xl.hf.space", "https://prodia-fast-stable-diffusion.hf.space", "https://bytedance-hyper-sdxl-1step-t2i.hf.space", "https://multimodalart-cosxl.hf.space", "https://cagliostrolab-animagine-xl-3-1.hf.space", "https://stabilityai-stable-diffusion.hf.space",
"--Speed--", "https://radames-real-time-text-to-image-sdxl-lightning.hf.space", "https://ap123-sdxl-lightning.hf.space",
"--LORA Support--", "https://artificialguybr-artificialguybr-demo-lora.hf.space", "https://artificialguybr-studio-ghibli-lora-sdxl.hf.space", "https://artificialguybr-pixel-art-generator.hf.space", "https://fffiloni-sdxl-control-loras.hf.space", "https://ehristoforu-dalle-3-xl-lora-v2.hf.space",
"--Image to Image--", "https://lllyasviel-ic-light.hf.space", "https://gparmar-img2img-turbo-sketch.hf.space",
"--Control of Pose--", "https://instantx-instantid.hf.space", "https://modelscope-transferanything.hf.space", "https://okaris-omni-zero.hf.space"
"--Control of Shapes--", "https://linoyts-scribble-sdxl-flash.hf.space",
"--Foreign Language Input--", "https://gokaygokay-kolors.hf.space"], label="Choose/Cancel type any .hf.space link here (can also type a link)'", allow_custom_value=True)
imagegenspacebtn = gr.Button("Use the chosen URL to load interface with a image generation model")
imagegenspace = gr.HTML("Image Space Chosen will load here")
imagegenspacebtn.click(display_website, inputs=linktoimagegen, outputs=imagegenspace)
linkstobecollectednoembed = "https://artgan-diffusion-api.hf.space", "https://multimodalart-stable-cascade.hf.space", "https://google-sdxl.hf.space", "https://visionmaze-magic-me.hf.space", "https://segmind-segmind-stable-diffusion.hf.space", "https://simianluo-latent-consistency-model.hf.space",
gr.HTML("Concept Art, UI elements, Static/3D Characters, Environments and Objects")
gr.HTML("Image Caption = https://huggingface.co/spaces/microsoft/Promptist, https://huggingface.co/spaces/gokaygokay/SD3-Long-Captioner, https://huggingface.co/spaces/gokaygokay/Florence-2, ")
gr.HTML("Images Generation Portraits = https://huggingface.co/spaces/okaris/omni-zero")
gr.HTML("Images Generation General (3rd Party) = https://www.craiyon.com/")
gr.HTML("Images Generation Posters with text - https://huggingface.co/spaces/GlyphByT5/Glyph-SDXL-v2")
gr.HTML("Placeholder for huggingface spaces that can assist - https://huggingface.co/spaces/EPFL-VILAB/4M, https://huggingface.co/spaces/EPFL-VILAB/MultiMAE ")
gr.HTML("SVG Generation = Coding models / SOTA LLM ")
gr.HTML("Images Generation - Upscaling - https://huggingface.co/spaces/gokaygokay/Tile-Upscaler")
gr.HTML("Vision Models for descriptions <br> https://huggingface.co/spaces/gokaygokay/Florence-2 <br>https://huggingface.co/spaces/vilarin/VL-Chatbox - glm 4v 9b <br>")
gr.HTML("Upscalers (save data transfer costs? highly detailed characters?) - https://huggingface.co/spaces/gokaygokay/AuraSR")
gr.HTML("Placeholder for huggingface spaces that can assist ")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist")
with gr.Tab("Video"):
with gr.Accordion("Video Spaces/Sites (Click Here to Open) - Image to Blender?", open=False):
with gr.Row():
linktovideogenspace = gr.Dropdown(choices=["--Genral--", "https://kadirnar-open-sora.hf.space",
"--Talking Portrait--", "https://fffiloni-tts-hallo-talking-portrait.hf.space",
"--Gif / ImgtoImg based video--", "https://wangfuyun-animatelcm-svd.hf.space", "https://bytedance-animatediff-lightning.hf.space", "https://wangfuyun-animatelcm.hf.space", "https://guoyww-animatediff.hf.space",],
label="Choose/Cancel type any .hf.space link here (can also type a link)'", allow_custom_value=True)
videogenspacebtn = gr.Button("Use the chosen URL to load interface with video generation")
videogenspace = gr.HTML("Video Space Chosen will load here")
videogenspacebtn.click(display_website, inputs=linktovideogenspace, outputs=videogenspace)
gr.HTML("Cutscenes, Tutorials, Trailers")
gr.HTML("Portrait Video eg. Solo Taking NPC - https://huggingface.co/spaces/fffiloni/tts-hallo-talking-portrait (Image + Audio and combination) https://huggingface.co/spaces/KwaiVGI/LivePortrait (Non verbal communication eg. in a library, when running from a pursuer)")
gr.HTML("Placeholder for huggingface spaces that can assist - https://huggingface.co/spaces/KingNish/Instant-Video, https://huggingface.co/spaces/multimodalart/stable-video-diffusion, https://huggingface.co/spaces/multimodalart/stable-video-diffusion")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist")
gr.HTML("3rd Party / Closed Source - https://runwayml.com/ <br>")
with gr.Tab("Animations (for lower resource use)"):
gr.HTML("Characters, Environments, Objects")
gr.HTML("Placeholder for huggingface spaces that can assist - image as 3d object in video https://huggingface.co/spaces/ashawkey/LGM")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist")
with gr.Tab("Audio"):
with gr.Accordion("Audio Spaces/Sites (Click Here to Open) - Image to Blender?", open=False):
with gr.Row():
linktoaudiiogenspace = gr.Dropdown(choices=["General", "https://artificialguybr-stable-audio-open-zero.hf.space", "",
"--Talking Portrait--","https://fffiloni-tts-hallo-talking-portrait.hf.space"],
label="Choose/Cancel type any .hf.space link here (can also type a link)'", allow_custom_value=True)
audiiogenspacebtn = gr.Button("Use the chosen URL to load interface with audio generation")
audiiogenspace = gr.HTML("Audio Space Chosen will load here")
audiiogenspacebtn.click(display_website, inputs=linktoaudiiogenspace, outputs=audiiogenspace)
gr.HTML("Music - Background, Interactive, Cutscene, Menu <br>Sound Effects - Environment, character, action (environmental triggered by user eg. gun), UI <br>Speech - Dialouge, narration, voiceover <br>The new render function means the Config can be made and iframe/api functions can be ordered as neccessary based on the part of the config that needs it to streamline workflows based on current state of config ")
gr.HTML("Placeholder for huggingface spaces that can assist")
gr.HTML("Audio Sound Effects - https://huggingface.co/spaces/artificialguybr/Stable-Audio-Open-Zero")
gr.HTML("Voices - Voice clone eg. actors part of your project - https://huggingface.co/spaces/tonyassi/voice-clone")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist")
gr.HTML("3rd Party / Closed Source - https://suno.com/ <br>https://www.udio.com/")
with gr.Tab("3D"):
with gr.Accordion("3D Model Spaces/Sites (Click Here to Open) - Image to Blender?", open=False):
with gr.Row():
linktoThreedModel = gr.Dropdown(choices=["https://wuvin-unique3d.hf.space", "https://stabilityai-triposr.hf.space", "https://hysts-shap-e.hf.space", "https://tencentarc-instantmesh.hf.space", "https://ashawkey-lgm.hf.space", "https://dylanebert-lgm-mini.hf.space", "https://dylanebert-splat-to-mesh.hf.space", "https://dylanebert-multi-view-diffusion.hf.space"], label="Choose/Cancel type any .hf.space link here (can also type a link)'", allow_custom_value=True)
ThreedModelspacebtn = gr.Button("Use the chosen URL to load interface with a 3D model")
ThreedModelspace = gr.HTML("3D Space Chosen will load here")
ThreedModelspacebtn.click(display_website, inputs=linktoThreedModel, outputs=ThreedModelspace)
gr.HTML("Characters, Environments, Objects")
gr.HTML("Placeholder for huggingface spaces that can assist - https://huggingface.co/spaces/dylanebert/3d-arena")
gr.HTML("Closed Source - https://www.meshy.ai/")
with gr.Tab("Fonts"):
gr.HTML("Style of whole game, or locations, or characters")
gr.HTML("Placeholder for huggingface spaces that can assist - there was a space that could make letter into pictures based on the prompt but I cant find it now")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist")
with gr.Tab("Shaders and related"):
gr.HTML("Any output that is not understood by the common person can be used as special effects eg. depth map filters on images etc.")
gr.HTML("Post-processing Effects, material effects, Particle systems, visual feedback")
gr.HTML("Visual Effects - eg. explosion can turn all items white for a moment, losing conciousness blurs whole screen")
gr.HTML("Placeholder for huggingface spaces that can assist - https://huggingface.co/spaces/EPFL-VILAB/4M, https://huggingface.co/spaces/EPFL-VILAB/MultiMAE ")
gr.HTML("Placeholder for models small enough to run on cpu here in this space that can assist")
with gr.Tab("Demos on Social Media for inspiration"):
gr.HTML("Social media that shows possiblities")
gr.HTML("https://x.com/blizaine")
with gr.Tab("Basic Game Engine Mechanics"):
gr.HTML("Placeholder for explanations of Player and Game Session")
with gr.Tab("LLM play testing"):
gr.HTML("LLM can read the contents in full and give critiques but they can also play the game if you make a api interface - gradio allows this in the form of gradio client but you can also reroute the user inputs to function calling")
with gr.Tab("Custom JS Config Creator"):
gr.HTML("-- Incomplete -- Companion Space for zerogpu / client api workflow planning for a way to send a zip to the Basic Game Engine at the bottom of https://huggingface.co/spaces/KwabsHug/TestSvelteStatic (Also to test how much can be done majority on cpu)")
with gr.Tab("Simple Config Creator"):
inventory_items = gr.State([])
skills_items = gr.State([])
objectives_items = gr.State([])
targets_items = gr.State([])
with gr.Tabs():
with gr.TabItem("Inventory"):
inventory_type = gr.Textbox(label="Type")
inventory_name = gr.Textbox(label="Name")
inventory_description = gr.Textbox(label="Description")
add_inventory = gr.Button("Add Inventory Item")
inventory_textbox = gr.JSON(label="Inventory Items", value=[])
with gr.TabItem("Skills"):
skills_branch = gr.Textbox(label="Branch")
skills_name = gr.Textbox(label="Name")
skills_learned = gr.Dropdown(choices=["True", "False"], label="Learned")
add_skill_button = gr.Button("Add Skill")
skills_textbox = gr.JSON(label="Skills", value=[])
with gr.TabItem("Objectives"):
objectives_id = gr.Textbox(label="ID")
objectives_name = gr.Textbox(label="Name")
objectives_complete = gr.Dropdown(choices=["True", "False"], label="Complete")
add_objective_button = gr.Button("Add Objective")
objectives_textbox = gr.JSON(label="Objectives", value=[])
with gr.TabItem("Targets"):
targets_name = gr.Textbox(label="Name")
targets_x = gr.Textbox(label="X Coordinate")
targets_y = gr.Textbox(label="Y Coordinate")
targets_collisionType = gr.Textbox(label="Collision Type")
targets_collisiontext = gr.Textbox(label="Collision Text")
add_target_button = gr.Button("Add Target")
targets_textbox = gr.JSON(label="Targets", value=[])
with gr.TabItem("Placeholders for Modal Target"):
gr.HTML("Placeholder")
with gr.TabItem("Placeholders for State Machine Modal Target"):
gr.HTML("Placeholder")
with gr.TabItem("Placeholders for Background"):
gr.HTML("Placeholder")
config_output = gr.JSON(label="Updated Configuration")
@gr.render(inputs=[inventory_items, skills_items, objectives_items, targets_items]) #, outputs=config_output)
def aggregate_config(inventory, skills, objectives, targets):
config = default_config.copy()
config['inventory'] = inventory
config['skills'] = skills
config['objectives'] = objectives
config['targets'] = targets
return config
add_inventory.click(add_inventory_item, inputs=[inventory_items, inventory_type, inventory_name, inventory_description], outputs=inventory_textbox)
add_inventory.click(aggregate_config, inputs=[inventory_items, skills_items, objectives_items, targets_items], outputs=config_output)
add_skill_button.click(add_skill, inputs=[skills_items, skills_branch, skills_name, skills_learned], outputs=skills_textbox)
add_skill_button.click(aggregate_config, inputs=[inventory_items, skills_items, objectives_items, targets_items], outputs=config_output)
add_objective_button.click(add_objective, inputs=[objectives_items, objectives_id, objectives_name, objectives_complete], outputs=objectives_textbox)
add_objective_button.click(aggregate_config, inputs=[inventory_items, skills_items, objectives_items, targets_items], outputs=config_output)
add_target_button.click(add_target, inputs=[targets_items, targets_name, targets_x, targets_y, targets_collisionType, targets_collisiontext], outputs=targets_textbox)
add_target_button.click(aggregate_config, inputs=[inventory_items, skills_items, objectives_items, targets_items], outputs=config_output)
with gr.Tab("Advanced Config Creator"):
gr.HTML("Config with More than text and images")
with gr.Tab("LLM/Robotics as custom controllers Considerations"):
gr.HTML("Controls changed the scope of the game eg. mouse vs keyboard vs console controller vs remote vs touch screen <br>LLM can be vision/surveilance based controler (eg. MGS/GTA camera gauged by an actual camera in real life) or it can be a companion (offline/off console game progrssion ideas)")
gr.HTML("Robotics - https://github.com/OpenTeleVision/TeleVision https://www.stereolabs.com/")
with gr.Tab("Other Considerations"):
with gr.Tab("General"):
gr.HTML("Experiment for https://huggingface.co/spaces/ysharma/open-interpreter/blob/main/app.py inplementation with gradio client api")
gr.HTML("Some conderations for future integration: https://huggingface.co/spaces/dylanebert/3d-arena, https://github.com/fudan-generative-vision/hallo")
gr.HTML("Useful Spaces and links: https://huggingface.co/spaces/artificialguybr/Stable-Audio-Open-Zero https://huggingface.co/spaces/stabilityai/TripoSR https://huggingface.co/spaces/wangfuyun/AnimateLCM-SVD https://huggingface.co/spaces/multimodalart/face-to-all https://huggingface.co/spaces/facebook/MusicGen https://huggingface.co/spaces/Doubiiu/tooncrafter")
gr.HTML("langchain docs as awareness for alot of the integration use cases and providers that are possible - https://python.langchain.com/v0.2/docs/integrations/tools/")
gr.HTML("https://huggingface.co/spaces/linoyts/scribble-sdxl-flash as map planner")
gr.HTML("---------------------------------------Gameplay Ideas-------------------------------")
gr.HTML("https://huggingface.co/spaces/Lin-Chen/ShareCaptioner-Video - game use example police questions a event with multiple eye witnesses needs to give as close to the caption description to win")
with gr.Tab("State management through huggingface?"):
gr.HTML("Huggingface as the login provider? - https://huggingface.co/docs/hub/en/spaces-oauth https://huggingface.co/docs/hub/en/oauth, persistent storage - https://huggingface.co/docs/hub/en/spaces-storage")
with gr.Tab("Finetuning options"):
gr.HTML("Price - https://openpipe.ai/pricing")
with gr.Tab("Backend and/or Hosting?"):
gr.HTML("Prototyping and freemium <br>free api <br>HF Pro subscription")
gr.HTML("GPU (Data privacy) = No Rate limits? - https://replicate.com/pricing, https://lambdalabs.com/service/gpu-cloud https://huggingface.co/pricing#endpoints https://tensordock.com/cloud-gpus")
gr.HTML("Speed - Groq, SambaNova, https://www.etched.com/announcing-etched ")
gr.HTML("Price - Coding - https://aider.chat/docs/leaderboards/ - https://www.deepseek.com/ 0.3 per million - is this per token or chinese character as that means converting code to chinese if possible can save api cost?")
with gr.Tab("Asset loading test"):
gr.HTML("SDXL (linoyts/scribble-sdxl-flash), SVD and Stable Audio used for the test assets (For commercial use need a licence)")
with gr.Row():
gr.Image(value="testmedia/Flash scribble SDXL - random squiggles as roads.webp")
gr.Video(value="testmedia/SVD - random squiggles as roads video 004484.mp4")
gr.Audio(value="testmedia/Stable Audio - Raindrops, output.wav")
gr.HTML("""
<div>
<p>This is a placeholder to test use as an all-media loader for ease of prototyping. Seems gradio HTML doesnt support loading local assets or my file path is wrong</p>
</div>
<div style="display: flex; justify-content: space-between; margin-bottom: 20px;">
<div style="width: 30%;">
<img src="testmedia/Flash scribble SDXL - random squiggles as roads.webp" alt="Random squiggles as roads" style="width: 100%; height: auto;">
</div>
<div style="width: 30%;">
<video width="100%" height="auto" controls>
<source src="testmedia/SVD - random squiggles as roads video 004484.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
<div style="width: 30%;">
<audio controls style="width: 100%;">
<source src="testmedia/Stable Audio - Raindrops, output.wav" type="audio/wav">
Your browser does not support the audio element.
</audio>
</div>
</div>
""")
demo.queue().launch()
|